提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
Lifecycle 是 Jetpack 的一员同时也是 LiveData 和 ViewModel 的基础,在 Lifecycle 之前依赖生命周期的操作都是通过重写父类的对应方法来实现的,通过 Lifecycle 可以把这部分操作定义在别的地方,也就是解耦。之前只是看过大概原理,今天来细读一下源码
基于 Lifecycle 2.3.1
主要成员
- LifecycleOwner 是一个接口用于被观察的组件实现,唯一一个方法用于返回一个 Lifecycle 对象,实现它的对象表示具有生命周期
- Lifecycle 是一个抽象类,三个抽象方法分别用于添加、移除观察者和获取组件(具有生命周期的对象比如 Activity、Fragment)当前状态,具体实现在 LifecycleRegistry 里,同时定义了两个枚举类 State(代表具有生命周期的对象的状态)、Event(代表具有生命周期的对象发出的事件)
- LifecycleRegistry Lifecycle 的具体实现,整个 Lifecycle 框架的核心
- LifecycleObserver 生命周期事件的观察者,是一个空实现,标记接口
- LifecycleEventObserver LifecycleObserver 的子接口,定义了一个方法可以接收所有的生命周期事件
- FullLifecycleObserver LifecycleObserver 的子接口,定义了接收所有生命周期事件的方法
- DefaultLifecycleObserver FullLifecycleObserver 的子接口,仅在编译平台是 Java 8 时可用,利用了 Java8 的接口方法空实现的特性,是推荐的使用方式
- OnLifecycleEvent 注解,可通过此注解标记对象方法接收指定的生命周期事件,是不推荐的使用方式
在 Activity 中的实现
public class ComponentActivity extends Activity implements
LifecycleOwner,
KeyEventDispatcher.Component {
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
@CallSuper
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
super.onSaveInstanceState(outState);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
主要逻辑在 ReportFragment 里
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();
}
}
injectIfNeededIn 方法里区分了版本,如果是 29 及以上版本调用 LifecycleCallbacks.registerIn 否则添加 ReportFragment 用于感知宿主 Activity 的生命周期变化,这里与 Glide 的处理一样。先看一下高版本的实现
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
static void registerIn(Activity activity) {
activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
}
@Override
public void onActivityPostCreated(@NonNull Activity activity,
@Nullable Bundle savedInstanceState) {
dispatch(activity, Lifecycle.Event.ON_CREATE);
}
@Override
public void onActivityPostStarted(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_START);
}
@Override
public void onActivityPostResumed(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_RESUME);
}
@Override
public void onActivityPrePaused(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_PAUSE);
}
@Override
public void onActivityPreStopped(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_STOP);
}
@Override
public void onActivityPreDestroyed(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_DESTROY);
}
}
LifecycleCallbacks 实现了 Application.ActivityLifecycleCallbacks 接口 Activity 通过 registerActivityLifecycleCallbacks 方法注册接口并且在 onCreate onStart onResume 生命周期方法后和 onPause onStop onDestroy 方法前调用 dispatch 去通知所有观察者事件变化。再看一下低版本的实现
public class ReportFragment extends android.app.Fragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatch(Lifecycle.Event.ON_CREATE);
}
@Override
public void onStart() {
super.onStart();
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
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);
}
private void dispatch(@NonNull Lifecycle.Event event) {
if (Build.VERSION.SDK_INT < 29) {
dispatch(getActivity(), event);
}
}
}
Fragment 的 onActivityCreated、onStart、onResume 等方法是后于 Activity 的相应方法的,Fragment 的 onPause、onStop、onDestroy 等方法是先于 Activity 的相应方法的,所以与低版本一样保证了先后顺序,并且在 dispatch 方法里判断了版本只有小于 29 才继续执行,因为上面不管是高低版本都会向宿主 Activity 添加 ReportFragment 避免高版本重复发送事件。总结一下就是在大于等于 29 的版本通过 android.app.Activity#registerActivityLifecycleCallbacks 方法感知生命周期,低版本通过向宿主 Activity 中添加 ReportFragment 感知生命周期
这里不太理解高版本为什么还要添加 ReportFragment
到这里不管高低版本都已经拿到了 Activity 的生命周期事件接下来看一下是怎么传递给生命周期的观察者的
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);
}
}
}
可以想到接下来肯定是遍历所有的观察者把事件转发出去,所以在 handleLifecycleEvent 之前先看一下添加观察者的逻辑
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
enforceMainThreadIfNeeded("addObserver");
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) {
return;
}
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
final Event event = Event.upFrom(statefulObserver.mState);
if (event == null) {
throw new IllegalStateException("no event up from " + statefulObserver.mState);
}
statefulObserver.dispatchEvent(lifecycleOwner, event);
popParentState();
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
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 = event.getTargetState();
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
ObserverWithState 有两个作用:一、观察者可以是注解也可以是接口实现 ObserverWithState 统一了它们的接口方便调用,二、ObserverWithState 内部也保存了生命周期事件用于记录这个观察者已经回调到的状态,防止重复调用 ObserverWithState 在构造方法中调用了 androidx.lifecycle.Lifecycling#lifecycleEventObserver 对观察者解析,最后把不同方式的观察者都解析成 LifecycleEventObserver 方便回调事件
static LifecycleEventObserver lifecycleEventObserver(Object object) {
boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
if (isLifecycleEventObserver && isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
(LifecycleEventObserver) object);
}
if (isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
}
if (isLifecycleEventObserver) {
return (LifecycleEventObserver) object;
}
final Class<?> klass = object.getClass();
int type = getObserverConstructorType(klass);
if (type == GENERATED_CALLBACK) {
List<Constructor<? extends GeneratedAdapter>> constructors =
sClassToAdapters.get(klass);
if (constructors.size() == 1) {
GeneratedAdapter generatedAdapter = createGeneratedAdapter(
constructors.get(0), object);
return new SingleGeneratedAdapterObserver(generatedAdapter);
}
GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
for (int i = 0; i < constructors.size(); i++) {
adapters[i] = createGeneratedAdapter(constructors.get(i), object);
}
return new CompositeGeneratedAdaptersObserver(adapters);
}
return new ReflectiveGenericLifecycleObserver(object);
}
只有引入 lifecycle-compiler 时才会生成 GeneratedAdapter 的子类,如果没有引入则会通过反射调用
private static int resolveObserverCallbackType(Class<?> klass) {
if (klass.getCanonicalName() == null) {
return REFLECTIVE_CALLBACK;
}
Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
if (constructor != null) {
sClassToAdapters.put(klass, Collections
.<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
return GENERATED_CALLBACK;
}
boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
if (hasLifecycleMethods) {
return REFLECTIVE_CALLBACK;
}
Class<?> superclass = klass.getSuperclass();
List<Constructor<? extends GeneratedAdapter>> adapterConstructors = null;
if (isLifecycleParent(superclass)) {
if (getObserverConstructorType(superclass) == REFLECTIVE_CALLBACK) {
return REFLECTIVE_CALLBACK;
}
adapterConstructors = new ArrayList<>(sClassToAdapters.get(superclass));
}
for (Class<?> intrface : klass.getInterfaces()) {
if (!isLifecycleParent(intrface)) {
continue;
}
if (getObserverConstructorType(intrface) == REFLECTIVE_CALLBACK) {
return REFLECTIVE_CALLBACK;
}
if (adapterConstructors == null) {
adapterConstructors = new ArrayList<>();
}
adapterConstructors.addAll(sClassToAdapters.get(intrface));
}
if (adapterConstructors != null) {
sClassToAdapters.put(klass, adapterConstructors);
return GENERATED_CALLBACK;
}
return REFLECTIVE_CALLBACK;
}
再来看一下是怎么解析标记了 OnLifecycleEvent 注解的方法的
boolean hasLifecycleMethods(Class<?> klass) {
Boolean hasLifecycleMethods = mHasLifecycleMethods.get(klass);
if (hasLifecycleMethods != null) {
return hasLifecycleMethods;
}
Method[] methods = getDeclaredMethods(klass);
for (Method method : methods) {
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation != null) {
createInfo(klass, methods);
return true;
}
}
mHasLifecycleMethods.put(klass, false);
return false;
}
遍历所有方法看是否标记了 OnLifecycleEvent 注解,主要逻辑都在 createInfo 里
private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) {
Class<?> superclass = klass.getSuperclass();
Map<MethodReference, Lifecycle.Event> 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<MethodReference, Lifecycle.Event> 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;
}
解析所有方法判断是否有 OnLifecycleEvent 注解并且对方法的参数进行校验最后缓存起来,可以看到不管是以什么方式使用最后都会返回 LifecycleEventObserver 的子类实例最后再通过 androidx.lifecycle.LifecycleRegistry.ObserverWithState#dispatchEvent 调用实例的 onStateChanged 方法把事件回调出去。接下来再回去看 handleLifecycleEvent 方法
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
moveToState(event.getTargetState());
}
private void moveToState(State next) {
if (mState == next) {
return;
}
mState = next;
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
return;
}
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
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;
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
isSynced() 内部通过判断最新和最老的订阅者的状态是否都等于当前状态 mState 来判断是否已经同步完毕的,如果没有就通过订阅者状态和当前状态的大小比较来通过 backwardPass 或者 forwardPass 来更新订阅者状态 sync() 里这个判断状态的方式就是依赖了订阅队列的状态有序性:判断订阅队列存在状态大于当前状态的订阅者不需要检查整个队列,只需要跟订阅队列中状态最大的也就是最先订阅的订阅者比较;同样的判断订阅队列存在状态小于于当前状态的订阅者也只需要跟最新订阅的订阅者比较 backwardPass 或者 forwardPass 用于更新状态,其中 backwardPass 的作用是将订阅队列中所有状态大于当前状态的订阅者同步到当前状态。而 forwardPass 就是将订阅队列中的所有状态小于当前状态的订阅者同步到当前状态 状态往 INITIALIZED->RESUMED 方向变化时调用 forwardPass 方法,状态往 RESUMED->DESTROYED 方向变化时调用 backwardPass 方法。下面看下 backwardPass
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Map.Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
ObserverWithState observer = entry.getValue();
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);
popParentState();
}
}
}
方法中会判断观察者的状态依次回调事件,在回调之前会记录当前观察者的状态回调之后再移除记录是为了处理事件嵌套的情况,保证回调事件的顺序和添加观察者的顺序一致
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = event.getTargetState();
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
最后就会通过添加观察者时创建的 ObserverWithState 对象回调事件,而 ObserverWithState 是通过在构造方法中根据观察者的方式解析出的 LifecycleEventObserver 回调出去的,下面依次看一下
class FullLifecycleObserverAdapter implements LifecycleEventObserver {
private final FullLifecycleObserver mFullLifecycleObserver;
private final LifecycleEventObserver mLifecycleEventObserver;
FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,
LifecycleEventObserver lifecycleEventObserver) {
mFullLifecycleObserver = fullLifecycleObserver;
mLifecycleEventObserver = lifecycleEventObserver;
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
switch (event) {
case ON_CREATE:
mFullLifecycleObserver.onCreate(source);
break;
case ON_START:
mFullLifecycleObserver.onStart(source);
break;
case ON_RESUME:
mFullLifecycleObserver.onResume(source);
break;
case ON_PAUSE:
mFullLifecycleObserver.onPause(source);
break;
case ON_STOP:
mFullLifecycleObserver.onStop(source);
break;
case ON_DESTROY:
mFullLifecycleObserver.onDestroy(source);
break;
case ON_ANY:
throw new IllegalArgumentException("ON_ANY must not been send by anybody");
}
if (mLifecycleEventObserver != null) {
mLifecycleEventObserver.onStateChanged(source, event);
}
}
}
FullLifecycleObserverAdapter 在 onStateChanged 中把事件回调出去最终调用了观察者的对应方法
class SingleGeneratedAdapterObserver implements LifecycleEventObserver {
private final GeneratedAdapter mGeneratedAdapter;
SingleGeneratedAdapterObserver(GeneratedAdapter generatedAdapter) {
mGeneratedAdapter = generatedAdapter;
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
mGeneratedAdapter.callMethods(source, event, false, null);
mGeneratedAdapter.callMethods(source, event, true, null);
}
}
public class AnnotationLifecycleTest_LifecycleAdapter implements GeneratedAdapter {
final AnnotationLifecycleTest mReceiver;
AnnotationLifecycleTest_LifecycleAdapter(AnnotationLifecycleTest receiver) {
this.mReceiver = receiver;
}
@Override
public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny,
MethodCallsLogger logger) {
boolean hasLogger = logger != null;
if (onAny) {
if (!hasLogger || logger.approveCall("onAny", 4)) {
mReceiver.onAny(owner,event);
}
return;
}
}
}
CompositeGeneratedAdaptersObserver 与 SingleGeneratedAdapterObserver 一致不重复贴代码了,最后看一下 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);
}
}
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<MethodReference> 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) {
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);
}
}
最后在封装的方法信息中调用了 invokeCallback 方法根据解析出的参数个数回调观察者的方法,到这里 Activity 的生命周期所有流程就都结束了,再来看一下 Fragment 是怎么实现的
在 Fragment 中的实现
Fragment 本身实现了 LifecycleOwner 接口提供的 Lifecycle 实现也是 LifecycleRegistry
public class Fragment implements LifecycleOwner {
LifecycleRegistry mLifecycleRegistry;
public Fragment() {
initLifecycle();
}
private void initLifecycle() {
mLifecycleRegistry = new LifecycleRegistry(this);
}
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
void performCreate(Bundle savedInstanceState) {
onCreate(savedInstanceState);
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
}
void performStart() {
onStart();
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
}
void performResume() {
onResume();
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
}
void performPause() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
onPause();
}
void performStop() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
onStop();
}
void performDestroy() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
onDestroy();
}
}
Fragment 本身提供的 Lifecycle 也与 Activity 一致都是 ON_CREATE ON_START ON_RESUME 事件在相应的生命周期方法后回调 ON_PAUSE ON_STOP ON_DESTROY 事件在相应的生命周期方法前回调。另外由于 Fragment 本身的生命周期与 Fragment 中 mView 的生命周期并不一致 Fragment 额外又提供了一个持有的 View 的 FragmentViewLifecycleOwner
class FragmentViewLifecycleOwner implements HasDefaultViewModelProviderFactory,
SavedStateRegistryOwner, ViewModelStoreOwner {
private final Fragment mFragment;
private final ViewModelStore mViewModelStore;
private ViewModelProvider.Factory mDefaultFactory;
private LifecycleRegistry mLifecycleRegistry = null;
private SavedStateRegistryController mSavedStateRegistryController = null;
FragmentViewLifecycleOwner(@NonNull Fragment fragment, @NonNull ViewModelStore viewModelStore) {
mFragment = fragment;
mViewModelStore = viewModelStore;
}
@NonNull
@Override
public ViewModelStore getViewModelStore() {
initialize();
return mViewModelStore;
}
void initialize() {
if (mLifecycleRegistry == null) {
mLifecycleRegistry = new LifecycleRegistry(this);
mSavedStateRegistryController = SavedStateRegistryController.create(this);
}
}
boolean isInitialized() {
return mLifecycleRegistry != null;
}
@NonNull
@Override
public Lifecycle getLifecycle() {
initialize();
return mLifecycleRegistry;
}
void setCurrentState(@NonNull Lifecycle.State state) {
mLifecycleRegistry.setCurrentState(state);
}
void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
mLifecycleRegistry.handleLifecycleEvent(event);
}
}
FragmentViewLifecycleOwner 也实现了 LifecycleOwner 接口向外提供的 Lifecycle 实现还是 LifecycleRegistry 它们俩除了 ON_CREATE ON_DESTROY 两个事件回调时机不同其他事件都是相同的
final void restoreViewState(Bundle savedInstanceState) {
onViewStateRestored(savedInstanceState);
if (mView != null) {
mViewLifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
}
}
void performDestroyView() {
if (mView != null && mViewLifecycleOwner.getLifecycle().getCurrentState()
.isAtLeast(Lifecycle.State.CREATED)) {
mViewLifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
}
mState = CREATED;
mCalled = false;
onDestroyView();
}
Fragment View 提供的 Lifecycle 的 ON_CREATE 事件在 onViewStateRestored 之后执行 ON_DESTROY 事件在 onDestroyView 之前执行。官网有一张图描述了它们的区别 另外在 fragment 版本的更新说明中有这样一段描述
添加了新的 Lint 检查,以确保您在从 onCreateView()、onViewCreated() 或 onActivityCreated() 观察 LiveData 时使用 getViewLifecycleOwner()
原因是在 Fragment 中订阅 LiveData 时在 LiveData 中实现的 Lifecycle 观察者会在 Lifecycle 组件处于 DESTROYED 状态时移除 Fragment 对 LiveData 的订阅,当在 Fragment 中 View 销毁重建而 Fragment 没有重建的一些场景可以避免重复订阅,因为 Fragment 在 onDestroy() 前才处于 DESTROYED 而 Fragment 中的 View 在 onDestroyView 前就处于 DESTROYED 通过上面的图也可以看出来
在 Service 中的实现
需要引入 androidx.lifecycle:lifecycle-service 本文基于 2.3.1
Lifecycle 在 Service 中的实现比较简单,子类 LifecycleService 继承自 Service 并且实现了 LifecycleOwner 接口提供的 LifecycleRegistry
public class LifecycleService extends Service implements LifecycleOwner {
private final ServiceLifecycleDispatcher mDispatcher = new ServiceLifecycleDispatcher(this);
@CallSuper
@Override
public void onCreate() {
mDispatcher.onServicePreSuperOnCreate();
super.onCreate();
}
@CallSuper
@Nullable
@Override
public IBinder onBind(@NonNull Intent intent) {
mDispatcher.onServicePreSuperOnBind();
return null;
}
@SuppressWarnings("deprecation")
@CallSuper
@Override
public void onStart(@Nullable Intent intent, int startId) {
mDispatcher.onServicePreSuperOnStart();
super.onStart(intent, startId);
}
@CallSuper
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@CallSuper
@Override
public void onDestroy() {
mDispatcher.onServicePreSuperOnDestroy();
super.onDestroy();
}
@Override
@NonNull
public Lifecycle getLifecycle() {
return mDispatcher.getLifecycle();
}
}
ServiceLifecycleDispatcher 承担了所有的工作
public class ServiceLifecycleDispatcher {
private final LifecycleRegistry mRegistry;
private final Handler mHandler;
private DispatchRunnable mLastDispatchRunnable;
public ServiceLifecycleDispatcher(@NonNull LifecycleOwner provider) {
mRegistry = new LifecycleRegistry(provider);
mHandler = new Handler();
}
private void postDispatchRunnable(Lifecycle.Event event) {
if (mLastDispatchRunnable != null) {
mLastDispatchRunnable.run();
}
mLastDispatchRunnable = new DispatchRunnable(mRegistry, event);
mHandler.postAtFrontOfQueue(mLastDispatchRunnable);
}
public void onServicePreSuperOnCreate() {
postDispatchRunnable(Lifecycle.Event.ON_CREATE);
}
public void onServicePreSuperOnBind() {
postDispatchRunnable(Lifecycle.Event.ON_START);
}
public void onServicePreSuperOnStart() {
postDispatchRunnable(Lifecycle.Event.ON_START);
}
public void onServicePreSuperOnDestroy() {
postDispatchRunnable(Lifecycle.Event.ON_STOP);
postDispatchRunnable(Lifecycle.Event.ON_DESTROY);
}
@NonNull
public Lifecycle getLifecycle() {
return mRegistry;
}
static class DispatchRunnable implements Runnable {
private final LifecycleRegistry mRegistry;
final Lifecycle.Event mEvent;
private boolean mWasExecuted = false;
DispatchRunnable(@NonNull LifecycleRegistry registry, Lifecycle.Event event) {
mRegistry = registry;
mEvent = event;
}
@Override
public void run() {
if (!mWasExecuted) {
mRegistry.handleLifecycleEvent(mEvent);
mWasExecuted = true;
}
}
}
}
Service 的 Lifecycle 比较简单并且没有 ON_PAUSE ON_RESUME 事件
在 Process 中的实现
需要引入 androidx.lifecycle:lifecycle-process 本文基于 2.3.1
ProcessLifecycleOwner 用于监听应用进入前后台,之前这种需求都是通过 registerActivityLifecycleCallbacks 来做的 ProcessLifecycleOwner 原理也差不多只不过还借助了 ReportFragment 。ProcessLifecycleOwner 只会发送一次 ON_CREATE 事件,不会发送 ON_DESTROY 事件,发送 ON_PAUSE 和 ON_STOP 事件会有 700 毫秒的延迟因为 ProcessLifecycleOwner 延迟处理了页面重建的情况,这种场景页面还在前台所以不会回调事件 ProcessLifecycleOwner 通过注册一个 ContentProvider 来初始化所以不需要用户再初始化(Startup 和 Picasso 也是这么做的),ContentProvider 的 onCreate 会早与 Application 的 onCreate 方法执行
public class ProcessLifecycleOwnerInitializer extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
return true;
}
}
class LifecycleDispatcher {
private static AtomicBoolean sInitialized = new AtomicBoolean(false);
static void init(Context context) {
if (sInitialized.getAndSet(true)) {
return;
}
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
}
static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
ReportFragment.injectIfNeededIn(activity);
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
}
private LifecycleDispatcher() {
}
}
ContentProvider 中只做了两件事,第一是调用 LifecycleDispatcher 的 init 方法注入 ReportFragment 监听宿主 Activity 的生命周期,第二是对 ProcessLifecycleOwner 进行初始化
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,
@Nullable Bundle savedInstanceState) {
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();
}
});
}
跟 Activity 一样同样区分版本使用不同的回调方法 ReportFragment 中的代码就不再贴了,文章太长了,先看一下 ProcessLifecycleOwner 中定义的几个变量
private int mStartedCounter = 0;
private int mResumedCounter = 0;
private boolean mPauseSent = true;
private boolean mStopSent = true;
再看一下 ProcessLifecycleOwner 中对其他几个事件的处理
private Runnable mDelayedPauseRunnable = new Runnable() {
@Override
public void run() {
dispatchPauseIfNeeded();
dispatchStopIfNeeded();
}
};
void activityStarted() {
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;
}
}
ProcessLifecycleOwner 整体也比较简单
ViewTreeLifecycleOwner
需要引入 androidx.lifecycle:lifecycle-runtime-ktx 本文基于 2.3.1
ViewTreeLifecycleOwner 是 lifecycle-runtime-ktx 中提供的 View 的一个扩展方法,可以方便的获取所属 Fragment 或者 Activity 的 LifecycleOwner
val lifecycleOwner = binding.textView.findViewTreeLifecycleOwner()
public fun View.findViewTreeLifecycleOwner(): LifecycleOwner? = ViewTreeLifecycleOwner.get(this)
使用和源码都比较简单直接调用了 ViewTreeLifecycleOwner 的 get 方法
public class ViewTreeLifecycleOwner {
private ViewTreeLifecycleOwner() {
}
public static void set(@NonNull View view, @Nullable LifecycleOwner lifecycleOwner) {
view.setTag(R.id.view_tree_lifecycle_owner, lifecycleOwner);
}
public static LifecycleOwner get(@NonNull View view) {
LifecycleOwner found = (LifecycleOwner) view.getTag(R.id.view_tree_lifecycle_owner);
if (found != null) return found;
ViewParent parent = view.getParent();
while (found == null && parent instanceof View) {
final View parentView = (View) parent;
found = (LifecycleOwner) parentView.getTag(R.id.view_tree_lifecycle_owner);
parent = parentView.getParent();
}
return found;
}
}
在 androidx.appcompat.app.AppCompatActivity、androidx.activity.ComponentActivity 的 setContentView 方法以及 androidx.fragment.app.Fragment#performCreateView (onCreateView 之后调用)方法和 androidx.fragment.app.DialogFragment 的 onStart 方法中都调用了 set 方法,所以在这些组件的子类中可以使用 ViewTreeLifecycleOwner 获取 LifecycleOwner
参考与感谢
从源码看 Jetpack(1)- Lifecycle 源码详解 从源码看 Jetpack(2)- Lifecycle 衍生物源码详解 Android架构组件(2)LifecycleRegistry 源码分析 Jetpack MVVM七宗罪 之一 拿Fragment当LifecycleOwner 为什么Fragment中要使用viewLifecycleOwner代替this
|