简体   繁体   中英

Is onSaveInstanceState called when the android system kills the process to claim memory?

I wrote a small game on android. It has one activity + one fragment. I save the state of the game in Fragment.onSaveInstanceState and restore the state in Fragment.onCreateView.

If I rotate the screen, the game state is preserved properly. However, if I turn off the screen and come back to the game at a later time, sometimes I lose the game state and get a new game instead. Therefore, I wonder if Fragment.onSaveInstanceState is called at all when the system decides to kill a process to recover memory. Also, what is the life time of the stuff that gets saved into the Bundle in Fragment.onSaveInstanceState?

By the way, is there anyway to easily test such a case during development? It'd be terribly inefficient to wait for a day or two for the system to kill it.

Thanks for helping me out!

I wonder if Fragment.onSaveInstanceState is called at all when the system decides to kill a process

Yes.It is called.

I think your issue lies somewhere here.From the documents :

The most significant difference in lifecycle between an activity and a fragment is how one is stored in its respective back stack. An activity is placed into a back stack of activities that's managed by the system when it's stopped, by default (so that the user can navigate back to it with the Back button, as discussed in Tasks and Back Stack). However, a fragment is placed into a back stack managed by the host activity only when you explicitly request that the instance be saved by calling addToBackStack() during a transaction that removes the fragment.

Not sure if this can solve your problem but i think you should keep it in mind while writing your game code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM