概述
Lifecycle
是生命周期感知型组件,用于存储有关组件(如 Activity 或 Fragment)的生命周期状态的信息,并允许其他对象观察此状态
使用
导入依赖
//如果已经集成了AndroidX的不需要额外操作,没有集成的话需要导入对应的依赖
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.0.0"
Lifecycle管理Activity的生命周期
class TestActivity : AppCompatActivity() {
private lateinit var mObserver: LifecycleObserver
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mObserver = MyObserver()
lifecycle.addObserver(mObserver)
}
override fun onStart() {
super.onStart()
println("owner onStart")
}
override fun onStop() {
super.onStop()
println("owner onStop")
}
}
internal class MyObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun connectListener() {
println("MyObserver connectListener")
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stopListener() {
println("MyObserver stopListener")
}
}
//打印的日志如下
2021-06-02 11:34:42.902 23976-23976/com.xz.fksj I/System.out: owner onStart
2021-06-02 11:34:42.903 23976-23976/com.xz.fksj I/System.out: MyObserver connectListener
2021-06-02 11:35:04.872 23976-23976/com.xz.fksj I/System.out: MyObserver stopListener
2021-06-02 11:35:04.883 23976-23976/com.xz.fksj I/System.out: owner onStop
可以明显的看出,设置的MyObserver能监听到Activity的生命周期的变化情况
监听整个app的生命周期,可以判断app是否处于前台
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get().lifecycle.addObserver(ApplicationLifecycleObserver())
}
/**
* Application生命周期观察,提供整个应用进程的生命周期
*
* Lifecycle.Event.ON_CREATE只会分发一次,Lifecycle.Event.ON_DESTROY不会被分发。
*
* 第一个Activity进入时,ProcessLifecycleOwner将分派Lifecycle.Event.ON_START, Lifecycle.Event.ON_RESUME。
* 而Lifecycle.Event.ON_PAUSE, Lifecycle.Event.ON_STOP,将在最后一个Activit退出后后延迟分发。如果由于配置更改而销毁并重新创建活动,则此延迟足以保证ProcessLifecycleOwner不会发送任何事件。
*
* 作用:监听应用程序进入前台或后台
*/
private class ApplicationLifecycleObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
private fun onAppForeground() {
println("ApplicationObserver: app moved to foreground")
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
private fun onAppBackground() {
println("ApplicationObserver: app moved to background")
}
}
}
源码分析
开始之前先简单介绍一下几个重要的类
- **LifecycleObserver : **Lifecycle观察者。我们需要自定义类实现LifecycleObserver,通过注解的方式可观察生命周期方法。
- LifecycleOwner : Lifecycle持有者。让Activity或者fragment实现该接口,当生命周期改变是事件会被LifecycleObserver接收到。
- Lifecycle : 生命周期抽象类。持有添加和移除监听方法。定义State和Event枚举。
- LifecycleRegistry : Lifecycle的实现类
- **State 枚举 : ** 当前生命周期所处状态。Lifecycle 将 Activity 的生命周期函数对应成 State (不可等同)
- Event 枚举 : 当前生命周期变化所对应的事件。State 变化触发 Event 事件,事件会被注册的观察者LifecycleObserver 接收处理。
首先来看Lifecycle
这个抽象类
public abstract class Lifecycle {
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
@MainThread
@NonNull
public abstract State getCurrentState();
//前面六个事件对应生命周期的方法,最后一个ON_ANY可以响应任何事件
@SuppressWarnings("WeakerAccess")
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
//5种状态,状态的变化都是由上面的六个事件所触发变化的
@SuppressWarnings("WeakerAccess")
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}
具体的事件和状态对应变化图如下
Event 表示生命周期事件,与 Activity/Fragment 生命周期方法对应。State 是 Lifecycle 这些生命周期对应的状态。
为什么不直接用对应的生命周期设置对应的状态呢,而是设置了五个状态呢?原因很简单,因为 Lifecycle 不仅仅只是给自己用这些状态,还有 LiveData,ViewMode 等控件也会用到这些状态的进行逻辑判断,所以 Google 工程师做了更好的封装和管理。
Event 中的 ON_CREATE,ON_START,ON_RESUME 是在 LifecyclerOwner 对应的方法执行之后分发,ON_PAUSE,ON_STOP,ON_DESTROY 是在 LifecyclerOwner 对应的方法执行之前分发。
具体lifecycle
是如何监听Activity
的生命周期的呢?接着往下看
我们先回到开头的例子中,例子中能直接使用lifecycle.addObserver(mObserver)
,
那是因为AppCompatActivity
内部肯定是实现了 LifecycleOwner
,通过LifecycleOwner
获取Lifecycle
的实例,这样才能调用 addObserver()
.具体看ComponentActivity
下。
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
HasDefaultViewModelProviderFactory,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
//具体的实现是由LifecycleRegistry来实现的,来看下对应的addObserver方法
public class LifecycleRegistry extends Lifecycle {
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//带状态的观察者,这个状态的作用:新的事件触发后 遍历通知所有观察者时
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
if (previous != null) {
return;
}
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
// it is null we should be destroyed. Fallback quickly
return;
}
//通过while循环,把新的观察者的状态连续不断的同步到最新的状态
//就算添加的晚了,还是会把之前的事件一个个分发给你(upEvent方法),这也是liveData数据倒灌的原因
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
popParentState();
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
mAddingObserverCounter--;
}
}
我们先来看ObserverWithState
这个类,负责监听者和生命周期的维护
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
//分发,通知观察者
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
事件的发送者是mLifecycleObserver
,具体的创建者是Lifecycling.lifecycleEventObserver(observer)
static LifecycleEventObserver lifecycleEventObserver(Object object) {
...
//直接看这一行,通过反射创建对应的监听者
return new ReflectiveGenericLifecycleObserver(object);
}
我们再往下面跟
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
}
CallbackInfo getInfo(Class klass) {
CallbackInfo existing = mCallbackMap.get(klass);
if (existing != null) {
return existing;
}
existing = createInfo(klass, null);
return existing;
}
//处理被OnLifecycleEvent注释的注解,存到mCallbackMap下,便于后续监听者的使用。
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
Class superclass = klass.getSuperclass();
Map handlerToEvent = new HashMap<>();
if (superclass != null) {
CallbackInfo superInfo = getInfo(superclass);
if (superInfo != null) {
handlerToEvent.putAll(superInfo.mHandlerToEvent);
}
}
Class[] interfaces = klass.getInterfaces();
for (Class intrfc : interfaces) {
for (Map.Entry entry : getInfo(
intrfc).mHandlerToEvent.entrySet()) {
verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
}
}
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
for (Method method : methods) {
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation == null) {
continue;
}
hasLifecycleMethods = true;
Class[] params = method.getParameterTypes();
int callType = CALL_TYPE_NO_ARG;
if (params.length > 0) {
callType = CALL_TYPE_PROVIDER;
if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
throw new IllegalArgumentException(
"invalid parameter type. Must be one and instanceof LifecycleOwner");
}
}
Lifecycle.Event event = annotation.value();
if (params.length > 1) {
callType = CALL_TYPE_PROVIDER_WITH_EVENT;
if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
throw new IllegalArgumentException(
"invalid parameter type. second arg must be an event");
}
if (event != Lifecycle.Event.ON_ANY) {
throw new IllegalArgumentException(
"Second arg is supported only for ON_ANY value");
}
}
if (params.length > 2) {
throw new IllegalArgumentException("cannot have more than 2 params");
}
MethodReference methodReference = new MethodReference(callType, method);
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
}
CallbackInfo info = new CallbackInfo(handlerToEvent);
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
这个时候回到ObserverWithState
的dispatchEvent
方法,进行事件发送。最终的调用者为
ReflectiveGenericLifecycleObserver
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
//ClassesInfoCache.class
void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
target);
}
private static void invokeMethodsForEvent(List handlers,
LifecycleOwner source, Lifecycle.Event event, Object mWrapped) {
if (handlers != null) {
for (int i = handlers.size() - 1; i >= 0; i--) {
handlers.get(i).invokeCallback(source, event, mWrapped);
}
}
}
//这里是最终的回调
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
//noinspection TryWithIdenticalCatches
try {
switch (mCallType) {
case CALL_TYPE_NO_ARG:
mMethod.invoke(target);
break;
case CALL_TYPE_PROVIDER:
mMethod.invoke(target, source);
break;
case CALL_TYPE_PROVIDER_WITH_EVENT:
mMethod.invoke(target, source, event);
break;
}
} catch (InvocationTargetException e) {
throw new RuntimeException("Failed to call observer method", e.getCause());
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
那么是如何保持生命周期同步的呢?
回到 ComponentActivity
,其中有这么一段
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
在ComponentActivity
中绑定一个透明的ReportFragment
,这里的写法跟Glide
里的是一样的,主要是用来感知生命周期的作用
public class ReportFragment extends Fragment {
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
// On API 29+, we can register for the correct Lifecycle callbacks directly
activity.registerActivityLifecycleCallbacks(
new LifecycleCallbacks());
}
// Prior to API 29 and to maintain compatibility with older versions of
// ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and
// need to support activities that don't extend from FragmentActivity from support lib),
// use a framework fragment to get the correct timing of Lifecycle events
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();
}
}
}
接着通过dispatch
将生命周期分发出去
@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);
// just want to be sure that we won't leak reference to an activity
mProcessListener = null;
}
//这里加了版本判断,>=29的,处理流程交给ActivityLifecycleCallbacks
private void dispatch(@NonNull Lifecycle.Event event) {
if (Build.VERSION.SDK_INT < 29) {
// Only dispatch events from ReportFragment on API levels prior
// to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks
// added in ReportFragment.injectIfNeededIn
dispatch(getActivity(), event);
}
}
//根据我们传入的参数,只需要看第一个if语句
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);
}
}
}
回到LifecycleRegistryd
,看handleLifecycleEvent
方法
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
private void moveToState(State next) {
//相同状态,不会重复分发
if (mState == next) {
return;
}
mState = next;
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
通过 sync()
将状态同步给所有观察者。
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
+ "garbage collected. It is too late to change lifecycle state.");
}
while (!isSynced()) {
mNewEventOccurred = false;
// no need to check eldest for nullability, because isSynced does it for us.
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
Entry newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Entry entry = ascendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}
看到最后发现还是熟悉的 observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
后面的流程就跟上面说过的一样。