Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 638
Ocelot Avatar asked Feb 27 '14 23:02

Ocelot


People also ask

What is onResume () in android?

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.

What is the onPause () method in activity called?

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).

What is onSaveInstanceState () and onRestoreInstanceState () in activity?

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.

What is the difference between onPause and onResume?

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.


2 Answers

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 {
    // ...
}
like image 162
Vitor M. Barbosa Avatar answered Sep 27 '22 18:09

Vitor M. Barbosa


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.

like image 36
Blo Avatar answered Sep 27 '22 18:09

Blo