一 前言
在上篇文章,Lifecycle的使用 里,详细介绍了Lifecycle的使用,只需自定义MyObserver,实现LifecycleObserver,然后在Activity或者Fragment里,添加
lifecycle.addObserver(myObserver)
自定义的监听器myObserver即可实现对Activity或者Fragment的监听。那么这到底是怎么实现的呢。这篇文章阅读一下Lifecycle的源码。
二 Lifecycle的三剑客
在正式阅读源码之前,很有必要先介绍Lifecycle的几个名词,LifecycleOwner ,LifecycleObserver,Lifecycle。Lifecycle实现的过程,其实就是观察者模式。
-
Lifecycle
Lifecycle是一个抽象类,生命周期管理组件,UML定义图如下:
Lifecycle相当于被观察者角色,从图上可以看出,Lifecycle定义了添加观察者,移除观察者等方法,此外还定义了两个重要的枚举类,Event和State,他们的关系如下图所示,
-
LifecycleObserver
是生命周期的观察者,相当于观察者角色,它是一个空的接口。自定义的观察者需要实现此接口。
public interface LifecycleObserver {
}
-
LifecycleOwner
是一个接口,定义如下:
public interface LifecycleOwner {
@NonNull
Lifecycle getLifecycle();
}
可以看到,接口返回的是Lifecycle对象,Owner有拥有者的意思,也就是说,实现了该接口,就拥有了监听生命周期的能力。
三 源码分析
那分析源码从哪入手呢,对了,就从这句代码入手分析
lifecycle.addObserver(myObserver)
上一篇文章提到,只要将自定义的Observer添加到观察者队列,就能实现对生命周期的监听,所以要从这句代码开始分析,在分析之前,先分析一下自定义的观察者MyObserver。
1. 创建自定义Observer
在Lifecycle的使用中,有MyObserver的创建。创建自定义的Observer,要实现LifecycleObserver接口,上文Lifecycle的三剑客中知道LifecycleObserver是一个空的接口。
在定义MyObserver的时候,定义的方法要用 @OnLifecycleEvent注解,OnLifecycleEvent定义如下:
@Retention(RetentionPolicy.RUNTIME) // 1
@Target(ElementType.METHOD) // 2
public @interface OnLifecycleEvent {
Lifecycle.Event value(); // 3
}
@interface关键字定义了一个注解。
1 处说明注解可以保留到程序运行的时候,它会被加载到JVM中,在程序运行的时候可以获取到。
2 说明此注解是运用到方法上
3 定义了一个Lifecycle.Event类型的成员变量,注解的成员变量在注解的定义中以无形参的方法形式声明。
那这个注解有什么用呢?
在我关于注解的系列文章里提过,Android注解,这几篇文章就够了(一)注解处理器,Android注解,这几篇文章就够了(二)注解,Android注解,这几篇文章就够了(三)自己写个注解处理器,注解不是代码的一部分,自己不会生效,对注解的处理一般有两种:
- 通过反射提取,主要的方法是getAnnotation()
- 由开发者提供APT来提取并处理这些Annotation信息
在引入Lifecycle时,在app的build.gradle下,引入了以下代码:
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
这个就是处理这些注解信息的,所以Lifecycle使用的是注解处理器annotationProcessor来处理注解信息的。
2.getLifecycle()
在kotlin语言里lifecycle,但是在java里,其实是getLifecycle(),查找getLifecycle(),它在ComponentActivity里,新建的XXX_Activity继承自AppCompatActivity,然后继承自FragmentActivity,然后继承自ComponentActivity,ComponentActivity实现了接口LifecycleOwner,也就是说ComponentActivity具有了管理生命周期的能力,新建的XXX_Activity的父类具有了生命周期管理能力。
在getLifecycle()里直接返回了mLifecycleRegistry,
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
再看下这个mLifecycleRegistry,它是LifecycleRegistry对象,直接通过new生成。
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
所以,生命周期管理主要在这个LifecycleRegistry里实现。
3.LifecycleRegistry,addObserver,添加观察者
LifecycleRegistry的结构图如下,LifecycleRegistry继承自Lifecycle,另外,LifecycleRegistry还有一个内部类ObserverWithState。
addObserver()源码如下:
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
// 1
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// 2
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
// 3
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
// 4
if (previous != null) {
return;
}
// 5
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
// it is null we should be destroyed. Fallback quickly
return;
}
// 6
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
// 7
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
// 8
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);
}
// 9
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
mAddingObserverCounter--;
}
// 1 mState在LifecycleRegistry的构造方法里已经初始化为INITIALIZED,所以在addObserver里,initialState为INITIALIZED。
// 2 处构造了ObserverWithState对象,ObserverWithState构造方法传入的参数是观察者对象和初始化状态。ObserverWithState是LifecycleRegistry的内部类,从命名上来看,是带State的Observer,具体后面再提。
// 3处 mObserverMap的类型是FastSafeIterableMap<LifecycleObserver, ObserverWithState>,所以此处的作用是将observer,statefulObserver放入map中。
// 4处如果以前放过了,则返回空
// 5处通过弱应用获取LifecycleOwner
// 6 mAddingObserverCounter表示有多少个正在添加,初始化为0,mHandlingEvent是否有事件正在处理,默认为false。这两个变量看似是支持多线程的,但是没有同步锁,也没有volatile修饰,只能说不支持多线程,一次添加一个观察者,一次只能处理一个事件。isReentrance为false。
// 7处是calculateTargetState()方法,计算目标的状态。
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;
// 1
return min(min(mState, siblingState), parentState);
}
从mObserverMap获取ObserverWithState,并获取ObserverWithState的State。前面已经初始化为INITIALIZED,mState也为INITIALIZED,mParentStates为null,最终计算并返回的State为INITIALIZED。
// 1处返回的是当前的状态mState,mObserverMap中最后一个观察者状态,有重入的情况下parentState的状态,三者的最小值。
// 8 由于statefulObserver.mState和targetState都是INITIALIZED,所以并不会执行while循环。
那么这个while循环和calculateTargetState()方法作用是什么呢?
(1)从State角度来说,我们可以添加多个生命周期观察者,但是每次添加新的观察者的初始状态是INITIALIZED,需要把它同步到当前的生命周期状态,确切地说,是同步到一个不大于当前状态的targetState,在while循环中,反复调用calculateTargetState()方法,直到同步到当前的生命周期状态。
(2)从Event角度来说,即使在onResume( )中调用addObserver( )来添加观察者,观察者依然可以接收到onCreate和onStart事件,不过最终要同步到targetState。
最终的状态是,没有生命周期切换,没有添加新的观察者,mObserverMap中的所有观察者应该处于同一个生命周期状态。
// 9 isReentrance为false,执行sync()方法。
private void sync() {
// 1
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
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;
}
// 1通过弱引用获取lifecycleOwner
// 2 通过isSynced()判断是否需要进行处理,通过下面的分析,isSynced()返回true,所以不会执行while循环。
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;
}
我们已经添加了观察者,有且仅有一个观察者,并且状态和mState状态相同,此方法返回true。
至此,addObserver完成。
4.生命周期时间的分发
那么由谁负责生命周期事件的分发呢?
观察者已经添加完毕了,那么如何将生命周期的变化通知观察者呢?
答案还是在ComponentActivity的onCreate()方法中。
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
这里的 ReportFragment.injectIfNeededIn(this)就是问题的答案。继续追进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
activity.registerActivityLifecycleCallbacks(
new LifecycleCallbacks());
}
// 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();
}
}
可以看到,这里是向Activity里注入了一个没有页面的Fragment,所以这个ReportFragment才是真正分发生命周期的地方。
if (Build.VERSION.SDK_INT >= 29) {
// On API 29+, we can register for the correct Lifecycle callbacks directly
activity.registerActivityLifecycleCallbacks(
new LifecycleCallbacks());
}
(1)在API>29时,通过registerActivityLifecycleCallbacks监听生命周期。
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
@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) {
}
}
可以看到,在各个生命周期里,调用的是dispatch(Activity, Lifecycle.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);
}
}
}
activity是LifecycleOwner的实例,所有最终调用了LifecycleRegistry的handleLifecycleEvent()方法,最终的生命周期事件在handleLifecycleEvent()方法里进行处理。
(2) API<29时,是在ReportFragment的生命周期里分发事件。
@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( Lifecycle.Event event)方法,继续看这个方法,
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);
}
}
最终调用的是dispatch(getActivity(), event)。
综上,生命周期事件的分发,是向Activity里注入注入了ReportFragment,最终分发时间,调用的是dispatch(Activity activity,Lifecycle.Event event)方法进行分发,然后调用LifecycleRegistry的handleLifecycleEvent(Lifecycle.Event event)处理事件。
5. LifecycleRegistry事件的处理
生命周期事件的处理,是在LifecycleRegistry的handleLifecycleEvent处理的。
继续看handleLifecycleEvent()方法。
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
首先调用getStateAfter方法获取状态,根据Event,获取State,Event和State的对应关系图前面有。
static State getStateAfter(Event event) {
switch (event) {
case ON_CREATE:
case ON_STOP:
return CREATED;
case ON_START:
case ON_PAUSE:
return STARTED;
case ON_RESUME:
return RESUMED;
case ON_DESTROY:
return DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException("Unexpected event value " + event);
}
此时,event为ON_CREATE,因此获取的状态是CREATED。
接下来调用moveToState()方法。
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;
}
mState为INITIALIZED,next为CREATED,不会直接返回,接着我们修改当前状态变量mState为CREATED。没有事件正在处理,mHandlingEvent为false,也没有正在添加的观察者,mAddingObserverCounter为0,不会直接返回。
接下来调用sync()方法。
sync()方法前面有,在这里再贴出来。
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);
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
先调用isSynced方法,
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;
}
mState为CREATED,mObserverMap中的ObserverWithState对象为INITIALIZED,因此返回false,接着执行while循环。
因为CREATED大于INITIALIZED,因此会执行 forwardPass(lifecycleOwner)方法。
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
// 1
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}
// 1 这个方法的功能是,获取观察者的Iterator, 并遍历Iterator比较状态,最终调用ObserverWithState的dispatchEvent()方法进行分发事件。里面有个重要的参数是upEvent()方法。
private static Event upEvent(State state) {
switch (state) {
case INITIALIZED:
case DESTROYED:
return ON_CREATE;
case CREATED:
return ON_START;
case STARTED:
return ON_RESUME;
case RESUMED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException("Unexpected state value " + state);
}
传递的事observer.mState,为INITIALIZED,因此此方法获取的时间是ON_CREATE。
除了upEvent方法,还有downEvent方法
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);
}
upEvent()方法获取state升级经历的事件,downEvent()获取state降级经历的事件。
状态之间的事件,事件之后的状态,状态之间的大小,可以看下面这张图,非常清晰。
6 ObserverWithState的最终处理
处理到现在了,可能有这样的疑惑,自定义的观察者,代码如下,
class MyObserver(var lifecycle:Lifecycle,var lifecycleCallback: LifecycleCallback) :LifecycleObserver{
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun connectOnCreate(){
print("OnCreate")
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun connectOnStart() {
print("OnStart")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun connectOnResume(){
print("OnResume")
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun disconnectOnDestroye() {
print("OnDestroy")
}
private fun print(string:String){
lifecycleCallback.update(string)
}
}
1.@OnLifecycleEvent注解什么时候起作用
2.用@OnLifecycleEvent注解的方法什么时候调用
可以看到,@OnLifecycleEvent注解的方法,注解值都是Lifecycle的Event事件,所以,这些事件应该会在Activity的这几个生命周期调用。
对注解的处理,大约有两种方式,一是利用反射,而是利用注解处理器。
在引入Lifecycle的时候,我们曾经添加过一下代码
kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
很明显,对于@OnLifecycleEvent注解,使用的是注解处理器的形式。这里直接给出,通过加上以上注解,会在app的build目录下,生成一个MyObserver_LifecycleAdapter的类。我的是在app/build/generated/source/kapt/debug/com.frank/lifecycledemo下,这个MyObserver_LifecycleAdapter很重要,后面会用到。
上文在添加观察者的方法addObserver()里,有一行代码
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
通过观察者observer和初始状态,构造了一个ObserverWithState对象,ObserverWithState是LifecycleRegistry的内部类,前面大体介绍过ObserverWithState,从字面意思看,是是将Observer和State组合在一起。
ObserverWithState代码如下:
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
// 1
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
// 1 处,可以看到,在ObserverWithState的初始化方法中,要初始化一个LifecycleEventObserver的对象,但是LifecycleEventObserver是一个接口,但是构造方法中,是初始化一个实现LifecycleEventObserver的对象,LifecycleEventObserver的源码如下:
public interface LifecycleEventObserver extends LifecycleObserver {
/**
* Called when a state transition event happens.
*
* @param source The source of the event
* @param event The event
*/
void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
它继承自LifecycleObserver,MyObserver也继承自LifecycleObserver,只不过在LifecycleEventObserver里,有个抽象的方法onStateChanged要实现。
mLifecycleObserver的初始化调用的是Lifecycling.lifecycleEventObserver(observer)方法。
@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object object) {
// 1
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;
}
// 2
final Class<?> klass = object.getClass();
// 3
int type = getObserverConstructorType(klass);
if (type == GENERATED_CALLBACK) {
// 4
List<Constructor<? extends GeneratedAdapter>> constructors =
sClassToAdapters.get(klass);
if (constructors.size() == 1) {
// 5
GeneratedAdapter generatedAdapter = createGeneratedAdapter(
constructors.get(0), object);
// 6
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);
}
// 1 MyObserver的类型是LifecycleObserver,所以这些判断都会略过,直接到 // 2处
// 3处的代码,获取观察者构造方法的类型,代码如下。通过下面的分析,type是GENERATED_CALLBACK。// 3的相关代码在代码补充章节,以分割线分开了
// 4 取出原先保存的constructors对象,为com.frank.lifecycledemo.MyObserver_LifecycleAdapter(com.frank.lifecycledemo.MyObserver)
// 5处,constructors只有一个,继续,调用createGeneratedAdapter()方法,返回一个GeneratedAdapter对象。// 5的相关代码分析在代码补充章节,在//3后面,以分割线分开了
// 6处,返回SingleGeneratedAdapterObserver对象,构造方法传入的参数是MyObserver_LifecycleAdapter对象。
下面继续分析ObserverWithState
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
// 1
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
// 通过以上分析,知道mLifecycleObserver为SingleGeneratedAdapterObserver对象,参数是MyObserver_LifecycleAdapter对象。
SingleGeneratedAdapterObserver源码如下:
class SingleGeneratedAdapterObserver implements LifecycleEventObserver {
private final GeneratedAdapter mGeneratedAdapter;
SingleGeneratedAdapterObserver(GeneratedAdapter generatedAdapter) {
mGeneratedAdapter = generatedAdapter;
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
mGeneratedAdapter.callMethods(source, event, false, null);
mGeneratedAdapter.callMethods(source, event, true, null);
}
}
mGeneratedAdapter即为MyObserver_LifecycleAdapter对象。
7 最后的处理
通过第五章节的分析,生命周期事件的分发处理,调用的事sync()方法,不管是对于 backwardPass(lifecycleOwner)还是forwardPass(lifecycleOwner)事件,最终调用的是ObserverWithState的dispatchEvent()方法,
来看一下这个方法
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
// 2
State newState = getStateAfter(event);
// 3
mState = min(mState, newState);
// 4
mLifecycleObserver.onStateChanged(owner, event);
// 5
mState = newState;
}
}
// 2第五章,经过了UP事件,newState为CREATED;
// 3 mState初始化为INITIALIZED,取最小值为INITIALIZED
// 4 状态变化,事件处理
// 5 更新状态变化后的mState为CREATED,此时生命周期到达on_create,随着生命周期的继续,根据upEvent还是downEvent,状态会依次更新。
最后的一个问题,生命周期事件在依次更新,但是在MyObserver定义的方法什么时候调用呢?
这个就是// 4处的代码,mLifecycleObserver.onStateChanged(owner, event),我们知道mLifecycleObserver是一个SingleGeneratedAdapterObserver实例,调用它的onStateChanged()方法如下,
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
mGeneratedAdapter.callMethods(source, event, false, null);
mGeneratedAdapter.callMethods(source, event, true, null);
}
通过上面的分析,mGeneratedAdapter其实是MyObserver_LifecycleAdapter对象,所以mLifecycleObserver.onStateChanged(owner, event)其实调用的事MyObserver_LifecycleAdapter的callMethods()方法,下面给出生成的MyObserver_LifecycleAdapter源码:
public class MyObserver_LifecycleAdapter implements GeneratedAdapter {
final MyObserver mReceiver;
MyObserver_LifecycleAdapter(MyObserver receiver) {
this.mReceiver = receiver;
}
@Override
public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny,
MethodCallsLogger logger) {
boolean hasLogger = logger != null;
if (onAny) {
return;
}
if (event == Lifecycle.Event.ON_CREATE) {
if (!hasLogger || logger.approveCall("connectOnCreate", 1)) {
mReceiver.connectOnCreate();
}
return;
}
if (event == Lifecycle.Event.ON_START) {
if (!hasLogger || logger.approveCall("connectOnStart", 1)) {
mReceiver.connectOnStart();
}
return;
}
if (event == Lifecycle.Event.ON_RESUME) {
if (!hasLogger || logger.approveCall("connectOnResume", 1)) {
mReceiver.connectOnResume();
}
return;
}
if (event == Lifecycle.Event.ON_DESTROY) {
if (!hasLogger || logger.approveCall("disconnectOnDestroye", 1)) {
mReceiver.disconnectOnDestroye();
}
return;
}
}
}
通过对上面代码的分析,我们可以得出,当event事件是Lifecycle.Event.ON_CREATE时,会调用mReceiver.connectOnCreate()方法,即MyObserver的connectOnCreate()方法,依次类推,在MyObserver里,用@OnLifecycleEvent注解的各个Event事件的方法,分别在对应的生命周期得到了调用。
以上就对Lifecycle源码的全部分析,下面的代码的补充分析。
8 代码补充 Lifecycling.lifecycleEventObserver(observer)
---------------------------------- // 3处相关代码分析开始-------------------------------------------------------
--------------- getObserverConstructorType()方法 开始 --------------------
private static int getObserverConstructorType(Class<?> klass) {
// 1
Integer callbackCache = sCallbackCache.get(klass);
if (callbackCache != null) {
return callbackCache;
}
// 2
int type = resolveObserverCallbackType(klass);
sCallbackCache.put(klass, type);
return type;
}
getObserverConstructorType()方法:
// 1处从缓存中获取类型,因为MyObserver以前没有添加过,所以为空。
// 2处调用resolveObserverCallbackType()方法获取类型,代码如下,通过分析,type为GENERATED_CALLBACK,保存并返回type。
-------------------------- getObserverConstructorType()方法 结束 ------------------------
-------------------------- resolveObserverCallbackType()方法 开始 ------------------------
private static int resolveObserverCallbackType(Class<?> klass) {
// anonymous class bug:35073837
// 1
if (klass.getCanonicalName() == null) {
return REFLECTIVE_CALLBACK;
}
// 2
Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
if (constructor != null) {
sClassToAdapters.put(klass, Collections
.<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
return GENERATED_CALLBACK;
}
boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
if (hasLifecycleMethods) {
return REFLECTIVE_CALLBACK;
}
Class<?> superclass = klass.getSuperclass();
List<Constructor<? extends GeneratedAdapter>> adapterConstructors = null;
if (isLifecycleParent(superclass)) {
if (getObserverConstructorType(superclass) == REFLECTIVE_CALLBACK) {
return REFLECTIVE_CALLBACK;
}
adapterConstructors = new ArrayList<>(sClassToAdapters.get(superclass));
}
for (Class<?> intrface : klass.getInterfaces()) {
if (!isLifecycleParent(intrface)) {
continue;
}
if (getObserverConstructorType(intrface) == REFLECTIVE_CALLBACK) {
return REFLECTIVE_CALLBACK;
}
if (adapterConstructors == null) {
adapterConstructors = new ArrayList<>();
}
adapterConstructors.addAll(sClassToAdapters.get(intrface));
}
if (adapterConstructors != null) {
sClassToAdapters.put(klass, adapterConstructors);
return GENERATED_CALLBACK;
}
return REFLECTIVE_CALLBACK;
}
resolveObserverCallbackType():
很明显,对于Observer的CallbackType有两种,
一种是REFLECTIVE_CALLBACK,即利用反射
一种是GENERATED_CALLBACK
两种类型定义如下:
private static final int REFLECTIVE_CALLBACK = 1;
private static final int GENERATED_CALLBACK = 2;
// 1 处不为空,继续往下
// 2处 是generatedConstructor()方法,通过下面这个方法的分析,constructor不为空,保存一下,返回type为GENERATED_CALLBACK。
-------------------------- resolveObserverCallbackType()方法 结束 ------------------------
-------------------------- generatedConstructor()方法 开始 ------------------------
@Nullable
private static Constructor<? extends GeneratedAdapter> generatedConstructor(Class<?> klass) {
try {
//1
Package aPackage = klass.getPackage();
// 2
String name = klass.getCanonicalName();
// 3
final String fullPackage = aPackage != null ? aPackage.getName() : "";
// 4
final String adapterName = getAdapterName(fullPackage.isEmpty() ? name :
name.substring(fullPackage.length() + 1));
// 5
@SuppressWarnings("unchecked") final Class<? extends GeneratedAdapter> aClass =
(Class<? extends GeneratedAdapter>) Class.forName(
fullPackage.isEmpty() ? adapterName : fullPackage + "." + adapterName);
// 6
Constructor<? extends GeneratedAdapter> constructor =
aClass.getDeclaredConstructor(klass);
if (!constructor.isAccessible()) {
constructor.setAccessible(true);
}
// 7
return constructor;
} catch (ClassNotFoundException e) {
return null;
} catch (NoSuchMethodException e) {
// this should not happen
throw new RuntimeException(e);
}
}
generatedConstructor():
// 1处,aPackage为com.frank.lifecycledemo,即项目的包名
// 2处,name为com.frank.lifecycledemo.MyObserver
// 3处,fullPackage为com.frank.lifecycledemo
// 4处调用getAdapterName(),因fullPackage.isEmpty()不为空,所以传入的参数是name.substring(fullPackage.length() + 1),即为MyObserver。通过下面的分析,adapterName为MyObserver_LifecycleAdapter。
// 5处Class.forName是获得Class的名字,为com.frank.lifecycledemo.MyObserver_LifecycleAdapter
// 6处返回aClass的构造函数对象constructor,为com.frank.lifecycledemo.MyObserver_LifecycleAdapter(com.frank.lifecycledemo.MyObserver)
// 7处将constructor对象返回
查看getAdapterName()代码
public static String getAdapterName(String className) {
return className.replace(".", "_") + "_LifecycleAdapter";
}
因传入的参数是MyObserver,所以此方法返回值是MyObserver_LifecycleAdapter。
-------------------------- generatedConstructor()方法 结束 ------------------------
---------------------------------- // 3处相关代码分析结束------------------------------------------------------
---------------------------------- // 5处相关代码分析开始-------------------------------------------------------
private static GeneratedAdapter createGeneratedAdapter(
Constructor<? extends GeneratedAdapter> constructor, Object object) {
//noinspection TryWithIdenticalCatches
try {
return constructor.newInstance(object);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
其实就是调用了一个constructor.newInstance(object),返回MyObserver_LifecycleAdapter对象。
---------------------------------- // 5处相关代码分析结束-------------------------------------------------------