阅读LifeCycle 的源码,需要一定的技术基础
1. 反射 市面上大部分框架基本上都使用了反射原来,而且配合反射的使用过程中还会使用 Map <class,结果> 来缓存反射后的结果,为后续加载提速,已空间换时间的方法
2. 注解 @Target @Retention 元注解等含义,要不然理解起来也是比较片面的,
3 lifeCycle观察者模式是有状态驱动事件来完成工作的,具体的流程会在下面分析,但是在分析的过程你需要建立这样的一个概念,要不然很容易给自己搞的很头疼,至于Lifecycle 未什么要设计的这么复杂,原因就是Lifecycle是jetpack所有事件的基础,他在创建之初服务的对象就不单单是一个观察者
如果你觉得以上问题都Ok ,那么下面就可以开始代码的阅读了
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifecycle.addObserver(MyObserve())
}
}
class MyObserve :LifecycleObserver{
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart(){
}
}
源码分析的过程就是在 lifecycle.addObserver(MyObserve()) 这里开始的, 这个方法是将观察者 MyObserve 与被观察者 Activity(LifecycleOwner) 建立绑定关系
建立绑定关系的代码在LifecycleRegistry里面
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
enforceMainThreadIfNeeded("addObserver");
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
if (previous != null) {
return;
}
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--;
}
这里我们要关注 他拿到了LifecycleObserver observer 干了什么,所以就要跟着 observer 来继续分析 ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); 这里的代码
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;
}
}
将observer 通过 Lifecycling.lifecycleEventObserver 转换成了 LifecycleEventObserver mLifecycleObserver, 继续分析
@NonNull
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;
}
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);
}
这里对这个object 做了一下分析, 由于我们传入的是一个LifecycleObserver ,都不满足 return 条件,就看下面的解析的过程,看到下面的代码,如果你研究过注解和反射就知道, 下面代码的含义就是在运行时通过class 反射获取所有代码注解的方法,在通过注解获取元注解的事件来做最后关联,将他们包装成LifecycleEventObserver 最后返回,到这里解析这条链路就结束了,在准备知识的过程中,提到过配合反射 大部分框架都会使用map 来做缓存,我们可以回到 observer 方法中的继续看一下下面代码
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
可以看到了这个里面有,不仅这里面有,framework 中也包含了非常多的这种用法
observer 的后续代码就是就是通过状态来判断是否需要同步状态,讲到这里就要讲一下lifecycle 的状态与事件的机制
至于这个流程是如何来的呢,看下面代码
@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");
}
可以看到 ON_CREATE ON_STOP 执行后,得到的都是 State.CREATED 这个状态 ON_START与 ON_PAUSE 得到的都是 State.STARTED 这个状态,如果你想明白了这里,其实addObserver方法后续同步状态的代码块的路基就明白了,
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
enforceMainThreadIfNeeded("addObserver");
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
if (previous != null) {
return;
}
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--;
}
在创建之初的的状态是INITIALIZED ,没有之前的同步状态结束,如果存在绑定出现状态不一致,就会启动的他下年的While 判断,至于为什么用while,如果状态差大于1 ,就会同步多次, 这个情况大概会出现在on Start 等状态中绑定,会就存在状态不一致的情况
到了这里绑定的流程就完成了, 下面分析时间分发的流程
事件分发的流程
事件分发是从 ComponentActivity 这个activity 中的onCreate 方法里面开始,这里比较有意思的是他的调用过程也借鉴了Glide 的方式,给这个Activity 添加了一个没有页面的activity 来感知activity 的生命周期状态,
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);
mActivityResultRegistry.onRestoreInstanceState(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
ReportFragment injectIfNeededIn
public static void injectIfNeededIn(Activity activity) {
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
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();
}
}
这么做的优势是什么?
1.代码分离
- 如果老版本activity 想要实现这个功能,可以主动添加这个fragment,后续功能自动封装实现
知道了消息是有谁来发出,我们就来跟踪一个 onStart 事件看看接下来的流程
@Override
public void onStart() {
super.onStart();
dispatchStart(mProcessListener);
dispatch(Lifecycle.Event.ON_START);
}
这里是发送事件
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) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
根据不同的角色来进行不同事件分发,我们查看的ComponentActivity 实现了LifecycleOwner,看下面的代码
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
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.
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;
}
这里就是事件和状态容易让人搞乱的地方,他是根据当前状态和上一个状态来判断当前是前进操作还是后退操作,
而从while 这个操作来看的话,这个状态是一步一步来操作的, 如果 观察者现在状态是2,而被观察现在的状态是5,那么观察者的状态变化是从 2-->3-->4-->5,这种设计模式是为了更好的适配其他jetpack,对外提供状态
接下来就是事件分发
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;
}
}
就又回到了我们绑定观察者分析时候的方法,最后event 流向了 mLifecycleObserver.onStateChanged(owner, event); 方法
class CompositeGeneratedAdaptersObserver implements LifecycleEventObserver {
private final GeneratedAdapter[] mGeneratedAdapters;
CompositeGeneratedAdaptersObserver(GeneratedAdapter[] generatedAdapters) {
mGeneratedAdapters = generatedAdapters;
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
MethodCallsLogger logger = new MethodCallsLogger();
for (GeneratedAdapter mGenerated: mGeneratedAdapters) {
mGenerated.callMethods(source, event, false, logger);
}
for (GeneratedAdapter mGenerated: mGeneratedAdapters) {
mGenerated.callMethods(source, event, true, logger);
}
}
}
到 CompositeGeneratedAdaptersObserver 后 找到反射后的方法 cellMethods 方法就完成了