Search code examples
androidandroid-activitylifecycleonresumeonpause

Android - execute code onResume and onPause for all the activities of the app?


I'm designing an architecture where the app needs to execute certain set of operations everytime it goes to background (onPause) and a set of operations everytime it comes back to foreground (onResume), irrespective of the activity (for all the activities). Is there a way with which I can achieve this, without having to call those methods in every activity class' onPause and onResume overrides?


Solution

  • Make your own class that extends Activity and add your desired behavior to its onPause and onResume methods.
    Then you extend that class on your activities.

    public class BaseActivity extends Activity {
        @Override
        protected void onPause() {
            // ...
        }
    
        @Override
        protected void onResume() {
            // ...
        }
    }
    
    public class Activity1 extends BaseActivity {
        // ...
    }