Home » Android » session state – Android — How to properly handle onPause/onResume methods?

session state – Android — How to properly handle onPause/onResume methods?

Posted by: admin June 15, 2020 Leave a comment


I have an app that starts playing sounds and begins/resumes gameplay in the onResume() method, but what I’m noticing is that if my app was the last run application when I put the phone into standby (screen off), and I just press the Menu button to check the time, then the phone starts playing the game and sounds in the background (the app isn’t actually visible, only the screen with the date/time is, yet onResume must have been called in my app). What am I to do here? Is there a way to discern what is reactivating the app, and then add a conditional statement that only starts the game when the app is actually visible?

Here is a snippet from my onResume:

    protected void onResume()
        mySaveGame = Utilities.loadSavegame(this);

        //check the savegame
            //start game using savegame values
            //run the 1st-run components


The only thing I can think of doing to prevent the game from starting whenever the screen gets turned on (even when the app isn’t visible) is to put this.finish() as the last line in onPause()… but that forces you to restart the app every time you want to go back to it because the precess itself was killed (which is fine because my onPause saves persistent data, but it’s not an elegant solution).

Please help.

How to&Answers:

Have you considered switching to onStart() and onStop(), rather than onResume() and onPause()?


I was having the same problem (I had my music player resume/pause at onResume()/onPause()) and the best solution I found is to pause and resume my activity when it is on the foreground which you can get with public void onWindowFocusChanged (boolean hasFocus) callback.

Edit: This in an old and slightly incorrect answer – correct response is described in the Android Developers Blog: making android games that play nice