Lifecycle 是一个专门用来处理生命周期的库,它能够帮助我们将 Acitivity、Framgent 的生命周期处理与业务逻辑处理进行解耦,让我们能够更加专注于业务;
基于 Lifecycle 的特性,在任意生命周期方法内注册观察者都能接收到完整的生命周期事件,比如在onResume 中注册一个观察者它会依次收到:
LifecycleEvent.onCreate -> LifecycleEvent.onStart -> LifecycleEvent.onResume。
相关依赖库如下:
dependencies {
def lifecycle_version = "2.3.0"
def arch_version = "2.1.0"
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
// Lifecycles only (without ViewModel or LiveData)
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
// Saved state module for ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"
// Jetpack Compose Integration for ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha01"
// Annotation processor
kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
// alternately - if using Java8, use the following instead of lifecycle-compiler
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
// optional - helpers for implementing LifecycleOwner in a Service
implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"
// optional - ProcessLifecycleOwner provides a lifecycle for the whole application process
implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"
// optional - ReactiveStreams support for LiveData
implementation "androidx.lifecycle:lifecycle-reactivestreams-ktx:$lifecycle_version"
// optional - Test helpers for LiveData
testImplementation "androidx.arch.core:core-testing:$arch_version"
}
相关类介绍:
- Lifecycle 抽象类,用于管理 Observer,包括 Event 和 State 两个枚举类型。
- LifecycleOwner 持有 Lifecycle 类的接口。如 AppCompatActivity 和 Fragment。
- LifecycleObserver 生命周期观察者,直接实现类有 LifecycleEventObserver 和 FullLifecycleObserver。
- LifecycleRegistry Lifecycle 的实现类。可以自定义 LifecycleOwner。
Lifecycle
/**
* Defines an object that has an Android Lifecycle.
*/
public abstract class Lifecycle {
public abstract void addObserver(LifecycleObserver observer);
public abstract void removeObserver(LifecycleObserver observer);
public abstract State getCurrentState();
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(State state) {
return compareTo(state) >= 0;
}
}
}
Lifecycle 是一个抽象类,其内部不仅包括了添加和移除观察者的方法,还包括 Event 和 State 枚举。State 指的是 Lifecycle 的生命周期所处的状态。Event 代表 Lifecycle 生命周期对应的事件,这些事件会映射到 Activity 和 Fragment 中的回调事件中。
LifecycleRegistry
public class LifecycleRegistry extends Lifecycle {
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
this(provider, true);
}
private LifecycleRegistry(@NonNull LifecycleOwner provider, boolean enforceMainThread) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
mEnforceMainThread = enforceMainThread;
}
}
LifecycleRegistry 是 Lifecycle 的实现类。必须在主线程。对目标对象是弱引用,不会导致 Activity 内存泄漏。
源码分析
ComponentActivity 和 Fragment 都实现了 LifecycleOwner 接口。
// androidx.activity:activity:1.2.0
public class ComponentActivity extends androidx.core.app.ComponentActivity
implements LifecycleOwner,... {
private final 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) {
Lifecycle lifecycle = getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).setCurrentState(Lifecycle.State.CREATED);
}
super.onSaveInstanceState(outState);
}
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
Activity 的生命周期代理给 ReportFragment 分发。
public class ReportFragment extends Fragment {
public static void injectIfNeededIn(Activity activity) {
// >= 10.0 使用 Activity 生命周期回调的方式分发生命周期
if (Build.VERSION.SDK_INT >= 29) {
activity.registerActivityLifecycleCallbacks(
new LifecycleCallbacks());
}
// < 10.0 使用 Fragemnt 分发生命周期,以兼容以前的版本。
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatch(Lifecycle.Event.ON_CREATE);
}
private void dispatch(@NonNull Lifecycle.Event event) {
if (Build.VERSION.SDK_INT < 29) {
dispatch(getActivity(), event);
}
}
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
// LifecycleRegistryOwner 已废弃
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);
}
}
}
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
// onActivityPostXXX() 在生命周期方法之后调用
@Override
public void onActivityPostCreated(@NonNull Activity activity,
@Nullable Bundle savedInstanceState) {
dispatch(activity, Lifecycle.Event.ON_CREATE);
}
// onActivityPreXXX() 在生命周期方法之前调用
@Override
public void onActivityPrePaused(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_PAUSE);
}
}
}
在 API 29 及以上直接使用 Activity#registerActivityLifecycleCallbacks 直接注册了生命周期回调,然后给当前 activity 添加一个无界面的 ReportFragment 代理生命周期回调。
// androidx.fragment:fragment:1.3.0
public class Fragment implements LifecycleOwner,...{
LifecycleRegistry mLifecycleRegistry;
public Fragment() {
initLifecycle();
}
private void initLifecycle() {
mLifecycleRegistry = new LifecycleRegistry(this);
}
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
// performStart() 和 performResume() 类似
void performCreate(Bundle savedInstanceState) {
onCreate(savedInstanceState);
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
}
// performStop() 和 performDestroy() 类似
void performPause() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
onPause();
}
}
观察者都是通过 LifecycleRegistry
类注册的,是 Lifecycle 的唯一实现类。
public class LifecycleRegistry extends Lifecycle {
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
private final WeakReference<LifecycleOwner> mLifecycleOwner;
private State mState;
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
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;
}
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) {
// 如 onPause -> onResume
backwardPass(lifecycleOwner);
}
Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
// 如 onResume -> onPause
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
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 && ...)) {
Event event = Event.downFrom(observer.mState);
observer.dispatchEvent(lifecycleOwner, event);
}
}
}
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) < 0 && ...)) {
final Event event = Event.upFrom(observer.mState);
observer.dispatchEvent(lifecycleOwner, event);
}
}
}
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// 包装观察者,绑定初始状态。同时反射获取被 OnLifecycleEvent 注解的方法
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
// 保存观察者
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
// 已经添加过,返回
if (previous != null) {
return;
}
State targetState = calculateTargetState(observer);
// 比较观察者的状态和目标对象状态,小于 0 说明两者状态还没有对齐
// 观察者会收到多个生命周期事件
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
// 根据当前状态,获取到后一个状态的事件
final Event event = Event.upFrom(statefulObserver.mState);
statefulObserver.dispatchEvent(lifecycleOwner, event);
// 重新计算观察者当前的状态,不一致会重新进入循环
targetState = calculateTargetState(observer);
}
}
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
// 适配成 ReflectiveGenericLifecycleObserver 或 FullLifecycleObserverAdapter
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
mLifecycleObserver.onStateChanged(owner, event);
}
}
}
ObserverWithState#mState 的作用是新的事件触发后 遍历通知所有观察者时,判断是否已经通知这个观察者了,即防止重复通知。
如果在目标对象 RESUMED 状态注册观察者,那么观察者会接收到三次生命周期事件:
- 第一次:分发 ON_CREATE 事件,观察者状态 INITIALIZED->CREATED
- 第二次:分发 ON_START 事件,观察者状态 CREATED->STARTED
- 第三次:分发 ON_RESUME 事件,观察者状态 STARTED->RESUMED
public class Lifecycling {
static LifecycleEventObserver lifecycleEventObserver(Object object) {
// 根据 Observer 类型,返回 FullLifecycleObserverAdapter 对象
final Class<?> klass = object.getClass();
int type = getObserverConstructorType(klass);
if (type == GENERATED_CALLBACK) {
// 一个构造方法返回 SingleGeneratedAdapterObserver 对象
// 多于一个构造方法返回 CompositeGeneratedAdaptersObserver 对象
}
return new ReflectiveGenericLifecycleObserver(object);
}
}
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);
}
}
final class ClassesInfoCache {
private final Map<Class<?>, CallbackInfo> mCallbackMap = new HashMap<>();
private final Map<Class<?>, Boolean> mHasLifecycleMethods = new HashMap<>();
CallbackInfo getInfo(Class<?> klass) {
CallbackInfo existing = mCallbackMap.get(klass);
if (existing != null) {
return existing;
}
existing = createInfo(klass, null);
return existing;
}
private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) {
Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
// 反射获取 Observer 类中的所有方法
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
for (Method method : methods) {
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
// 检查方法是否被 OnLifecycleEvent 注解
if (annotation == null) {
continue;
}
hasLifecycleMethods = true;
// 获取注解方法参数
Class<?>[] params = method.getParameterTypes();
int callType = CALL_TYPE_NO_ARG;
// 如果有一个参数,参数列表必须是(LifecycleOwner)
// 若果有两个参数,参数列表必须是(LifecycleOwner, Lifecycle.Event),而且必须是 Lifecycle.Event.ON_ANY 注解
// 超过两个参数抛出异常
MethodReference methodReference = new MethodReference(callType, method);
// 保存到 handlerToEvent Map 中
verifyAndPutHandler(handlerToEvent,; methodReference, event, klass);
}
CallbackInfo info = new CallbackInfo(handlerToEvent);
// 保存 CallbackInfo
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
static class CallbackInfo {
final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;
final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;
CallbackInfo(Map<MethodReference, Lifecycle.Event> handlerToEvent) {
mHandlerToEvent = handlerToEvent;
mEventToHandlers = new HashMap<>();
// 遍历 handlerToEvent,保存在 mEventToHandlers 中
}
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,...) {
for (int i = handlers.size() - 1; i >= 0; i--) {
handlers.get(i).invokeCallback(source, event, mWrapped);
}
}
}
static final class MethodReference {
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
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;
}
}
}
}
总结
- Activity 或 Fragemnt 的生命周期是通过 ReportFragment 实现的。
- 注册观察者,通过
反射
收集观察者中被OnLifecycleEvent
注解的方法,封装成ObserverWithState
保存在mObserverMap
中。 - 同步观察者状态。如果间隔多个状态,观察者会依次收到多个生命周期事件,直到状态一致。
- 收到事件时,从
mObserverMap
中获取观察者信息,通过反射回调观察者中的方法。
参考
[1]Lifecycle - developer
[2] Jetpack架构组件库-Lifecycle源码解析之知其所以然