Search code examples
androidandroid-activityandroid-lifecycleonpause

Running code in onPause() or onStop() state of the activity


There is a function in my android app that needs to run every time the user tries to edit his or her profile. There are two parts of edit profile in my app (please don't ask why, it has a very long tedious reason behind it). I need to revert back the changes the user did in the first part of the edit profile if the user decides to cancel everything. I have made a cancel button in the part two of edit profile but my question is, what if user presses the return button or the home button on the device and the app calls the onPause() and on onStop()? how can I run the same code in these two phases of the activities? Anyone out there who knows how to put code in different states on activities? Do I just make a function onPause() and stick the code in there? Would that work?


Solution

  • You can do many things inside both onPause and onStop, just remember to call super.onPause();, super.onStop(); or whatever you need inside each one, just follow the pattern below. Simply add the code to your Activity and you're good to go.

    @Override
    public void onPause() {
        super.onPause();  // Always call the superclass method first
        // Do what you want.
    }
    

    Additionaly, if you want your users to be able to go back on your activity and edit something instead of closing it, you can just call onBackPressed():

    @Override
    public void onBackPressed() {
         super.onBackPressed();
         // You can just call onStop to close the app
         // or do what you want.
    }