前言
关键类介绍
Lifecycle
定义:
用于存储有关组件(如 activity 或 fragment)的生命周期状态的信息,并允许其他对象观察此状态。
- 它是一个
抽象类
,具体实现类为LifecycleRegistry
; - 内部提供了
addObserver(LifecycleObserver observer) 添加观察者
、removeObserver(LifecycleObserver observer)移除观察者
方法; - 内部封装了
State【状态】
、Event【事件】
枚举类,以及一系列事件状态处理方法;
@MainThread
@NonNull
public abstract State getCurrentState();
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY;
@Nullable
public static Event downFrom(@NonNull State state) {
switch (state) {
case CREATED:
return ON_DESTROY;
case STARTED:
return ON_STOP;
case RESUMED:
return ON_PAUSE;
default:
return null;
}
}
@Nullable
public static Event downTo(@NonNull State state) {
switch (state) {
case DESTROYED:
return ON_DESTROY;
case CREATED:
return ON_STOP;
case STARTED:
return ON_PAUSE;
default:
return null;
}
}
@Nullable
public static Event upFrom(@NonNull State state) {
switch (state) {
case INITIALIZED:
return ON_CREATE;
case CREATED:
return ON_START;
case STARTED:
return ON_RESUME;
default:
return null;
}
}
@Nullable
public static Event upTo(@NonNull State state) {
switch (state) {
case CREATED:
return ON_CREATE;
case STARTED:
return ON_START;
case RESUMED:
return ON_RESUME;
default:
return null;
}
}
@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");
}
}
@SuppressWarnings("WeakerAccess")
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
//传入的state是否存在
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
构成Activity生命周期的状态和事件,其对应关系图如下:
由上图我们可以很容易理解其中定义的方法:
//根据传入的state获取逆序【生命周期结束方向】需要向下移动的事件
public static Event downFrom(@NonNull State state) {
switch (state) {
case CREATED:
return ON_DESTROY;
case STARTED:
return ON_STOP;
case RESUMED:
return ON_PAUSE;
default:
return null;
}
}
//根据传入的state获取逆序【生命周期结束方向】触发state的事件
public static Event downTo(@NonNull State state) {
switch (state) {
case DESTROYED:
return ON_DESTROY;
case CREATED:
return ON_STOP;
case STARTED:
return ON_PAUSE;
default:
return null;
}
}
//根据传入的state获取正序【生命周期上升方向】需要向下移动的事件
public static Event upFrom(@NonNull State state) {
switch (state) {
case INITIALIZED:
return ON_CREATE;
case CREATED:
return ON_START;
case STARTED:
return ON_RESUME;
default:
return null;
}
}
//根据传入的state获取正序【生命周期上升方向】触发state的事件
public static Event upTo(@NonNull State state) {
switch (state) {
case CREATED:
return ON_CREATE;
case STARTED:
return ON_START;
case RESUMED:
return ON_RESUME;
default:
return null;
}
}
LifecycleObserver
生命周期观察者
,用来监听Activity生命周期变化;其子类常用的有DefaultLifecycleObserver
、LifecycleEventObserver
;
public interface LifecycleEventObserver extends LifecycleObserver {
//生命周期变化回调
void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
LifecycleOwner
具有生命周期的类,对应被观察者
,提供获取getLifecycle()方法
,ComponentActivity
类实现该接口;
public interface LifecycleOwner {
@NonNull
Lifecycle getLifecycle();
}
LifecycleRegistry
Lifecycle
类的具体实现类,于ComponentActivity内部创建
,其内部持有LifecycleOwner
引用,通过维护mState【当前状态】
、mObserverMap【存储观察者对象】
等变量实现生命周期同步以及分发;
关键类UML类图关系
小结:
LifecycleOwner
作为被观察者,其被ComponentActivity
实现,同时ComponentActivity
内部持有LifecycleRegistry
对象,其提供添加、移除观察者LifecycleObserver
方法,而从持有注册的观察者集合,一旦Activity生命周期变化时,LifecycleOwner
便会触发LifecycleRegistry
对象中的方法,并由LifecycleRegistry
将事件分发给注册的观察者们;
观察者注册
注册观察者,最终调用的是LifecycleRegistry.addObserver方法
,如下:
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
//当前生命周期状态
private State mState;
//持有的LifecycleOwner
private final WeakReference<LifecycleOwner> mLifecycleOwner;
private int mAddingObserverCounter = 0;
private boolean mHandlingEvent = false;
private ArrayList<State> mParentStates = new ArrayList<>();
public void addObserver(@NonNull LifecycleObserver observer) {
//先进行线程校验,确保执行在主线程中;
enforceMainThreadIfNeeded("addObserver");
//如果当前mState状态是DESTROYED,则initialState赋值为DESTROYED,否则设置为INITIALIZED
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//将观察者observer和initialState保存成ObserverWithState对象,内部又会将observer包装成LifecycleEventObserver,以便后续进行Event分发;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//mObserverMap是支持在遍历过程中进行添加、删除操作,内部持有HashMap对象;
//以LifecycleObserver为K,Entry<LifecycleObserver,ObserverWithState>为Value进行存储,其中Entry<LifecycleObserver,ObserverWithState>是双向链表结构;
//可以简单理解成 内部存储了【所有观察者以及其对应State】的集合!!!
//1.先以LifecycleObserver为K进行查找,如果查找到,返回对应的ObserverWithState对象,否则按键值对存储,返回null
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
//2.当previous!=null,说明之前已存储过,不必进行后续事件处理
if (previous != null) {
return;
}
//mLifecycleOwner在LifecycleRegistry构造方法中初始化,是个虚引用,这里获取主要是为了检查LifecycleOwner是否已被回收
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
//如果获取不到LifecycleOwner对象,则直接返回
return;
}
//当前是否处于添加上一个observer 的状态下(即上一个observer的添加还没走完过程)|| 当前是否处于event事件处理中【主要是为了防止多次进行sync操作】
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
//3.计算新加入的LifecycleObserver需要同步的状态
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
//4. 当新加入的observer的mState小于目标状态时且observer没有被移除时,向observer分发生命周期事件
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
//5.将当前statefulObserver.mState 的状态保存在mParentState集合中
pushParentState(statefulObserver.mState);
//6.根据状态获取下一个触发的事件
final Event event = Event.upFrom(statefulObserver.mState);
if (event == null) {
throw new IllegalStateException("no event up from " + statefulObserver.mState);
}
//7.分发事件给注册的statefulObserver,最终会回调`LifecycleEventObserver.onStateChanged方法`
//这里需要注意下粘性事件问题,即使addObserver方法在onResume中调用,由于初始化时statefulObserver.mState为INITIALIZED,而mState已经为ON_RESUME,同样会分发ON_CREATE、ON_START事件~~~
statefulObserver.dispatchEvent(lifecycleOwner, event);
//8.将当前statefulObserver.mState 的状态从mParentState集合中移除
popParentState();
//9.计算下一个需要同步的状态
targetState = calculateTargetState(observer);
}
//10.当前不处于添加观察者、调度事件中,同步 state 给 所有observerWithState 并实现状态回调
if (!isReentrance) {
sync();
}
mAddingObserverCounter--;
}
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;
}
}
其中sync()
方法如下:
//同步 state 给 所有observerWithState 并实现状态回调
private void sync() {
//1.先判断lifecycleOwner是否已被回收,如果回收则直接抛异常
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.");
}
//2.同步所有观察者状态,直到和mState一致;
while (!isSynced()) {
mNewEventOccurred = false;
//mObserverMap中观察者们根据加入的顺序形成链表,新加入的位于链表结构的末尾;
//3.如果mState比链表中第一个加入的观察者状态还小,说明所有观察者状态都大于mState,根据状态和事件对应图对应逆序方向,应该【向下更新】,例如【RESUMED-->ON_PAUSE】`backwardPass方法会倒序遍历链表进行事件分发`
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
//4.如果mState比链表中最后添加的观察者状态还大,说明所有观察者状态都小于mState,
// 根据状态和事件对应图对应正序方向,应该【向上更新】,例如【CREATED-->ON_START】`forwardPass方法会正序遍历链表进行事件分发`
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
//是否所有观察者状态都同步完毕
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;
}
//【向上更新】,例如【CREATED-->ON_START】正序遍历链表进行事件分发
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 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
final Event event = Event.upFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event up from " + observer.mState);
}
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
//向下更新,例如【RESUMED-->ON_PAUSE】,倒序遍历链表进行事件分发
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();
}
}
}
小结
-
LifecycleRegistry
内部通过mObserverMap
对象持有所有注册的观察者们
,当调用addObserver
方法添加新的观察者的时候,会设置初始化默认值为DESTROYED
或INITIALIZED
,与当前mState
进行状态比较,不一致则进行状态同步以及生命周期事件分发,同时会判断当前是否处于添加观察者、调度事件中,如果不处于,会遍历所有注册的观察者进行事件同步分发操作;
生命周期分发
我们在androidx.core.app.ComponentActivity.onCreate
方法中可以看到:
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
其中ReportFragment.injectIfNeededIn(this):
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) {
//模仿Glide生命周期管理,添加空白Fragment监听生命周期
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
这里我们重点看下LifecycleCallbacks.registerIn(activity)方法
,其中LifecycleCallbacks
类如下:
@RequiresApi(29)
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
static void registerIn(Activity activity) {
activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
}
@Override
public void onActivityCreated(@NonNull Activity activity,
@Nullable Bundle bundle) {
}
@Override
public void onActivityPostCreated(@NonNull Activity activity,
@Nullable Bundle savedInstanceState) {
dispatch(activity, Lifecycle.Event.ON_CREATE);
}
@Override
public void onActivityStarted(@NonNull Activity activity) {
}
@Override
public void onActivityPostStarted(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_START);
}
@Override
public void onActivityResumed(@NonNull Activity activity) {
}
@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 onActivityPaused(@NonNull Activity activity) {
}
@Override
public void onActivityPreStopped(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_STOP);
}
@Override
public void onActivityStopped(@NonNull Activity activity) {
}
@Override
public void onActivitySaveInstanceState(@NonNull Activity activity,
@NonNull Bundle bundle) {
}
@Override
public void onActivityPreDestroyed(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_DESTROY);
}
@Override
public void onActivityDestroyed(@NonNull Activity activity) {
}
}
因此当Activity生命周期变化的时候,会通过dispatch
方法进行生命周期事件分发:
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);
}
}
}
dispatch
方法中会调用LifecycleRegistry.handleLifecycleEvent(event)
方法:
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
moveToState(event.getTargetState());
}
//进行状态同步,其中sync()方法我们上面已经分析过,其中会遍历所有存储的观察者进行生命周期事件分发
private void moveToState(State next) {
if (mState == next) {
return;
}
mState = next;
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
return;
}
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
小结
生命周期分发流程整体比较简单,通过注册ActivityLifecycleCallbacks
回调监听Activity生命周期变化,当生命周期变化时,最终会调用LifecycleRegistry.handleLifecycleEvent
方法进行所有注册的观察者状态同步以及生命周期事件分发;文章来源:https://www.toymoban.com/news/detail-517755.html
结语
如果以上文章对您有一点点帮助,希望您不要吝啬的点个赞加个关注,您每一次小小的举动都是我坚持写作的不懈动力!ღ( ´・ᴗ・` )文章来源地址https://www.toymoban.com/news/detail-517755.html
到了这里,关于Android JetPack深入分析Lifecycle源码的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!