我已经隔离了在执行 AsyncTask 时显示 ProgressDialog 然后在执行 onPostExecute 时尝试显示 AlertDialog 时遇到的问题。重现的步骤是:
1-运行任务
2-任务完成前按主页按钮
3-当您假设任务完成时返回应用程序
4-AlertDialog 未显示,并且显示了低亮度(如禁用)屏幕。
我发现将 dialog.dismiss() 行移到 onPostExecute 方法的末尾可以解决问题……但这很奇怪,不是吗?
源代码:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickButton(View view) {
new MyAsyncTask(this).execute();
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialog;
Context ctx;
public MyAsyncTask(Context ctx) {
this.ctx = ctx;
}
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(ctx);
dialog.setMessage("Loading");
dialog.show();
}
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void value) {
dialog.dismiss();
AlertDialog.Builder alertbox = new AlertDialog.Builder(ctx);
alertbox.setNeutralButton("OK", null);
alertbox.setMessage("Message");
alertbox.setIcon(android.R.drawable.ic_dialog_alert);
alertbox.show();
// dialog.dismiss(); If I remove it from above and put this line here, it will work ok
}
}
}