首先们要明确Lifecycle中两个枚举值,这两个枚举值和生命周期的状态有着直接关系,我们可以先记住,后面会看到使用的地方
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY;
//与state的对应关系
public State getTargetState() {
switch (this) {
//这里看到ON_CREATE和ON_STOP都对应State.CREATED ,在回退生命周期的时候就会用到
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");
}
...
}
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
下面我们先看下,我们日常开发中是如何使用Lifecycle来监听声明周期的,首先我们需要创建一个监听器
//实现LifecycleObserver接口
class MyLifecycleObserver : LifecycleObserver {
//必须声明对应生命周期的注解 才会回调对应方法 以下同理
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() {}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {}
}
然后在Activity中通过以下代码添加监听
//Activity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val observer = MyLifecycleObserver()
lifecycle.addObserver(observer)
}
当Activity执行到相应的生命周期方法的时候就会回调监听中定义的方法。那具体的实现是怎么做到的呢?首先我们看下lifecycle,定义在ComponentActivity中
//持有了Activity对象
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
//enforceMainThread默认true
private LifecycleRegistry(@NonNull LifecycleOwner provider, boolean enforceMainThread) {
//Activity对象 用软引用存储
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
mEnforceMainThread = enforceMainThread;
}
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
我们发现lifecycle其实是一个LifecycleRegistry对象,addObserver调用的也是其中的方法,继续看代码
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
//检查是否是主线程,也就是说我们添加监听只能在主线程中调用
enforceMainThreadIfNeeded("addObserver");
//初始状态INITIALIZED
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//注意这个对象 可以把它看成一个监听对象
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//存储到mObserverMap中 因为可能存在多个监听 这里做处理
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
//如果注册过 直接返回
if (previous != null) {
return;
}
//如果Activity对象为null直接返回
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
// it is null we should be destroyed. Fallback quickly
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();
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
mAddingObserverCounter--;
}
下面看下ObserverWithState这个对象的初始化
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
继续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;
}
//获取class对象
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);
}
继续看ReflectiveGenericLifecycleObserver
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
//解析监听器对象信息(我们声明的对应生命周期注解的方法) 存储到mInfo中,具体解析流程不做分析 可自行查看源码
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
//生命周期改变时候调用该方法 event为对应的生命周期
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
目前为止做的工作就是,把我们声明的监听器的信息进行解析并存储了起来。
监听已经注册好了,那么下来就要看看当 生命周期发生改变的时候,是怎么进行分发的了,我们查看ComponentActivity的onCreate()
protected void onCreate(@Nullable Bundle savedInstanceState) {
// Restore the Saved State first so that it is available to
// OnContextAvailableListener instances
mSavedStateRegistryController.performRestore(savedInstanceState);
mContextAwareHelper.dispatchOnContextAvailable(this);
super.onCreate(savedInstanceState);
//关键点就是这里
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
下面看ReportFragment
public static void injectIfNeededIn(Activity activity) {
//版本判断进行teshu 处理
if (Build.VERSION.SDK_INT >= 29) {
// On API 29+, we can register for the correct Lifecycle callbacks directly
LifecycleCallbacks.registerIn(activity);
}
// Prior to API 29 and to maintain compatibility with older versions of
// ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and
// need to support activities that don't extend from FragmentActivity from support lib),
// use a framework fragment to get the correct timing of Lifecycle events
//声明了一个没有UI页面的Fragment
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();
}
}
Glide大家应该都用过,对于生命周期的感知就是通过添加Fragment的方式来完成的,这里其实也是一样的,我们看下29及以后的处理
@RequiresApi(29)
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
static void registerIn(Activity activity) {
//直接注册了回调 29以前应该是没有吧 没有去深究
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的具体实现
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) {
}
}
既然是通过Fragment进行分发,那么显然我们直接看ReportFragment的生命周期就好了,我们以onResume为例,其余都是一样的处理。
public void onResume() {
super.onResume();
dispatchResume(mProcessListener);
//上面我们看29及之后的处理的时候 也看到该方法的调用了,这就是分发的方法,参数是对应的生命周期枚举
dispatch(Lifecycle.Event.ON_RESUME);
}
下面看下diapatch的实现
private void dispatch(@NonNull Lifecycle.Event event) {
//再次判断版本
if (Build.VERSION.SDK_INT < 29) {
// Only dispatch events from ReportFragment on API levels prior
// to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks
// added in ReportFragment.injectIfNeededIn
dispatch(getActivity(), event);
}
}
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
//这里已经弃用 我们不用关心
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
if (activity instanceof LifecycleOwner) {
//获取LifecycleRegistry对象 我们上面添加监听的时候就是通过LifecycleRegistry添加的
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
然后我们看LifecycleRegistry的handleLifecycleEvent方法
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
//主线程判断
enforceMainThreadIfNeeded("handleLifecycleEvent");
//注意这里这里是根据Event来判断当前state状态的 这里可以看最开始我们提到的枚举值
moveToState(event.getTargetState());
}
//生命周期状态的处理
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.
//如果当前状态值小于监听器状态值 则说明是销毁流程
//比如我们目前是onResume 走到了onPause State.STARTED < State.RESUMED
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;
}
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是ObserverWithState对象 我们上面注册时候 注册的就是这个
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
然后我们再看下ObserverWithState
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
//ReflectiveGenericLifecycleObserver 对象上面注册时候说过
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;
}
}
然后看ReflectiveGenericLifecycleObserver
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
//上面说过mInfo 存储了监听器的信息 我们解析的注解方法都在这里
mInfo.invokeCallbacks(source, event, mWrapped);
}
继续看CallbackInfo
void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
//event 通过Event找到对应的方法
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);
}
}
}
到这里我们就已经分析完Lifecycle生命周期的分发流程了,总结一下其实很简单:
解析监听器中声明的对应生命周期的注解方法存储起来,在Activity生命周期改变的时候获取对应的注解方法进行调用。
细节点
- 生命周期分发
29以前是通过添加空的Frgament,然后在Fragment中进行分发;
29之后是通过LifecycleCallbacks直接进行分发。 - State判断
不同的Event枚举对应相同的State值,在onResume后复用之前的状态来节省判断变量,达到生命周期正序和逆序的处理。
可能有些细节没有讲到,但是整体的思路和处理应该很清晰,如有哪里讲的不对,请留言。
网友评论