Search code examples
androidandroid-activityandroid-lifecycleonresumeandroid-homebutton

Android - Prevent onResume when returning to app after home button


Is there any way to prevent executing code within onResume when returning to an application after the home button has been pressed?
What method is called when the home button is pressed? I could possibly flag something up when home button is pressed?

Thanks


Solution

  • Thanks for the help everyone

    I managed to solve this by creating a boolean, executeOnResume, which I make false everytime onStop() is called and the app is closed. I then check the state of this boolean in onResume() when the app is opened again to choose whether some code should be executed or not.

    onStop()

     //-----application stopped
        @Override
        protected void onStop() {
            super.onStop();
    
            //do not execute onResume code when app opened again
            executeOnResume = false;
        }
    



    onResume()

    //-----application resumed
        @Override
        protected void onResume() {
            super.onResume();
    
            //if true
            if (executeOnResume) {
    
                //do something
            }
    
            else {
    
                //execute onResume true code the next time onResume is called. For example, returning from another activity
    
            }
        }