Search code examples
androidandroid-activityonpause

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 foreground, regardless of which Activity is active. But I need to make sure that the service is stopped when the app as a whole is paused (home button/back button).

How can I do that on an application level rather than an Activity level?


Solution

  • 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:

    public class ActivityStates {
    
        private static  ActivityStates  ref = null;
        private static int firstAct     = ACTIVITY_GONE;
    
        public static synchronized  ActivityStates getInstance() {
            if (ref == null) {
                ref = new ActivityStates();
            }
            return ref;
        }
    
        public int getFirstAct() {
            return firstAct;
        }
    
        public void setFirstAct(int arg) {
            this.firstAct = arg;
        }
    }
    

    .. and define some static constants that you can import

    public static final int ACTIVITY_GONE       = 0;
    public static final int ACTIVITY_BACKGROUND = 1;
    public static final int ACTIVITY_FOREGROUND = 2;
    

    then in each activity have a method

    private void setActivityState(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.