5

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 ?

Bulma
  • 990
  • 3
  • 16
  • 35

1 Answers1

3

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

matdev
  • 4,115
  • 6
  • 35
  • 56
  • Thank you for the approach . Let me try it – Bulma Aug 14 '19 at 01:40
  • matdev: It's working fine. Thanks ! However if Activity has 2 state such as State1 and State2. I only want detected this Activity && state == state1 when go to background . How to do that ? – Bulma Aug 14 '19 at 02:01
  • Well, I would add an attribute "currentState" to MyApplication class, and set its value in your Activity. Thus you know both current activity and current state when app goes in background – matdev Aug 14 '19 at 07:41
  • `@OnLifecycleEvent` is deprecated. https://developer.android.com/jetpack/androidx/releases/lifecycle#2.4.0-beta01 – Akito Nov 19 '21 at 15:15