Skip to content Skip to sidebar Skip to footer

Android: Detect When An Application As A Whole (not Individual Activities) Is Paused/exited?

One of the Activities in my app starts/binds to a service (also part of my app). I would like that service to continue running as long as the app as a whole is still in the foregr

Solution 1:

The easiest way is to have a singleton which keeps a track of the state of each activity, e.g showing just one activity as an example:

publicclassActivityStates {

    privatestatic  ActivityStates  ref = null;
    privatestaticint firstAct     = ACTIVITY_GONE;

    publicstatic synchronized  ActivityStates getInstance() {
        if (ref == null) {
            ref = new ActivityStates();
        }
        returnref;
    }

    publicintgetFirstAct() {
        return firstAct;
    }

    publicvoidsetFirstAct(int arg) {
        this.firstAct = arg;
    }
}

.. and define some static constants that you can import

publicstaticfinalint ACTIVITY_GONE       = 0;
publicstaticfinalint ACTIVITY_BACKGROUND = 1;
publicstaticfinalint ACTIVITY_FOREGROUND = 2;

then in each activity have a method

privatevoidsetActivityState(int state){
        ActivityStates as = ActivityStates.getInstance();
        as.setFirstAct(state);
}

Then in your onResume(), onPause, onDestroy() you can set the activitiy's state when you enter these methods, e.g in onResume have

setActivityState(ACTIVITY_FOREGROUND)

in onDestroy() have

setActivityState(ACTIVITY_GONE)

Then in you service, or wherever you want , you can use the get methods to find out the state of each activity and decide what to do.

Post a Comment for "Android: Detect When An Application As A Whole (not Individual Activities) Is Paused/exited?"