这是因为从AsyncTask的线程中启动新的Activity会导致问题。一种解决方法是在主线程中启动Intent,即使用runOnUiThread()方法或使用Handler。
以下是使用Handler的示例代码:
private class MyAsyncTask extends AsyncTask
private Context mContext;
public MyAsyncTask(Context context) {
mContext = context;
}
@Override
protected Boolean doInBackground(Void... params) {
// Some long running task here
return true;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result) {
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(mContext, NextActivity.class);
startActivity(intent);
}
});
}
}
}
在上面的代码中,我们在异步任务完成后使用Handler启动了新的Activity。注意在构造函数中传递了Context对象,这是因为我们需要它启动Intent。
另外一种方法是使用runOnUiThread方法来执行UI操作。这也是在主线程中启动Intent的另一种方法。