Search code examples
androidbackgroundactivity-lifecycleapplication-lifecycle

How to detect previous Activity when app go to background


I have 2 activities : ActivityA and ActivityB.
When application go to background I want to detect which Activity has just been on foreground.
For example : Activity A is in foreground -> Click home button -> App go to background

onBackground: ActivityA

Activity B is in foreground -> Click home button -> App go to background

onBackground: ActivityB

I confused about ProcessLifecycleObserver

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onEnterForeground() {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onEnterBackground() {
    }

because of can not detect which Activity here ?

And when I try to use ActivityLifecycleCallbacks it's activity lifecycle , not application lifecycle so background state can not detected here.

Does any one has solution for that case ?


Solution

  • You should use the android.arch.lifecycle package which provides classes and interfaces that let you build lifecycle-aware components.

    For example:

    public class MyApplication extends Application implements LifecycleObserver {
    
        String currentActivity;
    
        @Override
        public void onCreate() {
            super.onCreate();
            ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        private void onAppBackgrounded() {
            Log.d("MyApp", "App in background");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        private void onAppForegrounded() {
            Log.d("MyApp", "App in foreground");
        }
    
        public void setCurrentActivity(String currentActivity){
            this.currentActivity = currentActivity;
        }
    }
    

    In your activities's onResume() method, you can then maintain the currentActivity variable in your MyApplication singleton instance:

    @Override
    protected void onResume() {
        super.onResume();
        MyApplication.getInstance().setCurrentActivity(getClass().getName());
    }
    

    And check the currentActivity attribute value in onAppBackgrounded().