Issue
The Android Activity life cycle is giving me a little bit of a headache these days.
I want to store what Activity was the last one displaying, before the app went into background, so that I can restore the correct state when the user restores the app. The problem is that there are multiple possibilities for why the app went to the background and not all perform the same action.
For clarity lets assume I have 3 Activities; A-1, A-2 and A-3 (A-2 is the entry into A-3). A-2 and A-3 are just normal Activities, but A-1 is a dispatcher of sorts. It's the launcher Activity in the manifest file, and the only function it does is to read the SharedPreference
that the other two set in their onPause()
method which basically indicates what the last Activity was, and activates that Activity then calls this.finish()
. Straight forward.
The scenarios are (after all these the user restarts the app, either from background processes list or launcher):
- In A-3 the user taps "Back" button and goes to home screen. This runs
onPause()
, and thenonDestroy()
for the A-3. - In A-3 the user taps "Home" button and goes to home screen. This runs
onPause()
, thenonSavedInstanceState()
for the A-3. - User does either of the two above, then brings up a list of background processes and force kills the app. No code is executed.
- The OS detects that it needs to free memory, so first (of the two) it force kills background processes and then if that's not enough force kills the currently active process.
Now in each scenario the following happens:
- A-1 is launched, and it reads the preferences that were set in
onPause()
and launches A-3 as it should do. Works as designed (but may not be the best way). - A-1 is launched, and does the same thing as above.
- Now things become tricky. When the app is restarted, there is no indication that it was terminated, so A-1 reads the preferences and then launches A-3 when it should launch A-2. This is undesired and breaks the app.
- Is similar to number 3.
My question is, how best to manage application state in situations like this?
Does the bundle passed into onSavedInstanceState
only live while the app is running, so would that be the best way of saving this kind of information only during the "session"
Solution
If I understand correctly what you need, then you could simply override the onBackPressed() of A-3 so that it will modify the SavedPreferences, and when the user re-launches the app it will open A-3.
In the second case, you don't need to save anything, since the app is not closed, it's only put in the background. When the user re-enters the app, the OS will automatically re-activate the last active activity - A-3.
In cases 3 & 4 (probably after it was put in the background as in case 2), if the app is force killed, then you would not have modified the SavedPreferences since the user did not click back.
Answered By - tbkn23
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.