假设我们有两个活动,Activity1 和 Activity2。
在 Activity1 的 onClick() 方法中,如果按下某个按钮,我们会调用启动 Activity 2:
Intent myIntent = new Intent(Activity1.this, Activity2.class);
Activity1.this.startActivity(myIntent);
在 Activity2 中调用 finish() 并恢复 Activity1 后,我需要在 Activity1 恢复后立即在 Activity1 中显示一个对话框。
之前,我只是在 Activity1 的 onClick() 方法的同一块中调用 showDialog(id) :
public void onClick(View v) {
if(v == addHole){
//...
Intent myIntent = new Intent(Activity1.this, Activity2.class);
Activity1.this.startActivity(myIntent);
showDialog(END_DIALOG_ID);
}
}
问题是,在 Activity1 恢复后,与 END_DIALOG_ID 对应的对话框不可见,但屏幕变暗且无响应(就好像对话框存在一样),直到按下后退键。
我尝试将 showDialog() 调用放入 Activity1 的 onResume() 和 onRestart() 方法中,但这都会导致程序崩溃。
我还尝试在 Activity 2 中创建 AsyncTask 方法,并在其 onPostExecute() 中调用 showDialog(),但该对话框在 Activity 2 中不可见。
private class ShowDialogTask extends AsyncTask<Void, Void, Integer> {
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
protected Integer doInBackground(Void... id) {
//do nothing
return END_DIALOG_ID;
}
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
protected void onPostExecute(Integer id) {
super.onPostExecute(id);
showDialog(id);
}
}
我现在尝试通过调用来实现这一点
Activity1.this.startActivityForResult(myIntent, END_DIALOG_REQUEST);
与 Activity1 中相应的 setResult() 和 onActivityResult() 方法,但似乎应该有更好的实践来实现这一点。我所需要的只是在 Activity2 完成时显示一个对话框。
感谢您的任何帮助,您可以提供。