0

I'd like to preserve the state of my activity when it's swiped away from the Recent Apps list, so that when the user launches my app again, it would be in the same state that the user had left it.

Based on my debugging, it looks like my activity's onSaveInstanceState() gets called when the recent apps list is shown, but then, after I swipe away my app and relaunch it, I never get my savedInstanceState back.

How can I preserve my state across this interaction?

Dmitry Brant
  • 7,612
  • 2
  • 29
  • 47
  • Are you saving your state in the saveinstance bundle? if you do, then it will be available in onCreate – Prakash Nadar Jul 09 '15 at 22:54
  • @PrakashNadar: that's exactly the issue -- my savedInstanceState is not passed back to my activity the next time I launch it, after having closed it from the Recent Apps list. – Dmitry Brant Jul 09 '15 at 23:23
  • When the app is swiped away, the saved instance will not be provided, because the activity is killed by the users action.. the user expects the app is being "reset" i.e. like killing an app and restart.. So you should design the app or UX for that expectation and android is making sure thats what will happen. The saved instance will be given to you only when the user switches between application or higher level activity caused the activity to close. If you really really wish to restore the state (which I think is a bad idea) you should probably save the state in some persistent storage. – Prakash Nadar Jul 10 '15 at 14:52

1 Answers1

3

How can I preserve my state across this interaction?

Store that state in a database, SharedPreferences, file, or the cloud, as you see fit. You won't have a process anymore, and so you need to save your state somewhere persistent, then know to reload it later on.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I see... and is there a way to tell whether the activity is being closed due to the recent apps swipe, vs. a normal onSaveInstanceState? – Dmitry Brant Jul 09 '15 at 22:56
  • @DmitryBrant: Well, `onSaveInstanceState()` will have been called *long* before the user removes your task from the overview screen. If you happen to have a service running, it should be called [with `onTaskRemoved()`](http://developer.android.com/reference/android/app/Service.html#onTaskRemoved%28android.content.Intent%29), and your process may survive the task closure. However, I have never tried this, and given the complaints in this area, my guess is that it will not be reliable. Otherwise, no, you are not notified that your task is being closed. – CommonsWare Jul 09 '15 at 23:00
  • Thanks! I suppose a better question would be: How can I "know to reload it later on" if I don't know the reason why my activity was closed? Should I just always use SharedPreferences instead of savedInstanceState? – Dmitry Brant Jul 09 '15 at 23:12
  • @DmitryBrant: I have no way to answer that, sorry. – CommonsWare Jul 09 '15 at 23:16