26 practical Android skills: persistableMode and Activity persistence,
API 21 adds a new attribute to the Activity. As long as it is set to persistAcrossReboots, the activity has the persistence capability. In addition, a new bundle is required, that is, PersistableBundle.
The persistence here is different from the traditional meaning. Its implementation is in the onSaveInstanceState, onRestoreInstanceState, and onCreate methods of the Activity overload.
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState)public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState)public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState)
The onSaveInstanceState and onRestoreInstanceState methods are a pair of methods to save disasters. They are not in the "normal" Activity lifecycle, and only some unexpected exceptions will trigger them, for example, switching between the screen and the screen, and pressing the Home Key. When the PersistableBundle parameter is added after API 21, these methods have the ability to recover data after the system is shut down and restarted.
The comments of netizens are different, but in any case, this provides us with a convenient way. However, its application scenario is abnormal and will not affect our normal data persistence method. For example, in the pause method, you can perform some operations such as Preferences, file I/O, SQLite database, and ContentProvider.
How to practice it?
You only need to set attributes in activity in Manifest:
android:persistableMode="persistAcrossReboots"
Then you can directly use the preceding three methods in the activity.
Note that the API version is 21 or later.
Verification is a challenge. Because I don't have 5.0 or more system devices, ask for help and simulators. All kinds of problems have come. Whether it's Genymotion or the built-in simulator, the simulator will be stuck during shutdown. Although I see in the log that the program has passed the onSaveInstanceState (Bundle, PersistableBundle ). The simulator is turned on after it is shut down to see the effect. I did not succeed here. If any Prawns have an effect, please let me know.