Lifecycle 是 AAC 中帮助我们构建生命周期感知组件的框架.
常见的情况
在客户端开发中, 我们的组件需要页面的状态做出不同的响应.
举个例子, Activity 中有个播放器player, 为了更好的用户体验我们通常需要 :
- 在 Activity#onPasuse() 时暂停播放
- 在 Activity#onResume() 时继续播放
- 在 Activity#onDestory() 时销毁播放器和监听器
常见的模式是在 Activity/Fragment 的生命周期方法中实现依赖组件的操作。然而,这种模式会导致糟糕的代码组织和错误的扩散. 通过使用生命周期感知组件,您可以将依赖组件的代码移出生命周期方法,并移到组件本身。
使用Lifecycle
class DetailActivity :AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail)
getLifecycle().addObserver(object: DefaultLifecycleObserver {
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
player.start()
}
override fun onPause(owner: LifecycleOwner) {
super.onPause(owner)
player.pause()
}
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
player.release()
}
}
}
}
核心组件
Lifecycle 包括很多包: ViewModel, LiveData, ktx扩展, RxJava转LiveData扩展...
本篇讨论的只是
lifecycle-runtime
:
- LifecycleOwner : 生命周期持有者, 被观察的对象.
- LifecycleObserver : 生命周期观察者.
- Lifecycle : 表明生命周期的接口.
1. LifecycleOwner
LifecycleOwner 只定义了一个方法 Lifecycle getLifecycle()
返回 Lifecycle 对象.
当前的 ComponentActivity & Fragment 都实现了这个接口.
/**
* A class that has an Android lifecycle. These events can be used by custom components to
* handle lifecycle changes without implementing any code inside the Activity or the Fragment.
*
* @see Lifecycle
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public interface LifecycleOwner {
@NonNull
Lifecycle getLifecycle();
}
1.1 LifecycleOwner分发事件
以 Activity 为例, ComponentActivity 实现了 LifecycleOwner 接口, 并返回了 Lifecycle 的实现类对象 LifecycleRegistry.
- 通过一个没有界面的
ReportFragment
来充当生命周期的辅助类(这一点和Glide类似)
public class ComponentActivity extends Activity
implements LifecycleOwner{
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//创建 ReportFragment
ReportFragment.injectIfNeededIn(this);
}
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
- 在 ReportFragment 的生命周期回调中都调用了
dispatch(Lifecycle.Event.XXXX)
方法.
public class ReportFragment extends Fragment {
public static void injectIfNeededIn(Activity activity) {
// ProcessLifecycleOwner should always correctly work and some activities may not extend
// FragmentActivity from support lib, so we use framework fragments for activities
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();
}
}
@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);
// just want to be sure that we won't leak reference to an activity
mProcessListener = null;
}
}
-
dispatch(event)
调用((LifecycleRegistry) lifecycle).handleLifecycleEvent(event)
, 而 LifecycleRegistry 怎么处理 event 的接下来会分析.
public class ReportFragment extends Fragment {
private void dispatch(Lifecycle.Event event) {
Activity activity = getActivity();
//为旧版本support.v7.app.AppCompatActivity兼容的, 已经标记为deprecated
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
//androidx.fragment.app.FragmentActivity
if (activity instanceof LifecycleOwner) {
//Lifecycle对象由Activity实现LifecycleOwner接口返回
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
//调用Lifecycle # handleLifecycleEvent(event)方法来分发生命周期
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
}
2. LifecycleObserver
我们的组件实现 LifecycleObserver 接口, 标记着组件是生命周期的观察者.
/**
* Marks a class as a LifecycleObserver. It does not have any methods, instead, relies on
* {@link OnLifecycleEvent} annotated methods.
* <p>
* @see Lifecycle Lifecycle - for samples and usage patterns.
*/
@SuppressWarnings("WeakerAccess")
public interface LifecycleObserver {
}
但他是一个空接口, 参照 Lifecycle 的注释, 在不同的JDK版本上有不同的实现.
JDK版本 | 实现 |
---|---|
1.8之前 |
@OnLifecycleEvent 方法注解 |
1.8 | DefaultLifecycleObserver |
两种方式都是通过 Lifecycing 的 getCallback(Object object)
创建.
2.1 注解实现
@OnLifecycleEvent
是运行时注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnLifecycleEvent {
Lifecycle.Event value();
}
具体实现在 ClassesInfoCache 类中:
class ClassesInfoCache {
//判断是否有注解
boolean hasLifecycleMethods(Class klass) {
if (mHasLifecycleMethods.containsKey(klass)) {
return mHasLifecycleMethods.get(klass);
}
Method[] methods = getDeclaredMethods(klass);
for (Method method : methods) {
//根据 OnLifecycleEvent 注解
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation != null) {
//生成CallbackInfo对象, 保存到 mCallbackMap 中
createInfo(klass, methods);
return true;
}
}
mHasLifecycleMethods.put(klass, false);
return false;
}
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
Class superclass = klass.getSuperclass();
Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
if (superclass != null) {
//getInfo() 又会递归调用createInfo(), 解析所有的 @OnLifecycleEvent 注解
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);
}
}
// 解析 @OnLifecycleEvent 注解方法,保存到 info 中
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);
//以class名字作为key, 添加到mCallbackMap中
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
使用注解时, Lifecycying 的 getCallBack()
返回的是 ReflectiveGenericLifecycleObserver, 在 onStateChanged()
时反射调用 mInfo 中的方法.
class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
//反射调用对应的 event回调
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
2.2 DefaultLifecycleObserver
借助1.8的新特性 default method
, 我们不必实现所有的接口方法.
public interface DefaultLifecycleObserver extends FullLifecycleObserver {
@Override
default void onCreate(@NonNull LifecycleOwner owner) {
}
@Override
default void onStart(@NonNull LifecycleOwner owner) {
}
.....
@Override
default void onDestroy(@NonNull LifecycleOwner owner) {
}
}
此时 Lifecycing 返回的是 FullLifecycleObserverAdapter, onStateChanged()
时会调用 FullLifecycleObserver 中的回调.
class FullLifecycleObserverAdapter implements GenericLifecycleObserver {
private final FullLifecycleObserver mObserver;
FullLifecycleObserverAdapter(FullLifecycleObserver observer) {
mObserver = observer;
}
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
switch (event) {
case ON_CREATE:
mObserver.onCreate(source);
break;
.......
case ON_DESTROY:
mObserver.onDestroy(source);
break;
case ON_ANY:
throw new IllegalArgumentException("ON_ANY must not been send by anybody");
}
}
}
3. Lifecycle
Lifecycle 保存了 LifecycleOwner 的生命周期信息, 来给 LifecycleObserver 观察.
他使用了两个枚举来跟踪 LifecycleOwner 生命周期状态:
3.1 Event
生命周期事件, 对应着 Activity/Fragment 中的生命周期回调.
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
3.2 State
提供了五种生命周期状态和一个判断生命周期的方法.
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
//判断组件的状态是否在给定的state之后
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
3.3 State和Event
如图, State 是状态的节点, 而 Event 则是从一个State 到达另外一个 State 的过程.
lifecycle_state_event.png
3.4 Lifecycle的实现类
除了枚举, Lifecycle 还定义了三个抽象方法, 标准的状态机模式
//添加观察者
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer)
//移除观察者
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
//获取当前的状态
@MainThread
@NonNull
public abstract State getCurrentState();
在SDK中已经提供了他的一个实现类 LifecycleRegistry, 在 ComponentActivity & Fragment 中的 getLifecycle()
返回的就是该实现.
public class ComponentActivity extends Activity implements LifecycleOwner {
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
public class Fragment implements LifecycleOwner {
LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
4. LifecycleRegistry
LifecycleRegistry 实现了 Lifecycle 的三个抽象方法.
4.1. handleLifecycleEvent(event)
处理生命周期通过 handleLifecycleEvent(event)
处理:
public class LifecycleRegistry extends Lifecycle {
private int mAddingObserverCounter = 0;
private boolean mHandlingEvent = false;
private boolean mNewEventOccurred = false;
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
private void moveToState(State next) {
if (mState == next) {
return;
}
mState = next;
// mHandlingEvent 在sync()前后标记, 在sync()完成前为true
// mAddingObserverCounter在addObserver()中被递增递减, 在addObserver()完成前 != 0
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// 不需要sync()
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
// sync() 会把状态的变化转化为生命周期事件,然后转发给 LifecycleObserver
sync();
mHandlingEvent = false;
}
}
4.1.1 sync()
sync() 负责处理Aticivty/Fragmet 生命周期变化时, 同步 Observer 的状态, 从而触发 Observer 的状态回调.
LifecycleRegistry 使用 FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap
作为保存 Observer 和 State 映射关系的容器, 他保证 :
插入顺序 Observer1 < Observer2 时, Observer1.State1 >= Observer2.State2.
所以 isSynced()
判断是否同步完成, 只需要判断 mObserverMap
头尾的 State 相等eldestObserverState == newestObserverState
, 并且都等于最新的状态 mState
public class LifecycleRegistry extends Lifecycle {
//使用弱引用指向LifecycleOwner
private final WeakReference<LifecycleOwner> mLifecycleOwner;
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
/**
* Custom list that keeps observers and can handle removals / additions during traversal.
*
* Invariant: at any moment of time for observer1 & observer2:
* if addition_order(observer1) < addition_order(observer2), then
* state(observer1) >= state(observer2),
* mObserverMap中元素的state顺序和插入的顺序是相反的
*/
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
// happens only on the top of stack (never in reentrance),
// so it doesn't have to take in account parents
private void sync() {
//如果owner被回收了, 就不继续分发
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
+ "new events from it.");
return;
}
//一直同步到isSynced()为true
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<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
//mObserverMap中元素的state和插入的顺序是相反的, 参照注释
//判断是否同步完成, 只需要判断头尾元素都等于最新的state
private boolean isSynced() {
if (mObserverMap.size() == 0) {
return true;
}
State eldestObserverState = mObserverMap.eldest().getValue().mState;
State newestObserverState = mObserverMap.newest().getValue().mState;
return eldestObserverState == newestObserverState && mState == newestObserverState;
}
}
而while循环中的同步处理又分为两种情况 backwardPass()
和 forwardPass()
4.1.2 backwardPass()
因为 mObserverMap
中 Observer 的 State 是递减的, 所以如果第一个 Observer 的 State 小于等于 LifecycleRegistry 的 mState
, 那么 mObserverMap
中所有 Observer 的 State 都小于等于 mState
.
如果第一个 Observer 的 State 就大于 mState
, 那么 mObserverMap
后面可能还有大于 mState
的 Observer. 因为 mObserverMap
中 Observer 的 State 是递减的, 所以要从尾到头开始遍历.
private void backwardPass(LifecycleOwner lifecycleOwner) {
// 使用mObserverMap的反向迭代器, 从尾向头遍历
Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
//如果分发过程中有新的事件, 就停止分发
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
ObserverWithState observer = entry.getValue();
//如果observer.mState大于mState, 就向下调整
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
//向下调整的逻辑
Event event = downEvent(observer.mState);
pushParentState(getStateAfter(event));
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
向下调整的逻辑分解一下:
1.downEvent(observer.mState)
获取State节点的下一个Event
private static Event downEvent(State state) {
switch (state) {
case INITIALIZED:
throw new IllegalArgumentException();
case CREATED:
return ON_DESTROY;
case STARTED:
return ON_STOP;
case RESUMED:
return ON_PAUSE;
case DESTROYED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException("Unexpected state value " + state);
}
2. pushParentState(getStateAfter(event)) & popParentState()
这里引入了一个新的对象 ArrayList<State> mParentStates
来保存目标 State, 这是为了应对重入的场景:
// we have to keep it for cases:
// void onStart() {
// mRegistry.removeObserver(this);
// mRegistry.add(newObserver);
// }
// newObserver should be brought only to CREATED state during the execution of
// this onStart method. our invariant with mObserverMap doesn't help, because parent observer
// is no longer in the map.
private ArrayList<State> mParentStates = new ArrayList<>();
private void popParentState() {
mParentStates.remove(mParentStates.size() - 1);
}
private void pushParentState(State state) {
mParentStates.add(state);
}
重入的部分比较难理解, 参考注释中的例子, 在 observer.onStart()
中先 mRegistry.removeObserver(this)
移除自己, 然后添加observer mRegistry.add(newObserver)
.
- observer的 State 经过
forwardPass()
从INITIALIZED
变成CREATED
, 调用 observer.onCreate() - Activity 经过 onStart() 时通过
handleLifecycleEvent()
继续调用sync()
, observer 通过forwardPass()
从CREATED
变成STARTED
, 分发 observer.onStart().
注意此时分发未结束, 没有调用popParentState()
, 所以mParentStates
中仍然是 CREATED, observer 分发前的状态. - 这时
mRegistry.removeObserver(this)
移除掉observer, 这时mRegistry.add(newObserver)
添加了newObserver. 此时需要计算 newObserver 需要同步到的targetState
(在下面的addObserver(observer)
会提到), 此时mObserverMap
中已经没有 observer 的信息. 这时可以借助上一步保存的mParentStates
保存的 CREATED 来帮助我们计算 newOsberver 的targetState
. - 这时 observer 的
forwardPass
流程结束, 并且mObserverMap
中有了新的元素 newObserver, 不满足sync()
中isSynced()
的条件, 需要继续把 newObserver 同步到当前页面的状态STARTED
.
3. observer.dispatchEvent(lifecycleOwner, event)
通过 GenericLifecycleObserver 的 onStateChanged(owner, event)
来完成事件的分发.
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.getCallback(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.getCallback(observer)
中不管你使用注解+反射的方式, 还是Java8的default method方式, 都会使用适配器模式, 生成对应的 GenericLifecycleObserver 实现类.
forwardPass()
逻辑与 backwardPass()
相反, 不多赘述.
4.2. add & remove Observer
向 mObserverMap
中添加和删除 Observer.
需要注意的是 calculateTargetState()
中使用了暂存的 mParentStates
来处理 observer 重入的情况.上面已经分析过.
//观察者的集合
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
//初始化状态
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//不能重复添加同一个Observer, 保证唯一性
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
if (previous != null) {
return;
}
//LifecycleOwner即Fragment/Activity
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
//如果owner为空, 说明页面被回收了, 直接return
if (lifecycleOwner == null) {
// it is null we should be destroyed. Fallback quickly
return;
}
// isReentrance表示是重入执行,通过mAddingObserverCounter或mHandlingEvent判断。
// mHandlingEvent是在前文的sync方法前后进行标记的,也就是“在分发事件”。
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
// 计算要同步到的目标状态,是LifecycleRegistry上一个添加的Observer的状态、上一层被分发事件的Observer的状态
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--;
}
@Override
public void removeObserver(@NonNull LifecycleObserver observer) {
mObserverMap.remove(observer);
}
private State calculateTargetState(LifecycleObserver observer) {
Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);
State siblingState = previous != null ? previous.getValue().mState : null;
State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)
: null;
return min(min(mState, siblingState), parentState);
}
网友评论