第一章 Android: 彻底搞懂Lifecycle——使用篇
第二章 Android: 彻底搞懂Lifcycle——原理篇
上一篇我们认识了Lifecycle,并且学会了它怎么用。本篇再深入了解下它的原理,你会明白它是怎么做到感知生命周期的?
创作此时的最新稳定版是:lifecycle-* 2.4.1
【一句话概括】
就是会向当前界面添加一个隐藏的fragment,由这个fragment来触发生命周期通知,然后观察者再做出具体的响应处理。
现在我们知道了思路,如需详细了解,咱们接着看源码。
先看Lifecycle抽象类,下面是Lifecycle 2.4.1的源码:
lifecycle-common-2.4.1.jar—— androidx.lifecycle.Lifecycle.java;
public abstract class Lifecycle {
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@NonNull
AtomicReference<Object> mInternalScopeRef = new AtomicReference<>();
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
@MainThread
@NonNull
public abstract State getCurrentState();
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY;
public static Event downFrom(@NonNull State state) {}
public static Event downTo(@NonNull State state) {}
public static Event upFrom(@NonNull State state) {}
public static Event upTo(@NonNull State state) {}
public State getTargetState() {}
}
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state)
}
}
Lifecycle是个抽象类,里面有添加/移除观察者的方法,还有两个枚举类Event和State:
【疑问】那么它是如何跟Activity/Fragment生命周期关联的呢?
在支持库 26.1.0 及更高版本中的 Fragment 和 Activity 已实现 LifecycleOwner 接口。已经是一个拥有生命周期的被观察者了。
可以在AppCompatActivity——>FragmentActivity——>ComponentActivity——>androidx.core.app.ComponentActivity中找到实现。
androidx.core:core:1.8.0-alpha06——androidx.core.app.ComponentActivity.java
@RestrictTo(LIBRARY_GROUP_PREFIX)
public class ComponentActivity extends Activity implements LifecycleOwner{
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);// [1]
@SuppressLint("RestrictedApi")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);// [2]
}
@CallSuper
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
mLifecycleRegistry.markState(Lifecycle.State.CREATED);// [3]
super.onSaveInstanceState(outState);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;// [4]
}
}
【疑问】那状态怎么改变?
其实是交给了ReportFragment来处理。
public class ReportFragment extends android.app.Fragment {
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
LifecycleCallbacks.registerIn(activity);// [1]
}
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();// [2]
manager.executePendingTransactions();
}
}
// [3]
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);
}
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);// [4]
}
@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);
}
...
@RequiresApi(29)
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
...
}
}
androidx.lifecycle:lifecycle-runtime:2.4.1——androidx.lifecycle.LifecycleRegistry.java
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
moveToState(event.getTargetState());
}
首先验证了下是否在主线程,event.getTargetState()获取此事件的状态,然后传递给moveToState方法,改变状态。
@NonNull
public State getTargetState() {
switch (this) {
case ON_CREATE:
case ON_STOP:
return State.CREATED;
case ON_START:
case ON_PAUSE:
return State.STARTED;
case ON_RESUME:
return State.RESUMED;
case ON_DESTROY:
return State.DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException(this + " has no target state");
}
这里的状态变化可以参考开头的关系时序图。
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;
}
moveToState方法:先判断与当前状态是否一致,不一致则调用sync方法改变状态;
sync 方法中会根据当前状态判断是向前还是向后。
【疑问】怎样是向前?怎样是向后呢?
我们可以对照开头的Lifecycle时序图,状态由INITIALIZED——>到RESUMED 是向前,反之就是向后。
向前和向后的代码实现差不多,这里就以向前为例:
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);// [1]
if (event == null) {
throw new IllegalStateException("no event down from " + observer.mState);
}
pushParentState(event.getTargetState());
observer.dispatchEvent(lifecycleOwner, event);
popParentState();// [2]
}
}
}
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);// [1]
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = event.getTargetState();
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);// [2]
mState = newState;
}
}
androidx.lifecycle.Lifecycling.java
public class Lifecycling {
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;
}
...
}
}
此方法通过判断观察者类型来转换对应的观察者适配器;
还记得上篇中,我们继承DefaultLifecycleObserver来自定义观察者类吗, DefaultLifecycleObserver的父类就是FullLifecycleObserver, 现在我们主要看下FullLifecycleObserverAdapter适配器怎么实现的。
androidx.lifecycle.FullLifecycleObserverAdapter.java
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);
}
}
}
在onStateChanged中判断事件类型,直接调用了观察者的生命周期回调方法。
简单吧,利用Fragment来分发状态,并计算出下一状态和事件后,经过适配器转换找到观察者的生命周期回调方法。这是目前新版的原理。
在之前的版本中是利用注解找到观察者的事件对应回调方法,然后通过反射进行调用的。现在新版中已经弃用了。
最后,官方是强烈推荐使用DefaultLifecycleObserver来代替@OnLifecycleEvent注解方式的。
【思考】你知道使用“Fragment来观察生命周期”这种方式的,还有哪些知名第三方库吗?
上一篇
Android: 彻底搞懂Lifecycle——使用篇
你如果觉得本文易懂,有帮助的话,可以动动小手,点个赞啥的支持一下,你的支持是对我创作最大的谷(鼓)粒(励)儿!