概述
Lifecycle是感应Activity、Fragment、Service、Application 的生命周期状态的变化的一个组件,可以减少 Activity或者Fragment的代码逻辑压力
二:Lifecycle的感应生命周期 和 Activity真正的生命周期,还有Application注册registerActivityLifecycleCallbacks的调用时期对比
- 现在Activity里面打印各个方法
class LifeDemoActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
Log.e(TAG, "onCreate --之前")
super.onCreate(savedInstanceState)
Log.e(TAG, "onCreate --之后")
setContentView(R.layout.activity_life_demo)
lifecycle.addObserver(ActivityObserver())
}
override fun onStart() {
Log.e(TAG, "onStart --之前")
super.onStart()
Log.e(TAG, "onStart --之后")
}
override fun onRestart() {
Log.e(TAG, "onRestart --之前")
super.onRestart()
Log.e(TAG, "onRestart --之后")
}
override fun onResume() {
Log.e(TAG, "onResume --之前")
super.onResume()
Log.e(TAG, "onResume --之后")
}
override fun onPause() {
Log.e(TAG, "onPause --之前")
super.onPause()
Log.e(TAG, "onPause --之后")
}
override fun onStop() {
Log.e(TAG, "onStop --之前")
super.onStop()
Log.e(TAG, "onStop --之后")
}
override fun onDestroy() {
Log.e(TAG, "onDestroy --之前")
super.onDestroy()
Log.e(TAG, "onDestroy --之后")
}
companion object {
val TAG = "LifeDemoActivity";
fun startMe(activity: Activity) {
activity.startActivity(Intent(activity, LifeDemoActivity::class.java))
}
}
}
- 在 LifecycleObserver 打印各个方法
class ActivityObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
Log.e(LifeDemoActivity.TAG,"LifecycleObserver --onCreate")
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() {
Log.e(LifeDemoActivity.TAG,"LifecycleObserver --onStart")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
Log.e(LifeDemoActivity.TAG,"LifecycleObserver --onResume")
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
Log.e(LifeDemoActivity.TAG,"LifecycleObserver --onPause")
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {
Log.e(LifeDemoActivity.TAG,"LifecycleObserver --onStop")
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
Log.e(LifeDemoActivity.TAG,"LifecycleObserver --onDestroy")
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun onAny() {
}
}
- 在Application里面注册Activity的监听
class MyApplication:Application() {
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(object :ActivityLifecycleCallbacks{
override fun onActivityPaused(activity: Activity?) {
Log.e(LifeDemoActivity.TAG,"Application --onActivityPaused")
}
override fun onActivityResumed(activity: Activity?) {
Log.e(LifeDemoActivity.TAG,"Application --onActivityResumed")
}
override fun onActivityStarted(activity: Activity?) {
Log.e(LifeDemoActivity.TAG,"Application --onActivityStarted")
}
override fun onActivityDestroyed(activity: Activity?) {
Log.e(LifeDemoActivity.TAG,"Application --onActivityDestroyed")
}
override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {
Log.e(LifeDemoActivity.TAG,"Application --onActivitySaveInstanceState")
}
override fun onActivityStopped(activity: Activity?) {
Log.e(LifeDemoActivity.TAG,"Application --onActivityStopped")
}
override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
Log.e(LifeDemoActivity.TAG,"Application --onActivityCreated")
}
});
}
}
然后看打印
可以看出来,先在Activity之前调用,之后 Application中调用,然后再Activity之后调用,然后就是LifecycleObserver。
onCreate --之前
Application --onActivityCreated
onCreate --之后
LifecycleObserver --onCreate
onStart --之前
Application --onActivityStarted
onStart --之后
LifecycleObserver --onStart
onResume --之前
Application --onActivityResumed
onResume --之后
LifecycleObserver --onResume
之后开始按返回键,注意下面的会LifecycleObserver先走
LifecycleObserver --onPause
onPause --之前
Application --onActivityPaused
onPause --之后
LifecycleObserver --onStop
onStop --之前
Application --onActivityStopped
onStop --之后
LifecycleObserver --onDestroy
onDestroy --之前
Application --onActivityDestroyed
onDestroy --之后
三。监听app在前后台的-ProcessLifecycleOwner
使用 ProcessLifecycleOwner.get().lifecycle.addObserver(ApplicationObserver()),
- Lifecycle.Event.ON_CREATE 在app中只调用一次,比如当在第一个页面按返回键的时候,退出到桌面,此时进程是没有被杀死的,再打开app还是不会走这类
- Lifecycle.Event.ON_START 和 Lifecycle.Event.ON_RESUME 是成对出现的,都可以认为在前台
- Lifecycle.Event.ON_PAUSE 和 Lifecycle.Event.ON_STOP 是成对出现的,都可以认为在后台
- Lifecycle.Event.ON_DESTROY 永远不会走到这里
class ApplicationObserver : LifecycleObserver {
/**
* 在app中只调用一次,当在第一个页面按返回键的时候,此时进程没有被杀死,此时再打开app,也是不会走此方法
*/
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
Log.e(LifeDemoActivity.TAG,"ApplicationObserver --onCreate")
}
/**
* 应用在前台 对于Application onStart和onResume 都是成对出现的
*/
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() {
Log.e(LifeDemoActivity.TAG,"ApplicationObserver --onStart")
}
/**
* 应用在前台
*/
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
Log.e(LifeDemoActivity.TAG,"ApplicationObserver --onResume")
}
/**
* 应用在后台 对于Application onPause和ON_STOP 都是成对出现的
*/
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
Log.e(LifeDemoActivity.TAG,"ApplicationObserver --onPause")
}
/**
* 应用在后台
*/
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {
Log.e(LifeDemoActivity.TAG,"ApplicationObserver --onStop")
}
/**
* 这里永远也走不到
*/
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
Log.e(LifeDemoActivity.TAG,"ApplicationObserver --onDestroy")
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun onAny() {
}
}
四。先实现一个简单的观察者模式,因为Lifecycle用的就是观察者模式
具体的demo地址github
抽象被观察者角色:也就是一个抽象主题,它把所有对观察者对象的引用保存在一个集合中,每个主题都可以有任意数量的观察者。抽象主题提供一个接口,可以增加和删除观察者角色。一般用一个抽象类和接口来实现。
4.1 先定义一个被观察者接口
interface Observable {
/**
* 添加观察者
*/
fun addObserver(observe:Observe)
/**
* 移除观察者
*/
fun removeObserver(observe:Observe)
/**
* 通知观察者
*/
fun notifyObserve()
}
4.2 定义一个观察者接口
interface Observe {
// 收到消息之后的数据
fun received(message:String)
}
4.3 定义一个被观察者接实现类
class ObservableImpl : Observable {
private val arrayList = ArrayList<Observe>()
override fun addObserver(observe: Observe) {
if (!arrayList.contains(observe)) {
arrayList.add(observe)
}
}
override fun removeObserver(observe: Observe) {
arrayList.remove(observe)
}
override fun notifyObserve() {
for (observe in arrayList) {
observe.received("收到信息了")
}
}
}
4.4 定义一个观察者接实现类
class ObserveImpl(var name:String):Observe {
override fun received(message: String) {
System.out.println("${name}---${message}")
}
}
4.5 开始测试
class ExampleUnitTest {
@Test
fun testObserve() {
var observable: Observable = ObservableImpl()
var observeZhang: Observe = ObserveImpl("张三")
var observeLi: Observe = ObserveImpl("李四")
var observeWang: Observe = ObserveImpl("王五")
observable.addObserver(observeZhang)
observable.addObserver(observeLi)
observable.addObserver(observeWang)
observable.notifyObserve()
observable.removeObserver(observeZhang)
println("")
println("---去除张三----")
println("")
observable.notifyObserve()
}
}
测试结果是
五。源码解析
getLifecycle().addObserver(ActivityObserver())
在ComponentActivity中的getLifecycle() 获得的是一个 mLifecycleRegistry,mLifecycleRegistry是ComponentActivity的一个成员变量,handleLifecycleEvent()方法就是用来通知观察者生命周期的变化的
// 被观察者
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
// 设置状态通知观察者
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
然后下面看一看什么地方在调用 handleLifecycleEven,先看Activity的调用流程
5.1 先看监听 Activity 的调用时期
看看 ComponentActivity 的onCreate()方法 ,里面初始化了一个ReportFragment,这是一个透明的Fragment,,然后用这个Fragment来监控Activity的生命周期,像透明的Fragment的,当我们请求6.0权限的时候RxPermission,还有Glide监听Activity生命周期的时候也是用的透明的Fragment。然后我们在看一下ProcessLifecycleOwner的里面代码,然后我们看一下 ,这里面有两块代码,都是用来感知生命周期的,不知道具体为啥注册两种方案。
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
activity.registerActivityLifecycleCallbacks(
new LifecycleCallbacks());
}
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
// Hopefully, we are the first to make a transaction.
manager.executePendingTransactions();
}
}
我们直接看一下 api 大于29的办法吧,注册activity生命周期的方法,另一个就是监听Fragment的生命周期,来调用
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
@Override
public void onActivityCreated(@NonNull Activity activity,
@Nullable Bundle bundle) {
}
@Override
public void onActivityPostCreated(@NonNull Activity activity,
@Nullable Bundle savedInstanceState) {
// 在系统onCreate之后调用了 通知观察者的方法,是 Lifecycle.Event.ON_CREATE
dispatch(activity, Lifecycle.Event.ON_CREATE);
}
@Override
public void onActivityStarted(@NonNull Activity activity) {
}
@Override
public void onActivityPostStarted(@NonNull Activity activity) {
// 在系统onStart之后调用了 通知观察者的方法,是 Lifecycle.Event.ON_START
dispatch(activity, Lifecycle.Event.ON_START);
}
@Override
public void onActivityResumed(@NonNull Activity activity) {
}
@Override
public void onActivityPostResumed(@NonNull Activity activity) {
// 在系统onResume之后调用了 通知观察者的方法,是 Lifecycle.Event.ON_RESUME
dispatch(activity, Lifecycle.Event.ON_RESUME);
}
@Override
public void onActivityPrePaused(@NonNull Activity activity) {
// 在系统onPause之前调用了 通知观察者的方法,是 Lifecycle.Event.ON_PAUSE
dispatch(activity, Lifecycle.Event.ON_PAUSE);
}
@Override
public void onActivityPaused(@NonNull Activity activity) {
}
@Override
public void onActivityPreStopped(@NonNull Activity activity) {
// 在系统onStop之前调用了 通知观察者的方法,是 Lifecycle.Event.ON_STOP
dispatch(activity, Lifecycle.Event.ON_STOP);
}
@Override
public void onActivityStopped(@NonNull Activity activity) {
}
@Override
public void onActivitySaveInstanceState(@NonNull Activity activity,
@NonNull Bundle bundle) {
}
@Override
public void onActivityPreDestroyed(@NonNull Activity activity) {
// 在系统onDestroye之前调用了 通知观察者的方法,是 Lifecycle.Event.ON_DESTROY
dispatch(activity, Lifecycle.Event.ON_DESTROY);
}
@Override
public void onActivityDestroyed(@NonNull Activity activity) {
}
}
然后我们看一下dispatch的方法,这里调用的getLifecycle() 就是我们 ComponentActivity中的mLifecycleRegistry,通知观察者改变数据
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
if (activity instanceof LifecycleOwner) {
// 这里调用的getLifecycle() 就是我们 ComponentActivity中的mLifecycleRegistry
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
5.2 同理 Fragment 也是在对应的生命周期加的 handleLifecycleEven(),准确的是 在 perform方法,比如onCreate() 是在 performCreate()中 ,前面都有个perform
5.3 监听Application的生命周期方法
这个就有点麻烦了,先从 ProcessLifecycleOwner 的源码入手 ProcessLifecycleOwner.get().lifecycle.addObserver(ApplicationObserver()),
private static final ProcessLifecycleOwner sInstance = new ProcessLifecycleOwner();
// 监听整个app的生命周期,假如本app有多个进程的话,不会监听其他进程
@NonNull
public static LifecycleOwner get() {
return sInstance;
}
static void init(Context context) {
sInstance.attach(context);
}
由上面的源码可以看出来,ProcessLifecycleOwner是一个单利,然后他也没有在构造方法内去初始化东西,然后我们看他有个init(Context context)方法去初始化,我们看一下点进去看一下那里调用的.
public class ProcessLifecycleOwnerInitializer extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
return true;
}
在debug的AndroidManifest 或者 打正式包的AndroidManifest会自动注册这个ContentProvider
<provider
android:name="androidx.lifecycle.ProcessLifecycleOwnerInitializer"
android:authorities="com.nzy.mvvmsimple.lifecycle-process"
android:exported="false"
android:multiprocess="true" />
可以看到他是在 ContentProvider 中的 onCreate中去初始化的,然后 ContentProvider 是在启动app,在ActivityThread里面创建的。这个里面初始化了两个东西,先看一下
LifecycleDispatcher.init(getContext());
class LifecycleDispatcher {
private static AtomicBoolean sInitialized = new AtomicBoolean(false);
static void init(Context context) {
if (sInitialized.getAndSet(true)) {
return;
}
// 在这里用Application注册了Activity的生命周期回调
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
}
@SuppressWarnings("WeakerAccess")
@VisibleForTesting
static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
// 在Activity的onCreate中注入了一个ReportFragment
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
//
ReportFragment.injectIfNeededIn(activity);
}
}
private LifecycleDispatcher() {
}
}
LifecycleDispatcher的主要作用是在每个Activity中注入了一个透明的Fragment,然后用这个Fragment来监控Activity的生命周期,像透明的Fragment的,当我们请求6.0权限的时候RxPermission,还有Glide监听Activity生命周期的时候也是用的透明的Fragment。然后我们在看一下ProcessLifecycleOwner的里面代码
private static final ProcessLifecycleOwner sInstance = new ProcessLifecycleOwner();
static void init(Context context) {
sInstance.attach(context);
}
void attach(Context context) {
mHandler = new Handler();
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
Application app = (Application) context.getApplicationContext();
app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
@Override
public void onActivityPreCreated(@NonNull Activity activity,
activity.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
@Override
public void onActivityPostStarted(@NonNull Activity activity) {
activityStarted();
}
@Override
public void onActivityPostResumed(@NonNull Activity activity) {
activityResumed();
}
});
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT < 29) {
ReportFragment.get(activity).setProcessListener(mInitializationListener);
}
}
@Override
public void onActivityPaused(Activity activity) {
activityPaused();
}
@Override
public void onActivityStopped(Activity activity) {
activityStopped();
}
});
}
void activityStarted() {
// start数相加,当start==1的时候,也就是又一个Activity走到onStart()时候,就发送Lifecycle.Event.ON_START事件。并且把一个标志位 设置成false,下个Activity走到onStart()不会在调用
mStartedCounter++;
if (mStartedCounter == 1 && mStopSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
mStopSent = false;
}
}
void activityResumed() {
mResumedCounter++;
if (mResumedCounter == 1) {
if (mPauseSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
mPauseSent = false;
} else {
mHandler.removeCallbacks(mDelayedPauseRunnable);
}
}
}
void activityPaused() {
mResumedCounter--;
if (mResumedCounter == 0) {
mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS);
}
}
void activityStopped() {
mStartedCounter--;
dispatchStopIfNeeded();
}
void dispatchPauseIfNeeded() {
if (mResumedCounter == 0) {
mPauseSent = true;
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
}
}
void dispatchStopIfNeeded() {
if (mStartedCounter == 0 && mPauseSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
mStopSent = true;
}
}
这里用了计数相加法 ,用来记录每个Activity的生命周期,比如当发送这个的 Lifecycle.Event.ON_START,start数相加,当start==1的时候,也就是又一个Activity走到onStart()时候,就发送Lifecycle.Event.ON_START事件。并且把一个标志位 设置成false,下个Activity走到onStart()不会在调用