MoschDev
MoschDev

Reputation: 671

Android - Close app when home key is pressed

I made this app that works fine, but when i leave the app and open it again it always force closes. how can i make it so when the user presses the home and or back key it will kill the app process?

Making it so when the app is opened again it has a fresh start.

Upvotes: 3

Views: 5374

Answers (1)

Anup Cowkur
Anup Cowkur

Reputation: 20553

You are not supposed to "kill the process". You should handle home button presses and other such interactions that navigate away from your app via the onPause() and onResume() methods.

In your onPause() method, you should save the state of your app. This can range from saved it in Bundles, SharedPreferences, sqlite or whatever form of persistence is appropriate for your app.

In your onResume() method, you should restore the state of your app so that the user is given an illusion that nothing has changed at all.

This is how android handles multitasking and this is how you must accommodate it within your app as well to efficiently and reliable suit your app to the android framework.

I suggest you go through the activity life cycles guide here first:

http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

More on pausing and resuming an activity specifically here:

http://developer.android.com/training/basics/activity-lifecycle/pausing.html

Also, you might want to read up on data storage options here:

http://developer.android.com/guide/topics/data/data-storage.html

Upvotes: 5

Related Questions