If my app encounters a particular error, I want to end my app without any trace of it remaining in the system. I have already seen many threads on this topic, specially these two.
Is quitting an application frowned upon?
How to quit android application programmatically
The answers are great but the proposed solutions are too tedious and/or unnecessarily complex.
Taking a cue from Neil Traft's answer in the first post above, I have found a perfect solution for such scenarios.
System.exit(0) or android.os.Process.killProcess(android.os.Process.myPid()) both seem to work if you have only one Activity in the app's backstack, else Android just relaunches your app pushing the (top - 1) Activity to the foreground, maybe because Android assumes that the user was interacting with the app and it suddenly "crashed", so he should continue interacting with it.
So, my solution is to first send the app into background using Activity.moveTaskToBack() and then invoke either of the two methods above.
private void terminateApp() {
// TODO: Don't forget to clean up your background threads, services, etc.
// send the app into background, otherwise Android will relaunch the app process if you have multiple Activities in your backstack.
moveTaskToBack(true);
// kill everything running in this process.
System.exit(-1); // or you can use android.os.Process.killProcess(android.os.Process.myPid());
}
I don't see any problem with this approach except that it goes against Android design principles... though this works perfectly when you really, really need it.
Hope this helps someone!