Android - Close app when home key is pressed

流过昼夜 提交于 2019-12-23 19:24:00

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/13206844/android-close-app-when-home-key-is-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!