一、Lifecycle是什么?
JetPack.Lifecycle能够监听Activity/Fragment生命周期行为的各种变化
下面是Lifecycle的重要细节:
Lifecycle可以有效的避免内存泄漏和解决android生命周期的常见难题
Livecycle 是一个表示android生命周期及状态的对象
LivecycleOwner 用于连接有生命周期的对象,如activity,fragment
LivecycleObserver 用于观察查LifecycleOwner
Lifecycle框架使用观察者模式实现观察者监听被观察者的生命周期的变化
二、用法
1、添加依赖
(1)如果项目使用的是androidX
dependencies {
def lifecycle_version = "2.4.0"
def arch_version = "2.1.0"
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
// 只有Lifecycles (不带 ViewModel or LiveData)
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
// Saved state module for ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"
// lifecycle注解处理器
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
// 替换 - 如果使用Java8,就用这个替换上面的lifecycle-compiler
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
//以下按需引入
// 可选 - 帮助实现Service的LifecycleOwner
implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"
// 可选 - ProcessLifecycleOwner给整个 app进程 提供一个lifecycle
implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"
// 可选 - ReactiveStreams support for LiveData
implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version"
// 可选 - Test helpers for LiveData
testImplementation "androidx.arch.core:core-testing:$arch_version"
// 这种依赖支持是 精简版本
// implementation "androidx.lifecycle:lifecycle-runtime:2.0.0"
// implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
// implementation "androidx.lifecycle:lifecycle-common-java8:2.0.0"
// annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.0.0"*/
}
(2)如果项目使用的是非androidX,那就需使用lifecycle android.arch.lifecycle库
dependencies {
def lifecycle_version = "1.1.1"
// 包含ViewModel和LiveData
implementation "android.arch.lifecycle:extensions:$lifecycle_version"
// 仅仅包含ViewModel
implementation "android.arch.lifecycle:viewmodel:$lifecycle_version"
// 仅仅包含LiveData
implementation "android.arch.lifecycle:livedata:$lifecycle_version"
// 仅仅包含Lifecycles
implementation "android.arch.lifecycle:runtime:$lifecycle_version"
// For Kotlin use kapt instead of annotationProcessor
// annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version"
// 如果用Java8, 用于替代compiler
// implementation "android.arch.lifecycle:common-java8:$lifecycle_version" // 这个不行
// implementation 'androidx.lifecycle:lifecycle-common-java8:2.2.0'
// 可选,ReactiveStreams对LiveData的支持
implementation "android.arch.lifecycle:reactivestreams:$lifecycle_version"
// 可选,LiveData的测试
testImplementation "android.arch.core:core-testing:$lifecycle_version"
// 除此之外,不要忘了在build.gradle添加 "androidx.lifecycle:common-java8:<version>"
implementation "androidx.lifecycle:common-java8:1.1.1"
implementation "android.arch.lifecycle:extensions:1.1.1"
}
2、使用
(1)使用1: 继承LifecycleObserver接口,自定义方法,方法上添加@OnLifecycleEvent注解
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifecycle.addObserver(MyLifecycleObserver())
}
// 监听activity的生命周期
class MyLifecycleObserver : LifecycleObserver {
private val TAG = MyLifecycleObserver::class.java.simpleName
// 方法名可以自由定义,需要添加@OnLifecycleEvent注解
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun myCreate() = Log.e(TAG, "myCreate: ")
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun myStart() = Log.e(TAG, "myStart: ")
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun myResume() = Log.e(TAG, "myResume: ")
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun myPause() = Log.e(TAG, "myPause: ")
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun myStop() = Log.e(TAG, "myStop: ")
}
(2)使用2: 继承DefaultLifecycleObserver接口,实现对应的方法。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
Log.d(TAG, "onCreate: ")
}
override fun onStart(owner: LifecycleOwner) {
Log.d(TAG, "onStart: ")
}
override fun onResume(owner: LifecycleOwner) {
Log.d(TAG, "onResume: ")
}
override fun onPause(owner: LifecycleOwner) {
Log.d(TAG, "onPause: ")
}
override fun onStop(owner: LifecycleOwner) {
Log.d(TAG, "onStop: ")
}
override fun onDestroy(owner: LifecycleOwner) {
Log.d(TAG, "onDestroy: ")
}
})
}
三、源码解析
AppCompatActivity继承自FragmentActivity,而FragmentActivity又继承自ComponentActivity,ComponentActivity实现了LifecycleOwner接口。
ComponentActivity.create()
--> ReportFragment.injectIfNeededIn(this);
// 创建了一个ReportFragment,与activity的生命保持一致。以此来监听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();
}
1、首先我们需要了解到有五大状态:DESTROYED(销毁状态)、INITIALIZED(初始状态)、CREATED(创建状态)、STARTED(启动状态)、RESUMED(可见状态)
以被观察者(activity)的生命周期驱动观察者(状态)的变化,来达到观察者中保存的状态和被观察者的生命周期保持一致。
2、接下来,我们代码分析下流程。
// lifecycle是在ComponentActivity实现的。lifecycle = LifecycleRegistry()
lifecycle.addObserver(MyLifecycleObserver())@MainActivity
// 初始化状态,如果是非销毁状态,就初始化状态为INITIALIZED
--> State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;@LifecycleRegistry
// observer 作为参数传入ObserverWithState
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
// observer 继续传
--> mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
// object 就是 observer。ReflectiveGenericLifecycleObserver这个类要记住,后面要用到。。。。。。。
--> return new ReflectiveGenericLifecycleObserver(object);
// mWrapped 就是 observer
--> mWrapped = wrapped;
// 获取到observer的class。
--> mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
sync();
// 如果观察者、被观察者的状态不一致,那就去同步状态
--> while (!isSynced()) {
mNewEventOccurred = false;
// 被观察者的状态比观察者中的状态要小,说明是逆操作,往后走
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
// 再次校验,如果观察者中的状态比被观察者的要大,继续执行
--> while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred && mObserverMap.contains(entry.getKey()))) {
// 事件回流。通过观察者中的状态,获取到事件。下面再分析
Event event = Event.downFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event down from " + observer.mState);
}
pushParentState(event.getTargetState());
// 上面获取到事件后,就去分发事件
observer.dispatchEvent(lifecycleOwner, event);
// mLifecycleObserver就是上面的ReflectiveGenericLifecycleObserver
--> mLifecycleObserver.onStateChanged(owner, event);
--> mInfo.invokeCallbacks(source, event, mWrapped);
--> invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event, target);
--> handlers.get(i).invokeCallback(source, event, mWrapped);
// 反射执行对应的方法
--> mMethod.invoke(target);
popParentState();
}
}
Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
// 被观察者的状态比观察者中的状态要大,说明是正操作,往前走
if (!mNewEventOccurred && newest != null && mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
// 再次校验,如果观察者中的状态比被观察者的要小,继续执行
--> while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred && mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
// 事件正流。通过观察者中的状态,获取到事件。下面再分析
final Event event = Event.upFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event up from " + observer.mState);
}
// 上面获取到事件后,就去分发事件。后面的逻辑与上面一样。
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
3、上面分析到,被观察者的状态发生变化,导致观察者的状态也发生响应的变化。继而观察者再通过比较上一次和当前的状态,获取出当前应该执行的事件。
我们来画个流程图来分析。
绿色部分是状态
红色路径是正操作
蓝色路径是反操作
通过前进状态获取到事件:
public static Event upFrom(@NonNull State state) {
switch (state) {
case INITIALIZED:
return ON_CREATE;
case CREATED:
return ON_START;
case STARTED:
return ON_RESUME;
default:
return null;
}
}
通过后退状态获取到事件:
public static Event downFrom(@NonNull State state) {
switch (state) {
case CREATED:
return ON_DESTROY;
case STARTED:
return ON_STOP;
case RESUMED:
return ON_PAUSE;
default:
return null;
}
}
4、上面分析了在设置监听时,去同步状态的流程。其实当framgment的生命周期发生变化的执行,也是类似的。以onStart为例。
ReportFragment.onStart() {
--> dispatch(getActivity(), event);
--> ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
--> moveToState(event.getTargetState());
// 如果状态一致,直接return,不执行
--> if (mState == next) {
return;
}
mState = next;
mHandlingEvent = true;
//这个代码是不是又似曾相识,跟上面的一样
sync();
mHandlingEvent = false;