Search code examples
androidandroid-lifecycle

Is there a way to determine whether onCreate() has just been called prior to onResume()


Is there a way to determine whether onCreate() has just been called prior to onResume().

I wan't to do stuff in onCreate() for view initialization etc, but I don't want to do them again in onResume(), and I'd still like the stuff to be done each time I resume...

Is there a way to determine whether the application has just been created prior to entering the current onResume()?


Solution

  • There is no built-in system call that will tell you whether or not onResume() is being called because the activity was simply paused, or whether it's being called because the activity was entirely re-created. So you will have to track it yourself.

    It's relatively easy to set a boolean in onCreate() and then check it in onResume():

    public class MainActivity extends AppCompatActivity {
    
        private boolean didCreate;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            ...
            this.didCreate = true;
        }
    
        @Override
        protected void onResume() {
            ...
    
            if (didCreate) {
                ...
            } else {
                ...
            }
    
            this.didCreate = false;
        }
    }