Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this questionIn Android, you need to implement the following Activity methods so your application can be restored to its previous state if the OS decides to destroy then recreate your activity:
public void onSaveInstanceState(Bundle savedInstanceState)
public void onRestoreInstanceState(Bundle savedInstanceState)
The examples I've seen of implementing these methods is to use put/getBoolean, put/getInt etc. on the Bundle object (i.e. primitive objects only) to save the application state. This seems hugely error prone way to save your state for a start and I cannot see how this scales to storing complex objects without writing lots of code.
What options do I have for storing/restoring state in a robust and easy to implement fashion?
In case it's important, my application (a game) needs to store about 50 objects, which each store开发者_如何学运维 maybe 5 float variables and some store references to other objects. I don't particularly want to have to write save/restore methods for every class and subclass (maybe about 15 of these) I use. It would be ideal if I could just stick all my state relevant objects in an object called "state" and then just call save/load on "state" to handle everything.
Is using Java serialization an option? I've heard it's very slow, but is that a problem for save/restoring? Could I just write my data to the SD card? To a database?
Take a look at the Bundle class, it supports storing Parcelable and Serializable. So if you implement one of those interfaces for your state object you should be all set.
Also have a look at onRetainNonConfigurationInstance and getLastNonConfigurationInstance. They allow you to let your objects being references by the O.S. while you activity is not running, and get them back when it is re-created. The first of the two methods is an override, the second method shall be called in onCreate. Notice that they are deprecated, but there are other equivalent methods available in new android versions. Also notice that the documentation says
should only be used as an optimization
, and that you must be ready to restore your state otherwise.
Another way to retain objects in memory is subclassing the Application class, as described in this article.
精彩评论