SoFunction
Updated on 2025-03-04

Analysis of the method of Android programming to realize state saving

This article describes the method of Android programming to implement state saving. Share it for your reference, as follows:

1. When we were sending a text message, we had already written hundreds of words. At this time, a call suddenly came. After we answered the call, if we found that the hundreds of words we worked hard had disappeared, it would be very popular, but in fact, these contents were all saved. During the process of answering the call, the activity we send message may be recycled by the system. At this time, the onSaveInstanceState callback method of the Activity will be called, and we can save the status data in this method, and restore the status data in the onCreate method or the callback method provided after 2.0.

2. When we are playing games, we may want to listen to music again, and then we will press the home or back key to exit the game to start the music, and then return to the game. When we return to the game, we find that the state just now is still saved. In this case, we can save the state like this. Save the status data in the onPause method and perform state recovery in the onResume method.

The state of the activity is retained in memory and when resume it starts executing immediately.

When the user is opening a new activity, the current activity may be in a stopped state in memory or may be killed by the system because the new activity requires more memory. However, when the user presses the return key on the new activity, what he wants to see is the original activity interface. If the original activity is recreated, it will be restored to the end of the user seeing it. So how do we do it? Actually, it is not difficult, as mentioned in the previous section,onPause()oronStop()oronDestyroy()Just save the necessary data in it. But now something new emerges from Google:onSaveInstanceState(), you can see its meaning: it is specifically used to save the instance state. This "instance" does not refer to the activity object, but the process it is located, because the destruction of the activity is caused by the killing of the process it is located. onSaveInstanceState() is called when the system feels that it needs to kill the activity. It is passed into a parameter: Bundle. This Bundle can be considered a map, dictionary, etc., and uses "key-value" to save data. So what state is called feeling like you are going to be killed?

Original words of the official document:

Android calls onSaveInstanceState() before the activity becomes vulnerable to being destroyed by the system, but does not bother calling it when the instance is actually being destroyed by a user action (such as pressing the BACK key)

From this sentence, we can see that when an activity becomes "easy" to be destroyed by the system, the activity's onSaveInstanceState will be executed unless the activity is actively destroyed by the user, for example, when the user presses the BACK key. Pay attention to the double quotes above, what is "easy"? The implication is that the activity has not been destroyed, but is just a possibility. What are the possibilities? By rewriting the onXXX methods of all life cycles of an activity, including onSaveInstanceState and onRestoreInstanceState methods, we can clearly know when an activity (assuming activity A) will be executed when it is displayed at the top level of the current task. There are several situations:

1. When the user presses the HOME key. This is obvious. The system does not know how many other programs you want to run after pressing HOME, and naturally does not know whether activity A will be destroyed. Therefore, the system will call onSaveInstanceState to give users the opportunity to save some non-permanent data. The following analysis follows this principle
2. Press and hold the HOME key to select when running other programs.
3. When pressing the power button (off the screen display).
4. When starting a new activity from activity A.
5. When switching the screen direction, for example, when switching from vertical screen to horizontal screen. Before the screen switch, the system will destroy activity A. After the screen switch, the system will automatically create activity A. Therefore, onSaveInstanceState will definitely be executed
In short, the call of onSaveInstanceState follows an important principle, that is, when the system destroys your activity "without your permission", onSaveInstanceState will be called by the system. This is the responsibility of the system, because it must provide an opportunity for you to save your data (of course if you don't save it, you'll do whatever you want).

As for the onRestoreInstanceState method, it should be noted that the onSaveInstanceState method and the onRestoreInstanceState method are called in pairs.

The premise that onRestoreInstanceState is called is that activity A is "really" destroyed by the system, and if it is just stuck in the case where there is such a possibility, the method will not be called., for example, when activity A is being displayed, the user presses the HOME key to return to the main interface, and then the user returns to activity A. In this case, activity A will not be destroyed by the system due to memory reasons, so the onRestoreInstanceState method of activity A will not be executed

In addition, the bundle parameter of onRestoreInstanceState will also be passed to the onCreate method, and you can also choose to restore data in the onCreate method.

So, isn't it possible to save data in onPause()? Why did you come up with such a guy? What is the relationship between them? It turns out that the main purpose of onSaveInstanceState() is to save data related to the status of the activity. When the system kills the activity, if it wants the activity to appear exactly the same as it is now, then it will call onSaveInstanceState(), otherwise it will not be called. So understand this: onSaveInstanceState() is not always called. For example, when the user presses return on an activity, it will not be called, because the user clearly knows that the activity is to be destroyed and does not expect it to look the same next time as it is now (of course, the developer can keep it dead expression, if you have to do this, the system can't do it), so there is no need to call onSaveInstanceState(). Now you should understand:What needs to be saved in onPause(), onStop() and onDestroy() are those that need to be permanently data, rather than saving data used to restore state. There are special methods for state data: onSaveInstanceState()

The data is saved in a Bundle, and the Bundle is permanently renamed by the system. When the activity's onCreate() is called again, the originally saved bundle is passed in to restore the appearance of the last time when it was dying. If the last time the bundle was not saved, it is null.

It's not over yet. If you don't implement your own onSaveInstanceState(), the appearance of the control on the activity may still be saved and restored. It turns out that the activity class has implemented onSaveInstanceState(). In the default implementation of onSaveInstanceState(), all control related methods will be called to save the state of the controls, such as the text entered in EditText, whether CheckBox is selected, etc.However, not all controls can be saved, it depends on whether you assign a name to the control in the layout file (android:id). The famous ones will exist, and the unknown ones will not care about it.

Since there are ready-made ones available, do we still need to implement onSaveInstanceState() yourself? It depends on the situation. If there are variables in your own derived class that affect the UI or the behavior of your program, of course you have to save this variable, so you need to implement it yourself, otherwise it is not necessary, but in most cases you must implement it yourself. By the way,Don't forget to call onSaveInstanceState() of the parent class in your implementation

Note:Since onSaveInstanceState() is not called every time it is destroyed, don't save the data that needs to be permanent. The best place to save those data is: onPause().

The best way to test the state recovery ability of your program is to rotate the screen. Whenever the direction of the screen changes, the current activity will be destroyed by the system and then recreated.

Sample code:

import ;
import ;
import ;
import ;
import ;
public class MainActivity extends Activity {
    //Content input box    private EditText content;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        (savedInstanceState);
        setContentView();
        content=(EditText)findViewById();
        if(savedInstanceState!=null){
            //Get saved data            String saveString=("content");
            //Recover data            (saveString);
        }
    }
    /**
     * Save status data in this method
     */
    @Override
    protected void onPause() {
        ();
        //Get the content of the input box to be saved        String saveString=().toString();
        SharedPreferences sp=("save", Context.MODE_PRIVATE);
        //Save the contents of the input box        ().putString("content", saveString).commit();
    }
    /**
     *Restore status data in this method
     */
    @Override
    protected void onResume() {
        //Get saved content        String saveString=("save", Context.MODE_PRIVATE).getString("content", null);
        //Restore content        (saveString);
        ();
    }
    /**
     * Save status data in this method
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //Get the content of the input box to be saved        String saveString=().toString();
        //Save the contents of the input box        ("content", saveString);
        (outState);
    }
}

For more information about Android related content, please check out the topic of this site:Android programming activity operation skills summary》、《Android View View Tips Summary》、《Summary of Android data skills for operating json format》、《Android development introduction and advanced tutorial》、《Android resource operation skills summary"and"Android control usage summary

I hope this article will be helpful to everyone's Android programming design.