私の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();
}
});
}
これを達成するための最良の方法は何ですか?