当应用程序进入后台时如何检测上一个 Activity

How to detect previous Activity when app go to background

我有 2 个活动:ActivityA 和 ActivityB。
当应用程序进入后台时,我想检测哪个 Activity 刚刚出现在前台。
例如 : Activity A 在前台 -> 单击主页按钮 -> 应用程序转到后台

onBackground: ActivityA

Activity B 在前台 -> 点击主页按钮 -> 应用程序转到后台

onBackground: ActivityB

我对 ProcessLifecycleObserver 感到困惑

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

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

因为这里无法检测到哪个Activity?

当我尝试使用 ActivityLifecycleCallbacks 时,它是 activity 生命周期,而不是应用程序生命周期,因此无法在此处检测到后台状态。

有人对此案例有解决方案吗?

您应该使用 android.arch.lifecycle 包,它提供 类 和让您构建生命周期感知组件的接口。

例如:

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;
    }
}

在您的活动的 onResume() 方法中,您可以在 MyApplication 单例实例中维护 currentActivity 变量:

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

并检查 onAppBackgrounded() 中的 currentActivity 属性值。