Search code examples
androidandroid-activityandroid-lifecycleonresumeonpause

Android Pause / Resume


Just looking at this documentation about Activity Lifecycle https://developer.android.com/reference/android/app/Activity.html

it seems to me the onResume callback is not really a real resume. Because it will run if

a. Activity is just created, even if it was not paused. b. Activity was paused and then it's resumed.

I am sending a user to another activity to do stuff, and depending on what the user did on those other activities, when they return, I need to decide whether to reload the app manifest. However, I don't even wanna check if the app was not paused at all! (ie. the user just opened the activity)

Is there a better way to track if the user is really resuming other than creating a variable in onPause that I will check when the user returns?


Solution

  • Declare a boolean flag in your activity:

    boolean hasBeenPaused = false;
    

    Now in your onPause(), set this to true:

    public void onPause(){
       hasBeenPaused = true;
    }
    

    Since your onResume gets called whether or not the app was previously paused, you can now check the boolean and know if it's a fresh start onResume or post pause onResume

    public void onResume(){
    
       if(hasBeenPaused){
          //onPause was called
          //May be because of home button press, recents opened, another activity opened or a call etc... 
       }else{
          //this is a call just after the activity was created
       }
    
    }
    

    If you want to persist, you can even save this variable inside onSaveInstanceState and get the saved state in your onCreate