2
嘿同胞程序員 我想從我的服務通過broadcastReceiver傳遞一個字符串數組到我的MainActivity。
字符串數組包裝在一個意圖。
但是,當我嘗試從我的意圖
獲得String []時,它是一個對象數組,我不能只使用intent.getStringArrayExtra(String)。
然後我試過這個:Android ClassCastException Object [] to String []
如何將對象數組轉換爲Java中的字符串數組?
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
但doesen`t工作,要麼:/
public class MainActivity extends Activity implements View.OnClickListener {
final String LOG_TAG = "mainActivityLogs";
Button btnStartService;
private int numberOfFinishedTasks = 0;
private List<String> finishedTasksInTheLast60Sec = new ArrayList<>();
private int startedTasks = 0;
private ProgressBar pbService;
private Handler progressHandler = new Handler();
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//results in java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[]
finishedTasksInTheLast60Sec = Arrays.asList(intent.getStringArrayExtra("finishedTasks"));
//results in java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[]
Object[] objectArray = intent.getStringArrayExtra("finishedTasks");
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
finishedTasksInTheLast60Sec = Arrays.asList(stringArray);
numberOfFinishedTasks += finishedTasksInTheLast60Sec.size();
for (String finishedTask : finishedTasksInTheLast60Sec) {
Log.d(LOG_TAG, finishedTask);
}
}
};
此功能在服務文件的MyService和VAR finishedTasks只包含關閉線程的名字:
private void sendBroadcast(List<String> finishedTasks) {
Intent intent = new Intent("myServiceUpdate");
intent.putExtra("finishedTasks", finishedTasks.toArray());
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
我希望你能幫助,如果你需要整個代碼只是文本:)
intent.putStringArrayListExtra( 「finishedTasks」,(ArrayList的)finishedTasks);真的很有用^^非常感謝:) –