aqww
aqww

Reputation: 75

What is the purpose of the command APP_CMD_SAVE_STATE ?

Everytime the application loses focus (whether manually by hitting the menu button, or by going to idle ) an APP_CMD_SAVE_STATE command is sent.

In the example shown from the Android API documentation for native activity (https://developer.android.com/reference/android/app/NativeActivity.html) , when this particular command is sent they are saving some sort of "state" inside their android_app .

    // (...)
    switch (cmd) {
    case APP_CMD_SAVE_STATE:
        // The system has asked us to save our current state.  Do so.
        engine->app->savedState = malloc(sizeof(struct saved_state));
        *((struct saved_state*)engine->app->savedState) = engine->state;
        engine->app->savedStateSize = sizeof(struct saved_state);
        break;
    // (...)

If you look in their code, savedState is just a struct holding values. First I thought that we need to save every single value that matters for our app everytime we lose focus, because otherwise the values would all become corrupt or something like that (yeah scary!)

I run a simple test by removing the code snippet above, and fortunately nothing changed, the values of my struct stayed the same after regaining focus even without saving them.

So I was wondering what is the purpose of this command ? Is that something important to consider ?

Upvotes: 5

Views: 623

Answers (1)

Ruslan
Ruslan

Reputation: 19130

The APP_CMD_SAVE_STATE command is sent when your app loses focus. The aim is to make it possible to not only suspend your app, but, if the system has to kill the app to get some resources (e.g. free RAM), the app can be restored seamlessly next time the user returns to it.

If you look in their code, savedState is just a struct holding values.

Yes, from the point of view of the Native Activity, it's just a struct. But this struct is passed to Android in ANativeActivity_onCreate() function that's called via JNI (and usually it's implemented in android_native_app_glue.c from the SDK, which you could alter or replace if you need). Thus, Android will take care of the data when managing apps.

I run a simple test by removing the code snippet above, and fortunately nothing changed, the values of my struct stayed the same after regaining focus even without saving them.

Your test was too soft :) Try opening the Recents screen and close your activity from there: tap the × button or Close All command. The effect will be to kill the app, and you should now find that your data have been wiped unless you use the save-restore mechanism.

Upvotes: 1

Related Questions