Today received an electric plane, on the way the interviewer asked a question, if an activity in the background, because of insufficient memory may be killed, before this, if you want to save the state data, such as the customer fill in some information, such as, which method in which to do.
Onsaveinstancestate is not a life-cycle approach, but it is definitely invoked as long as the activity is killed in a non-active situation.
The Onsaveinstancestate method is called in several places that require attention:
1, Onsaveinstancestate () and onrestoreinstancestate () are not life cycle methods, they are different from life cycle methods such as onCreate (), OnPause (), and they are not necessarily triggered. Onsaveinstancestate () is called when an activity is destroyed by the system when an application encounters an unexpected condition (such as insufficient memory, the user presses the home key directly). However, when the user actively destroys an activity, such as pressing the return key in the app, Onsaveinstancestate () will not be called
2, when the test found that the screen switch when the activity was destroyed, the Onsaveinstancestate () method must be called
3. Call to save the state of each instance before the activity is killed to ensure that the state can be OnCreate (bundle) or Onrestoreinstancestate (bundle) (the incoming bundle parameter is encapsulated by the Onsaveinstancestate) . This method is called before an activity is killed and can revert to its previous state when the activity returns at some point in the future.
4, I in the test, using kill kill process Way kill process Onsaveinstancestate () method is not called
Let's take a look at the following code
Packageim.weiyuan.com.viewutils;ImportAndroid.os.PersistableBundle;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast; Public classMainactivityextendsappcompatactivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); if(Savedinstancestate! =NULL) {Toast.maketext (mainactivity. This, savedinstancestate.getstring ("Data"), Toast.length_long). Show (); }} @Overrideprotected voidOnStop () {Super. OnStop (); LOG.D ("123456", "OnStop is called"); } @Overrideprotected voidOnPause () {Super. OnPause (); LOG.D ("123456", "OnPause is called"); } @Override Public voidonsaveinstancestate (Bundle outstate) {Super. Onsaveinstancestate (outstate); LOG.D ("123456", "Onsaveinstancestate is called"); Outstate.putstring ("Data", "1020223"); }}
Save Android activity Status