Everyone who uses apps knows that they are sometimes rather tough to exit. It’s not always because developers don’t care too much about it. Sometimes the api is tricky. If you want the user to exit your application by pressing the back button you need to override the onKeyDown method in your activity. The default implementation would be moveTaskToBack(true), which basically pauses your app and sends it to the background, right? Wrong! Because it only pauses the ui-thread.

Which means any other asynchronous task running keeps running. It wastes resources, leading to a worse user experience and and eventually to uninstalls. Why? Because it’s a unexpected behaviour. I mean don’t get me wrong, it’s perfectly fine if the app goes to the background because the user is getting interrupted by other apps. However if he wants to exit, he should have a possibility to do so. But what then?

Calling finish() often doesn’t do the trick. In that case you can use killProcess with the app process id.

Java

1

2

3

4

5

6

7

8

@Override

publicbooleanonKeyDown(intkeyCode,KeyEvent event){

// cleanup app, save preferences, etc.

android.os.Process.killProcess(android.os.Process.myPid());

// finish(); // not working properly, especially not with asynchronous tasks running

// return moveTaskToBack(true);

returnsuper.onKeyDown(keyCode,event);

}

Done. Just make sure that you have finished all your business before actually killing your app like saving preferences, etc. It will immediatelly close the app.