Lifecycle是Jetpack架构组件中用来感知生命周期的组件,使用Lifecycle可以帮助开发者写出与生命周期相关且更简洁、更易维护的代码。
项目中添加Lifecycle组件的依赖项:
build.gradle(:app) 1 2 3 4 5 6 dependencies { ... def lifecycle_version = "2.5.0" implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version" ... }
Lifecycle Lifecycle 组件可以让任何一个类都能轻松感知到 Activity 的生命周期,同时又不需要在 Activity 中编写大量的逻辑处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 class MyObserver (val lifecycle: Lifecycle):LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_START) fun activityStart () { Log.e("MyObserver" ,"activityStart" ) Log.e("MyObserver" ,lifecycle.currentState.toString()) } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun activityStop () { Log.e("MyObserver" ,"activityStop" ) } }
OnLifecycleEvent注解方法中,Lifecycle.Event的枚举如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 public enum Event { ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DESTROY, ON_ANY; ... }
几个状态分别对应Activity的生命周期,最后一个状态则表示可对应Activity的任意生命周期。
在Activity中注册MyObserver:
1 2 3 4 5 6 7 8 9 10 11 12 13 class MainActivity : AppCompatActivity () { override fun onCreate (savedInstanceState: Bundle ?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) lifecycle.addObserver(MyObserver(lifecycle)) } }
追溯源码,AppCompatActivity 继承自androidx.core.app.ComponentActivity,而ComponentActivity实现了LifecycleOwner接口,所以可以直接调用getLifecycle()。
ComponentActivity源码如下:
1 2 3 4 5 public class ComponentActivity extends Activity implements LifecycleOwner , KeyEventDispatcher.Component { ... }
LifecycleOwner源码如下:
1 2 3 4 5 6 7 8 9 public interface LifecycleOwner { @NonNull Lifecycle getLifecycle () ; }
除了ComponentActivity外,其子类如androidx.fragment.app.FragmentActivity、androidx.appcompat.app.AppCompatActivity、androidx.fragment.app.Fragment中都是可以直接使用Lifecycle的。
自定义LifecycleOwner 如果当前父类未实现LifecycleOwner接口,比如android.app.Activity,则需要自定义LifecycleOwner。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class MyActivity : Activity (), LifecycleOwner { private lateinit var lifecycleRegistry: LifecycleRegistry override fun onCreate (savedInstanceState: Bundle ?) { super .onCreate(savedInstanceState) lifecycleRegistry = LifecycleRegistry(this ) lifecycleRegistry.markState(Lifecycle.State.CREATED) } public override fun onStart () { super .onStart() lifecycleRegistry.markState(Lifecycle.State.STARTED) } override fun getLifecycle () : Lifecycle { return lifecycleRegistry } }
还可以通过Lifecycle的getCurrentState方法主动获取当前Activity的生命周期状态,getCurrentState会返回如下种类的State:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 public enum State { DESTROYED, INITIALIZED, CREATED, STARTED, RESUMED; public boolean isAtLeast (@NonNull State state) { return compareTo(state) >= 0 ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 class MainActivity : BaseActivity () { override fun onCreate (savedInstanceState: Bundle ?) { super .onCreate(savedInstanceState) Log.d("TAG" ,"onCreate: " +lifecycle.currentState) } override fun onStart () { super .onStart() Log.d("TAG" ,"onStart: " +lifecycle.currentState) } override fun onResume () { super .onResume() Log.d("TAG" ,"onResume: " +lifecycle.currentState) } override fun onPause () { super .onPause() Log.d("TAG" ,"onPause: " +lifecycle.currentState) } override fun onStop () { super .onStop() Log.d("TAG" ,"onStop: " +lifecycle.currentState) } override fun onDestroy () { super .onDestroy() Log.d("TAG" ,"onDestroy: " +lifecycle.currentState) } }
State返回值与Activity生命周期的对应关系如下:
源码分析 androidx.core.app.ComponentActivity 中默认实现了LifecycleOwner接口,getLifecycle返回的实际是一个LifecycleRegistry对象
ComponentActivity 1 2 3 4 5 6 7 8 private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry (this );@NonNull @Override public Lifecycle getLifecycle () { return mLifecycleRegistry; }
LifecycleRegistry是Lifecycle的唯一实现类
LifecycleRegistry 1 public class LifecycleRegistry extends Lifecycle {}
Lifecycle抽象类中定义了添加观察者(addObserver)、移除观察者(removeObserver)、以及获取当前状态(getCurrentState)的方法,可见这是典型的观察者模式。
查看androidx.core.app.ComponentActivity
1 2 3 4 5 6 7 @SuppressLint("RestrictedApi") @Override protected void onCreate (@Nullable Bundle savedInstanceState) { super .onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this ); }
查看ReportFragment的injectIfNeededIn方法
1 2 3 4 5 6 7 8 9 10 11 12 13 public static void injectIfNeededIn (Activity activity) { if (Build.VERSION.SDK_INT >= 29 ) { LifecycleCallbacks.registerIn(activity); } android.app.FragmentManager manager = activity.getFragmentManager(); if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null ) { manager.beginTransaction().add(new ReportFragment (), REPORT_FRAGMENT_TAG).commit(); manager.executePendingTransactions(); } }
在ReportFragment的生命周期方法中都会执行dispatch方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 @Override public void onActivityCreated (Bundle savedInstanceState) { super .onActivityCreated(savedInstanceState); dispatchCreate(mProcessListener); dispatch(Lifecycle.Event.ON_CREATE); } @Override public void onStart () { super .onStart(); dispatchStart(mProcessListener); dispatch(Lifecycle.Event.ON_START); } @Override public void onResume () { super .onResume(); dispatchResume(mProcessListener); dispatch(Lifecycle.Event.ON_RESUME); } @Override public void onPause () { super .onPause(); dispatch(Lifecycle.Event.ON_PAUSE); } @Override public void onStop () { super .onStop(); dispatch(Lifecycle.Event.ON_STOP); } @Override public void onDestroy () { super .onDestroy(); dispatch(Lifecycle.Event.ON_DESTROY); mProcessListener = null ; }
查看dispatch方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 @SuppressWarnings("deprecation") static void dispatch (@NonNull Activity activity, @NonNull Lifecycle.Event event) { if (activity instanceof LifecycleRegistryOwner) { ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event); return ; } if (activity instanceof LifecycleOwner) { Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle(); if (lifecycle instanceof LifecycleRegistry) { ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); } } }
dispatch方法最终都会进入到LifecycleRegistry的handleLifecycleEvent方法中,通过handleLifecycleEvent设置状态并通知观察者,Activity便能监听到生命周期的变化了。
备注 参考资料 :
使用生命周期感知型组件处理生命周期
第一行代码(第3版)
《Android Jetpack开发 原理解析与应用实战》