Reputation: 123
In my app I have the following structure:
Activity A calls activity B, and finishes, removing itself from the stack; Activity B receives an intent from activity A that specifies some action to perform, when these actions are performed, the user will see a message indicating it (still in activity B) .If the user presses the home button the app will go to background, calling "onPause"
and then "onStop"
. All works as expected.
The problem is that if the user leaves the app in background for a few hours, and tries to open the app again (after a few hours) the onCreate
method in activity B will be called with the exact same intent as it received some hours ago from activity A.
(if the user goes back to the app a few minutes after, he will see activity B just like when he left)
What I wanted was that in this case my app would open activity A and not activity B or, activity B but with the message that was on screen when user left.
Looking at the activity life cycle it seems that the app is killing by the OS, all of this makes sense, what I really don't understand is why activity B opens with onCreate
method and the same intent as before.
Upvotes: 2
Views: 1883
Reputation: 95578
Use onSaveInstanceState()
to record the state of ActivityB. Android will call this before it kills the process. When the user returns to the application, it will recreate the process and then recreate whatever activity was on the top of the activity stack (in your case, ActivityB). When it does that, it will pass the saved instance state to the activity as a parameter in the onCreate()
call. You should be able to put something in there so that your ActivityB can tell that it is being recreated after a process kill/restart. In that case, ActivityB could just show the user the message again (which it would have to save in the onSaveInstanceState()
method) or it could just redirect the user back to ActivityA so that he can start all over again.
Upvotes: 1
Reputation: 869
I ran into same problem, I DO NOT know if its the way or its right to do so, but i just changed the Intent
Extra when needed.
intent.putExtra(SEARCH_EXTRA, false);
setIntent(intent);
So your activity does not perform the operation, since it didn't receive what it wants.
Upvotes: 1
Reputation: 12048
This is the expected behaviour described in the Activity lifecycle.
When an activity is started it always receives an Intent
object. The intent that was used to start your activity B was preserved by the OS when your ativity was killed, and resend when the activity was returned to "live".
It's up tu your activity preserve the status and restore it as needed. Based on your problem description I would suggest to use onStop()
so save to SharedPreferences
the activity status and message, and onResume()
to read it back. In onDestroy()
you should clear the preferences to ensure a new clean cycle start.
Regards.
Upvotes: 1