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?
onStart() , onStop() , onRestart() : Called back when the Activity is starting, stopping and re-starting. onPause() , onResume() : Called when the Activity is leaving the foreground and back to the foreground, can be used to release resources or initialize states.
onPause() The system calls this method as the first indication that the user is leaving your activity (though it does not always mean the activity is being destroyed); it indicates that the activity is no longer in the foreground (though it may still be visible if the user is in multi-window mode).
The onSaveInstanceState() method allows you to add key/value pairs to the outState of the app. Then the onRestoreInstanceState() method will allow you to retrieve the value and set it back to the variable from which it was originally collected.
onPause() gets called when your activity is visible but another activity has the focus. onResume() is called immediately before your activity is about to start interacting with the user. If you need your app to react in some way when your activity is paused, you need to implement these methods.
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 {
// ...
}
You could extends your Activities
by a BaseActivity
which extends Activity
, and create the two methods onPause / onResume in it.
See this answer for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With