Android: How to properly exit application when inconsistent condition is unavoidable?
- by Bevor
First of all I already read about all this discussion that it isn't a good idea to manually exit an Android application. But in my case it seems to be needed. I have an AsyncTask which does a lof of operations in background. That means downloading data, saving it to local storage and preparing it for usage in application. It could happen that there is no internet connection or something different happens. For all that cases I have an Exception handling which returns the result. And if there is an exception, the application is unusable so I need to exit it. My question is, do I have to do some unregistration unloading or unbinding tasks or something when I exit the application by code or is System.exit(0) ok? I do all this in an AsyncTask, see my example:
public class InitializationTask extends AsyncTask<Void, Void, InitializationResult> {
private ProcessController processController = new ProcessController();
private ProgressDialog progressDialog;
private Activity mainActivity;
public InitializationTask(Activity mainActivity) {
this.mainActivity = mainActivity;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(mainActivity);
progressDialog.setMessage("Die Daten werden aufbereitet.\nBitte warten...");
progressDialog.setIndeterminate(true); //means that the "loading amount" is not measured.
progressDialog.setCancelable(false);
progressDialog.show();
};
@Override
protected InitializationResult doInBackground(Void... params) {
return processController.initializeData();
}
@Override
protected void onPostExecute(InitializationResult result) {
super.onPostExecute(result);
progressDialog.dismiss();
if (!result.isValid()) {
AlertDialog.Builder dialog = new AlertDialog.Builder(mainActivity);
dialog.setTitle("Initialisierungsfehler");
dialog.setMessage(result.getReason());
dialog.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
//TODO cancel application
System.exit(0);
}
});
dialog.show();
}
}
}