我在执行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
}
}
}