我的 android 应用程序首先加载所有必要的数据,同时显示一个加载对话框:
// Load data in background, while updating the loading dialog.
(new AsyncTask<Void, String, Void>() {
    @Override
    protected Void doInBackground(Void... params) {
        publishProgress(getString(R.string.loading_a));
        if!(loadA())
            showErrorDialogAndQuit();
        publishProgress(getString(R.string.loading_b));
        if(!loadB())
            showErrorDialogAndQuit();
        publishProgress(getString(R.string.loading_c));
        if(!loadC())
            showErrorDialogAndQuit();
        return null;
    }
    protected void onProgressUpdate(String... progress) {
        dialog.setMessage(progress[0]);
    }
    protected void onPostExecute(Void result) {
        // Update the UI.
        updateUI();
        dialog.dismiss();
    }
}).execute();
方法loadA()、loadB()和loadC()可能会失败,返回 false。此时,我希望显示一条错误消息,并在方法中退出应用程序showErrorDialogAndQuit()。
我尝试按如下方式创建它,但在应用程序退出后它似乎总是抛出错误,这与加载对话框不再有窗口有关。
public void showErrorDialogAndQuit() {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            AlertDialog aDialog = new AlertDialog.Builder(MyActivity.this).setMessage("Fatal error.").setTitle("Error")
                    .setNeutralButton("Close", new AlertDialog.OnClickListener() {
                        public void onClick(final DialogInterface dialog, final int which) {
                            // Exit the application.
                            finish();
                        }
                    }).create();
            aDialog.setOnKeyListener(new OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    // Disables the back button.
                    return true;
                }
            });
            aDialog.show();
        }
    });
}
实现这一目标的最佳方法是什么?