一.前言
- 本篇笔记的主线包含三点,Lifecycle的作用、实现原理、以及源码分析;
二.简介
- 官方文档
- 生命周期感知型组件可执行操作来响应另一个组件(如 Activity 和 Fragment)的生命周期状态的变化。这些组件有助于您写出更有条理且往往更精简的代码,这样的代码更易于维护。
三.实现原理
- 结论先行:Lifecycle是基于反射和观察者模式实现的。
- 使用过程中,实现不同的观察者实现,内部的具体执行流程不同,若使用DefaultLifecycleObserver,则内部不会执行反射相关的代码。若观察者使用LifecycleObserver实现,则会执行反射的代码;
- 同时API29和29以下,会有一些小小的区别,另外,Lifecycle的依赖有多种方式,参考官网文档最好;
- 关于结论有个细节需要进行区分,使用jdk1.7的情况是需要使用到反射,但是jdk1.8是不需要使用到反射的。
- 当然,这里我需要贴上我分析的Lifecycle所对应的库版本,其它版本暂时还没有去关注,所以该细节也需要注意。
dependencies {
def lifecycle_version = "2.2.0"
// Lifecycles only (without ViewModel or LiveData)
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
}
- sdk的版本是30(在分析源码的时候,有个位置跟sdk版本有些关联);
- 大家先记住结论,源码分析完成之后就可以验证该结论。
四.使用
- 主要是三个方面,要实现被观察者、观察者、建立被观察者和观察者之间的联系;
- 被观察者:直接或间接实现LifecycleOwner接口;
- 观察者:直接或间接实现LifecycleObserver接口;
- 被观察者和观察者建立关联:被观察者对象.addObserver(观察者对象);
- 上代码
import android.util.Log;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
/**
* 创建观察者
*/
public class TestObserver implements LifecycleObserver {
private static final String TAG = "Lifecycle";
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
Log.e(TAG, "onCreate");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
Log.e(TAG, "onStart");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
Log.e(TAG, "onResume");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
Log.e(TAG, "onPause");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
Log.e(TAG, "onStop");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestory() {
Log.e(TAG, "onDestory");
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
public void onAny() {
Log.e(TAG, "onAny");
}
}
//被观察者和观察者建立关联
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
//MainActivity是被观察者
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//调用api
getLifecycle().addObserver(new TestObserver());
}
}
4.1.注意事项
- 我们拿一个具体的被观察者和观察者举例。
- 假设被观察者是Activity,只要该Activity直接或间接实现了LifecycleOwner接口(是否默认实现跟sdk版本或者是否是Androidx都管关系),那么被观察者就准备完毕。
- 观察者的创建,我们需要创建一个新类,直接或间接实现LifecycleObserver接口。这里需要区分使用的Jdk是1.7还是1.8。假设是1.8版本(比较主流),需要实现DefaultLifecycleObserver(间接实现了LifecycleObserver)接口。关于观察者的创建,Lifecycle.java中的注释有明确的说明。
- 使用DefaultLifecycleObserver的注意事项:sdk >= 24;同时,要添加依赖 : implementation "android.arch.lifecycle:common-java8:<版本>";
* <p>
* If you use <b>Java 8 Language</b>, then observe events with {@link DefaultLifecycleObserver}.
* To include it you should add {@code "androidx.lifecycle:common-java8:<version>"} to your
* build.gradle file.
* <pre>
* class TestObserver implements DefaultLifecycleObserver {
* {@literal @}Override
* public void onCreate(LifecycleOwner owner) {
* // your code
* }
* }
* </pre>
* If you use <b>Java 7 Language</b>, Lifecycle events are observed using annotations.
* Once Java 8 Language becomes mainstream on Android, annotations will be deprecated, so between
* {@link DefaultLifecycleObserver} and annotations,
* you must always prefer {@code DefaultLifecycleObserver}.
* <pre>
* class TestObserver implements LifecycleObserver {
* {@literal @}OnLifecycleEvent(ON_STOP)
* void onStopped() {}
* }
* </pre>
- 被观察者和观察者都有了,那么建立关联调用api即可。
五.观察者观察被观察者什么呢
- 这似乎是一句多余的话,在简介中已经提及到,是观察组件的生命周期,那自然是观察者去观察者被观察者的生命周期方法。的却如此,可是重要的东西多强调一次还是很有必要,在后面分析源码的时候,会从addObserver方法作为入口,而该方法会完成观察者和被观察者的准备工作。那么,准备工作的代码分析完成之后,我们该如何做下一步的源码分析呢?答案就是从被观察者(后续我们以Activity代替)的生命周期方法开始。Activity一共有7个生命周期方法,OnRestart我们不管,那么还有6个。但是我们只分析OnCreate和其它5个中的一个,选择onResume吧(其它四个同理,就略掉)。
- 除了addObserver方法做了一些准备工作,OnCreate也做了一些准备工作,当activity的onResume被调用的时候,观察者就知道了,知道activity的onResume方法被调用了。
- 以上,我们就总结成一句话:activity发送通知给观察者的时机是:其生命周期发生变化的时候。
- 这一段可能对一些同学来说,可能是多余的,但学习思路还是有必要捋清楚的,不仅能事半功倍,还能省更多的时间。好了,下面开始正真的源码分析,当然,源码分析过程中会有一个难点,这里先不提及,后面重点补充。
六.源码分析
- 请根据注释,按照序号的步骤进行分析;
6.1.从addObserver方法开始
//Lifecycle.java
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
6.2.LifecycleRegistry类addObserver方法
- Lifecycle的addObserver的为抽象方法,其唯一实现类为LifecycleRegistry,查看其addObserver方法
public void addObserver(@NonNull LifecycleObserver observer) {
//1.初始状态值
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//2.封装成ObserverWithState对象,在6.3中进行分析。参数observer是观察者
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
//备注:下方的方法在6.17之后再做分析,先将Lifecycle的实现原理捋出来
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);
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
popParentState();
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
mAddingObserverCounter--;
}
6.3.ObserverWithState
- 分析其构造方法
//ObserverWithState是LifecycleRegistry的内部类
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
//3.在6.4中分析Lifecycling.lifecycleEventObserver(observer)
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
//12.调用的是LifecycleEventObserver的onStateChanged方法
//13.在6.14中分析LifecycleEventObserver的onStateChanged方法
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
6.4.Lifecycling类的静态方法
- 这里需要说明一下,由于在四中提到,我们使用jdk1.8版本,则观察者是实现DefaultLifecycleObserver,而DefaultLifecycleObserver是继承FullLifecycleObserver,则下方boolean isFullLifecycleObserver = true;
- 如果使用jdk1.7,则分析最后一行ReflectiveGenericLifecycleObserver即可;
@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) {
//4.在6.5中进行分析FullLifecycleObserverAdapter
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);
}
6.5.分析FullLifecycleObserverAdapter
- mFullLifecycleObserver赋值为观察者;
- mLifecycleEventObserver赋值为null;
- 这里有个onStateChanged方法,得有个印象,后面会回来分析这里。
class FullLifecycleObserverAdapter implements LifecycleEventObserver {
private final FullLifecycleObserver mFullLifecycleObserver;
private final LifecycleEventObserver mLifecycleEventObserver;
//5.赋值操作
FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,
LifecycleEventObserver lifecycleEventObserver) {
mFullLifecycleObserver = fullLifecycleObserver;
mLifecycleEventObserver = lifecycleEventObserver;
}
//14.当被观察者生命周期发生了变化,会触发调用onStateChanged方法,参数1是被观察者,因为上文我们分析的是activity的onResume方法,对应的Lifecycle.Event是ON_RESUME,那么最终回调的是mFullLifecycleObserver.onResume(source);
@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:
//15.在6.15中分析FullLifecycleObserver类的方法
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);
}
}
}
- 经过6.1到6.5,我们分析完了addObserver方法,这里再补充一下,我们是基于jdk1.8实现的观察者,如果我们是基于jdk1.7实现的观察者,则源码分析的路线会不同,源码的内容会更多一些,会涉及到反射的实现(有兴趣的同学可以自行研究一下)。
6.6.分析被观察者(activity)的基类
- 从onCreate声明方法开始,内部可以看到ReportFragment.injectIfNeededIn(this),进入ReportFragment类进行查看;
6.7.ReportFragment类的injectIfNeededIn方法
public static void injectIfNeededIn(Activity activity) {
//6.根据不同判断执行不同逻辑
if (Build.VERSION.SDK_INT >= 29) {
activity.registerActivityLifecycleCallbacks(
new LifecycleCallbacks());
}
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
- 这里有个版本的区分,先看大于等于29的情况,注册了一个监听,分析参数中的LifecycleCallbacks类。当activity的生命周期发生变化会执行下面的回调,最终执行ReportFragment中的dispatch方法;
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
//...
@Override
public void onActivityPostCreated(@NonNull Activity activity,
@Nullable Bundle savedInstanceState) {
dispatch(activity, Lifecycle.Event.ON_CREATE);
}
//...
@Override
public void onActivityPostResumed(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_RESUME);
}
//...
}
- 而在api29以下,则在activity中添加了一个无UI的ReportFragment,在ReportFragment的生命周期方法中调用了ReportFragment中的dispatch方法;这里有细节需要补充一下,我们只要明白activity和fragment的生命周期方法的关系就可以理解,在ReportFragment的生命周期方法中调用dispatch方法(ReportFragment只利用了5个生命周期方法,onStart、onResume、onPause、onStop、onDestroy),能达到在activity声明中求方法中调用dispatch方法一样的效果。同样地,我们只分析一个声明周期方法,还是选取onResume,内部调用的是dispatch(Lifecycle.Event.ON_RESUME)方法。最终还是调用了跟api大于等于29的版本一样的方法。
- 这里总结一下,关于版本的问题,大于等于29,未使用添加无UI的ReportFragment方式,而是直接调用ReportFragment内部的方法,小于29的则使用了添加无UI的ReportFragment的方式;
6.8.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) {
//观察者默认间接实现LifecycleOwner
//7.在6.9中分析
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
6.9.分析handleLifecycleEvent方法
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event); //后面重点分析
//8.在6.10中分析
moveToState(next);
}
- 这里有个重点,就是Lifecycle.Event和Lifecycle.State,者两个枚举类都跟被观察者有关系。我们先记住,后面重点分析;
public enum Event {
/**
* Constant for onCreate event of the {@link LifecycleOwner}.
*/
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
6.10.分析moveToState
//先分析sync,其它的细节稍后着重讲解
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;
//9.在6.11中分析
sync();
mHandlingEvent = false;
}
6.11.分析sync
//先分析backwardPass,其它的细节稍后再回来分析
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) {
//10.在6.12中分析,分析该方法和分析forwardPass效果是一样的,选取一个即可
backwardPass(lifecycleOwner);
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
6.12.分析backwardPass
//observer.dispatchEvent(lifecycleOwner, event),其它的细节稍后再回来分析
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
Event event = downEvent(observer.mState);
pushParentState(getStateAfter(event));
//11.在6.13中分析,即分析ObserverWithState的dispatchEvent方法
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
6.13.ObserverWithState的dispatchEvent方法
- ObserverWithState类在步骤6.3中我们已经分析过,现在我们回到6.3中的dispatchEvent,步骤是第12;
6.14.LifecycleEventObserver的onStateChanged方法
public interface LifecycleEventObserver extends LifecycleObserver {
//13.找到LifecycleEventObserver的实现类,分析其onStateChanged即可
//我们结合6.4和6.5的分析可以知道,其实现类是FullLifecycleObserverAdapter(温馨提示:若是jdk1.7则实现类是其它类)
//回到6.5中,分析FullLifecycleObserverAdapter的onStateChanged方法
void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
6.15.FullLifecycleObserver类
- 最终是调用了FullLifecycleObserver实现类中的方法,而其唯一的实现类是DefaultLifecycleObserver,在4.1中我们已经提到过DefaultLifecycleObserver类。所以最终的实现则是在DefaultLifecycleObserver的实现类(观察者)中,从而完成了,activity生命周期发生变化,观察者类中的方法得到了调用(即感应到了变化);
interface FullLifecycleObserver extends LifecycleObserver {
void onCreate(LifecycleOwner owner);
void onStart(LifecycleOwner owner);
void onResume(LifecycleOwner owner);
void onPause(LifecycleOwner owner);
void onStop(LifecycleOwner owner);
void onDestroy(LifecycleOwner owner);
}
6.16.简单总结一下
-
到此,我们知道了被观察者的生命周期方法得到调用后,观察者中的方法会相应的得到回调,从而实现观察者能感知到被观察者生命周期的变化的原理;
-
6.9-6.12中省略了一些部分,这是lifecycle难点的部分。我们着重分析一下,为了避免让源码分析起来产生混乱的感觉,分析6.9-6.12的代码会重新贴出;
七.源码细节
7.1.分析getStateAfter方法
- 分析getStateAfter方法,其作用:将activity对应的生命周期的枚举状态转换成Lifecycle专用的枚举状态。这样做的原因:Lifecycle不需要知道activity所有的状态,只关心结束和是否是活动的;
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);
}
- 分析到这里之后,我们需要回到6.1中的addObserver方法了,是时候深入细节了(其实,看到6.16已经够了,但是如果还想深入,那么深入细节是有必要的)。
7.2.再次分析addObserver
- 在此,我们假设addObserver只被调用了一次。
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//1.在7.3.中分析mObserverMap.putIfAbsent(observer, statefulObserver)
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
//5.根据7.3.可知,previous = null
if (previous != null) {
return;
}
//6.获取到被观察者,并判断是否被回收
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
// it is null we should be destroyed. Fallback quickly
return;
}
//7.isReentrance = false(mAddingObserverCounter默认为0,mHandlingEvent默认为false)
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
//8.在7.5中分析calculateTargetState方法
// targetState = INITIALIZED
State targetState = calculateTargetState(observer);
//mAddingObserverCounter = 1
mAddingObserverCounter++;
//statefulObserver.mState = INITIALIZED,前面已经分析过,很明显 statefulObserver.mState.compareTo(targetState) = 0,故不会进入while循环
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.isReentrance = false,故执行sync方法,在7.6中分析sync
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
//mAddingObserverCounter = 0
mAddingObserverCounter--;
}
7.3.mObserverMap.putIfAbsent(observer, statefulObserver)
private HashMap<K, Entry<K, V>> mHashMap = new HashMap<>();
public V putIfAbsent(@NonNull K key, @NonNull V v) {
//2.返回Null,因为第一次执行addObserver时,mHashMap未存储任何键值对
Entry<K, V> current = get(key);
//不执行
if (current != null) {
return current.mValue;
}
//3.在7.4中分析一下put(key, v)方法
//4.存储key-观察者,value=Entry<key, ObserverWithState(key,initialState = INITIALIZED)>
mHashMap.put(key, put(key, v));
return null;
}
7.4.put(key, v)
protected Entry<K, V> put(@NonNull K key, @NonNull V v) {
Entry<K, V> newEntry = new Entry<>(key, v);
//4.1.长度加1
mSize++;
if (mEnd == null) {
//4.2.mStart = mEnd = Entry<key, ObserverWithState(key,initialState = INITIALIZED)
mStart = newEntry;
mEnd = mStart;
//4.3.返回Entry<key, ObserverWithState(key,initialState = INITIALIZED)
//回溯到putIfAbsent->addObserver方法中,即步骤1中继续分析
return newEntry;
}
//未执行,不用管
mEnd.mNext = newEntry;
newEntry.mPrevious = mEnd;
mEnd = newEntry;
return newEntry;
}
7.5.calculateTargetState
- 返回State最小的生命周期状态:这个最小是怎么理解呢?如下:DESTROYED = 0,INITIALIZED = 1,CREATED = 2,STARTED = 3,RESUMED = 4,很清晰吧。
private State calculateTargetState(LifecycleObserver observer) {
//顺着上面的分析previous首次是为null
Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);
//siblingState = null
State siblingState = previous != null ? previous.getValue().mState : null;
//parentState = null (mParentStates是个集合,刚开始是空)
State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1) : null;
//最终返回的是 INITIALIZED,返回到7.2中的步骤8
return min(min(mState, siblingState), parentState);
}
7.6.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.");
}
//10.在7.7.中分析isSynced()方法
//根据7.7.可知!isSynced()=false,不执行while语句
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;
}
7.7.isSynced
- 返回当前生命状态是否一致 不相同为false
private boolean isSynced() {
//没有观察者时返回true
if (mObserverMap.size() == 0) {
return true;
}
//获取最先添加进来的观察者生命周期状态
State eldestObserverState = mObserverMap.eldest().getValue().mState;
//获取最后(最近)添加进来的观察者生命周期状态
State newestObserverState = mObserverMap.newest().getValue().mState;
//如果最先的和最后的Observer的状态不一致或者当前的状态和最新的状态不一致时,那么需要进行状态同步
//7.4中已经分析过
//首次情况下,mStart = mEnd = Entry<key, ObserverWithState(key,initialState = INITIALIZED),故eldestObserverState = newestObserverState = INITIALIZED
//返回结果为true,回到步骤10
return eldestObserverState == newestObserverState && mState == newestObserverState;
}
7.8.小结
- 初始状态分析完毕了,我们需要举例被观察者具体的生命周期方法被调用时,源代码的执行情况,我们就那activity仅执行了onCreate方法为例。这里有细节需要注意,项目中依赖的是androidx.appcompat:appcompat:1.0.0,有必要把基类activity的继承关系梳理一下,如此,才能知道activity的onCreate方法执行时代码的走向。基类activity继承RxAppCompatActivity,间接继承AppCompatActivity->FragmentActivity->,activity的onCreate的方法执行会触发FragmentActivity的onCreate,继而触发ComponentActivity的onCreate方法,ComponentActivity的onCreate执行初始化的工作,执行完毕后,FragmentActivity的onCreate会执行mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)方法,实际上就是6.9的方法。
- 上面的流程需要自己整理一下,最好运行一个demo,具体跟踪一下,之所以啰嗦,是因为handleLifecycleEvent方法多处都有调用,继承关系不同等因素会导致源码跟踪的路线不同。下面就正在开始分析了。直接贴出handleLifecycleEvent,不在6.9中直接添加注释,免得引起混乱。
7.9.传入具体参数分析handleLifecycleEvent
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
//11.参数为 Lifecycle.Event.ON_CREATE,执行后next = CREATED
State next = getStateAfter(event);
//在7.10.中分析moveToState,参数为CREATED
moveToState(next);
}
7.10.传入具体参数分析moveToState
//next = CREATED
private void moveToState(State next) {
//mState = INITIALIZED,故不执行if语句
if (mState == next) {
return;
}
//更新 mState = CREATED
mState = next;
//此时 mHandlingEvent = false mAddingObserverCounter = 0,前面已经分析过(7.2)
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// we will figure out what to do on upper level.
return;
}
//更新mHandlingEvent
mHandlingEvent = true;
//12.在7.11.中再次分析sync
sync();
//更新mHandlingEvent
mHandlingEvent = false;
}
7.11.再次分析sync
private void sync() {
//略
//13.分析isSynced
//eldestObserverState = newestObserverState (mStart = mEnd = Entry<key, ObserverWithState(key,initialState = INITIALIZED))
//但是 mState( = CREATED ) != newestObserverState ( = INITIALIZED )
//故!isSynced = true,执行while语句
while (!isSynced()) {
//更改标记
mNewEventOccurred = false;
//14.mState = CREATED = 2,mObserverMap.eldest().getValue().mState = INITIALIZED = 1,结果是false,mState.compareTo(mObserverMap.eldest().getValue().mState > 0,故不进入if语句
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
//15.newest = mEnd = mStart = Entry<key, ObserverWithState(key,initialState = INITIALIZED) ( 在7.4中已经分析)
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
//三个条件都成立,执行forwardPass
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
//16.在7.12中分析
forwardPass(lifecycleOwner);
}
}
//更改标记
mNewEventOccurred = false;
}
7.12.分析forwardPass
- 结论先行:遍历观察者集合,当观察者生命周期状态小于当前生命周期状态时 分发事件
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
//显然是执行while语句的
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
ObserverWithState observer = entry.getValue();
//17.结合6.1中的1和2,以及7.2中的1,可以得知
//observer.mState = INITIALIZED = 1,而 mState = CREATED = 2
//故条件1成立,条件2和条件3显然也是成立的,执行while语句
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
//将INITIALIZED添加到成员变量mParentStates中
pushParentState(observer.mState);
//18.这一步很熟悉了,之前分析过了,参数2是将CREATED转换成ON_START
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
//移除成员变量mParentStates集合中的最后一个元素
popParentState();
}
}
}
- 到此,我觉得可以结束该篇笔记了。当然还有细节,有了上面的分析之后,其它的细节即便是遇到了(在总结Livedata的时候,会补充Lifecycle的另外一个细节),按照上面的分析思路,也比较好处理了。
八.总结
- 写的有点多,但是是有一个完整的思维路线的,一些位置有些重复,但是还是有必要。使用jdk1.7时,相应的源码分析思路简单提及一下,我们要分析的就是ReflectiveGenericLifecycleObserver类,在6.4中提到过。
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
//这里的参数是观察者的class对象---非常重要
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
- 分析ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
//ClassesInfoCache.java
CallbackInfo getInfo(Class klass) {
CallbackInfo existing = mCallbackMap.get(klass);
if (existing != null) {
return existing;
}
existing = createInfo(klass, null);
return existing;
}
//createInfo 参数2为null
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
Class superclass = klass.getSuperclass();
Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
if (superclass != null) {
CallbackInfo superInfo = getInfo(superclass);
if (superInfo != null) {
handlerToEvent.putAll(superInfo.mHandlerToEvent);
}
}
Class[] interfaces = klass.getInterfaces();
for (Class intrfc : interfaces) {
for (Map.Entry<MethodReference, Lifecycle.Event> entry : getInfo(
intrfc).mHandlerToEvent.entrySet()) {
verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
}
}
//这里会执行后面,就是一个反射的方法。最终是把观察者中的所有方法都获取到了
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
for (Method method : methods) {
//注解的使用
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation == null) {
continue;
}
hasLifecycleMethods = true;
Class<?>[] params = method.getParameterTypes();
//@OnLifecycleEvent(Lifecycle.Event.ON_CREATE),指括号内的参数个数,TestObserver类目前都是一个
int callType = CALL_TYPE_NO_ARG;
//会执行该位置
//如:@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
if (params.length > 0) {
callType = CALL_TYPE_PROVIDER;
if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
throw new IllegalArgumentException(
"invalid parameter type. Must be one and instanceof LifecycleOwner");
}
}
Lifecycle.Event event = annotation.value();
if (params.length > 1) {
callType = CALL_TYPE_PROVIDER_WITH_EVENT;
if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
throw new IllegalArgumentException(
"invalid parameter type. second arg must be an event");
}
if (event != Lifecycle.Event.ON_ANY) {
throw new IllegalArgumentException(
"Second arg is supported only for ON_ANY value");
}
}
if (params.length > 2) {
throw new IllegalArgumentException("cannot have more than 2 params");
}
//将目标的method做了一层封装,分析MethodReference
MethodReference methodReference = new MethodReference(callType, method);
//再次包装methodReference
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
}
CallbackInfo info = new CallbackInfo(handlerToEvent);
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
//最终返回info,说明:CallbackInfo包含的有观察者类定义的方法的信息
return info;
}
- 分析new MethodReference(callType, method);
static class MethodReference {
final int mCallType;
final Method mMethod;
MethodReference(int callType, Method method) {
mCallType = callType;
mMethod = method;
mMethod.setAccessible(true);
}
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
//noinspection TryWithIdenticalCatches
try {
switch (mCallType) {
case CALL_TYPE_NO_ARG:
mMethod.invoke(target);
break;
case CALL_TYPE_PROVIDER:
mMethod.invoke(target, source);
break;
case CALL_TYPE_PROVIDER_WITH_EVENT:
mMethod.invoke(target, source, event);
break;
}
} catch (InvocationTargetException e) {
throw new RuntimeException("Failed to call observer method", e.getCause());
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MethodReference that = (MethodReference) o;
return mCallType == that.mCallType && mMethod.getName().equals(that.mMethod.getName());
}
@Override
public int hashCode() {
return 31 * mCallType + mMethod.getName().hashCode();
}
}
- 到此,对Lifecycle是已经有一个很深入的了解了。
评论区