Search code examples
androidandroid-activitydestroyonkeydown

android: pause (close) app so that it is re-opened on the same state


I have an app that records some data (time, user’s gps position etc). Now I want to implement this: when user presses back I pop an alertdialog with two options to “pause” or “exit”. I can do that overriding the onKeyDown method. Now “exit” should mean to close the app and the recording of data is stopped. “pause” should mean that the user can close the app for some minutes and then continue when he re-opens from the exactly same point.

I have done some research, but I got confused on many points:

1) Can I guarantee somehow that the activity gets paused and not destroyed? Moreover finish() destroys the activity. Is there some method to pause it programmatically?

2) If only the onPause is called then when app is opened again shouldn’t start from onResume? So all the counters (which I normally set to zero in the onCreate method) should remain in the last state?

3) One obvious way would be to save the whole state of the counters etc in the device db and then restore it when user re-opens. But it is more painful, and most of all this a good practice?

Thanks in advance for any clarification!


Solution

  • you Can't guarantee that the activity never will be destroyed, cause if the system needs memory or something it will automaticaly close some apps, but you can save your state of your app in a variable "savedinstancestate" witch you can save in a persistance database, or in the SD.

    If you want to pause the app you should call the "onPause" method and then call the method "onResume" if you do this, you will be able to restart your app from the last state.

    if you want to stop your app, only call the method "onStop"

    i'm not a master of Android, but i hope that this answer could throw some light about your question ;)