Android How to programmatically close an app by pressing back button properly.

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.

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.

See also activitys-threads-memory-leaks

Facebook comments:

comments

1 Comment

  1. Thank You Jan,
    as you said the AsyncActivity will remain even after calling finish(). your solution works with device CPU directly. i mean it’s like assembly command.

Leave a Reply