使用 androidx.lifecycle.ProcessLifecycleOwner
- 引入 androidx.lifecycle
dependencies {
implementation 'androidx.lifecycle:lifecycle-process:2.2.0'
}
- 实现LifecycleObserver子类
import android.util.Log;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
public class ApplicationObserver implements LifecycleObserver
{
private String TAG = this.getClass().getName();
public ApplicationObserver()
{
}
/**
* ON_CREATE 在应用程序的整个生命周期中只会被调用一次
* */
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate()
{
Log.d(TAG, "Lifecycle.Event.ON_CREATE");
}
/**
* 应用程序出现到前台时调用
* */
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart()
{
Log.d(TAG, "Lifecycle.Event.ON_START");
}
/**
* 应用程序出现到前台时调用
* */
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume()
{
Log.d(TAG, "Lifecycle.Event.ON_RESUME");
}
/**
* 应用程序退出到后台时调用
* */
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause()
{
Log.d(TAG, "Lifecycle.Event.ON_PAUSE");
}
/**
* 应用程序退出到后台时调用
* */
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop()
{
Log.d(TAG, "Lifecycle.Event.ON_STOP");
}
/**
* 永远不会被调用到,系统不会分发调用ON_DESTROY事件
* */
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy()
{
Log.d(TAG, "Lifecycle.Event.ON_DESTROY");
}
}
- 在app进程任意一个地方调用以下代码
ProcessLifecycleOwner.get().getLifecycle()
.addObserver(new ApplicationObserver());
- app进程在不断跳转activity的过程中,最终的日志为:
//addObserver调用时才出现下面三行日志
D/com.xxx.ApplicationObserver: Lifecycle.Event.ON_CREATE
D/com.xxx.ApplicationObserver: Lifecycle.Event.ON_START
D/com.xxx.ApplicationObserver: Lifecycle.Event.ON_RESUME
…
…
…
//app退到后台打印下面两行日志
D/com.xxx.ApplicationObserver: Lifecycle.Event.ON_PAUSE
D/com.xxx.ApplicationObserver: Lifecycle.Event.ON_STOP
从源码看是使用了ActivityLifecycleCallbacks,但比我们自己去封装要好用很多。
并且它不需要传入context。看源码,aar包在AndroidManifest.xml添加了一个 ContentProvider,然后通过继承ContentProvider类拿到context