应用程序进入后台时如何检测以前的活动

mih*_*o39 5 android background application-lifecycle activity-lifecycle

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

onBackground: ActivityA
Run Code Online (Sandbox Code Playgroud)

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

onBackground: ActivityB
Run Code Online (Sandbox Code Playgroud)

我对 ProcessLifecycleObserver 感到困惑

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

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onEnterBackground() {
    }
Run Code Online (Sandbox Code Playgroud)

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

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

有没有人对这种情况有解决方案?

mat*_*dev 3

您应该使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

@Override
protected void onResume() {
    super.onResume();
    MyApplication.getInstance().setCurrentActivity(getClass().getName());
}
Run Code Online (Sandbox Code Playgroud)

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