您不能在非 ui 线程中显示对话框。您可以将活动引用传递给异步任务。要处理这种情况,您可以尝试在 doInBackground 中捕获异常并在 onPostExecute 中重新抛出它
例如
private class MyAsyncTaskTask extends AsyncTask<...> {
private Activity ownerActivity;
private Exception exceptionToBeThrown;
public MyAsyncTaskTask(Activity activity) {
// keep activity reference
this.ownerActivity = activity;
}
protected Long doInBackground(...) {
try {
...
} catch (Exception e) {
// save exception and re-thrown it then.
exceptionToBeThrown = e;
}
}
protected void onPostExecute(...) {
// Check if exception exists.
if (exceptionToBeThrown != null) {
ownerActivity.handleXXX();
throw exceptionToBeThrown;
}
}
}
如果您的异步任务在 Acvitiy 类中,那么您可以直接访问它,例如,
public class MyActivity extends Activity {
...
AsyncTask<...> task = new AsyncTask<...>() {
public void onPostExecute(...) {
// Access activity directly
MyActivity.this.xxx()
}
}
}