您可以做的一个选择是拥有一个 BaseActivity ,您的所有活动都从该 BaseActivity 扩展,它有一个成员变量来保存您的前台活动。当您的 AsyncTask 完成时,您可以使用 BaseActivity 中的 Activity 引用来显示您的 AlertDialog。例如:
文件:MyBaseActivity.java
public class MyBaseActivity extends Activity {
protected static Activity sForegroundActivity;
class MyAsyncTask extends AsyncTask<Object, Object, Object> {
@Override
protected Object doInBackground(Object... params) {
// do stuff
return null;
}
protected void onPostExecute(Object result) {
// cover the edge case where the AsyncTask finished while we are transitioning
// between activities and we have not set the foreground activity instance
if(sForegroundActivity == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(sForegroundActivity);
builder.setMessage("Showing Dialog in Foreground Activity");
builder.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// handle ok clicked
}
});
builder.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// handle cancel clicked
}
});
builder.create().show();
}
}
@Override
public void onStart() {
super.onStart();
sForegroundActivity = this;
}
@Override
public void onStop() {
super.onStop();
sForegroundActivity = null;
}
}
文件:ActivityA.java
public class ActvityA extends MyBaseActivity {
private void startAsyncTaskAndGoToActivityB() {
// start our AsyncTask
new MyAsyncTask().execute();
// go to ActivityB. When the AsyncTask finishes, the AlertDialog will be shown in ActivityB
Intent myIntent = new Intent(this, ActivityB.class);
startActivity(myIntent);
}
}