Search code examples
androidandroid-lifecycleandroid-viewmodel

android - is the activity restored from an inactive app state


I am loading data from the web and storing it in a ViewModel. Thus, when the orientation of the device changes, the data is retained and I do not have to reload it from the web. However if the app gets into an inactive state (due to other apps needing memory) the data inside the ViewModel will get deleted and I will need to reload it upon restoring the activity/fragment. This problem can of course be circumvented by saving some flag in the onSaveInstanceState() method and reloading the data from the web if we find the flag in our savedInstanceState bundle when recreating the activity/fragment. This however does not differentiate between coming back from inactivity and a simple orientation change. Thus every time I'd turn the device the data would unnecessarily be reloaded from the server.

Is there a way to know if the activity/fragment was restored from an inactive state?


Solution

  • Is there a way to know if the activity/fragment was restored from an inactive state?

    You can leverage the fact that variables will return to their default (uninitialized) value when your app's process is killed, and combine that with normal savedInstanceState logic.

    public class MainActivity extends AppCompatActivity {
    
        private static boolean processWasAliveTheWholeTime;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            if (savedInstanceState == null) {
                processWasAliveTheWholeTime = true;
            } else {
                if (!processWasAliveTheWholeTime) {
                    // if savedInstanceState is not null, that means we're being recreated.
                    // the only way processWasAliveTheWholeTime could be false is if our process was killed.
                }
            }
        }
    }