写一篇最好懂的Lifecycle的基本使用和原理分析

想要完全弄清楚Lifecycle完成对Activity或许Fragment的生命周期办法感知的基本原理,咱们可以从以下两个方面去思考:

1、Lifecycle是怎么感知到Activity或许Fragment的生命周期办法的?

2、Lifecycle是怎么调用咱们自界说类中对应的生命周期办法的?

为了讲清楚Lifecycle的原理,我需求从基本使用开端讲起,作为我剖析原理的进口,这儿我选择两种基本使用办法
一、基本使用
引入依靠
implementation "androidx.lifecycle:lifecycle-common-java8:2.5.1"
办法一

1、自界说ILifecycleObserver接口,完成LifecycleObserver接口

/**
 * 自界说生命周期观察者接口,完成LifecycleObserver
 */
interface ILifecycleObserver:LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate(owner:LifecycleOwner)
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStart(owner:LifecycleOwner)
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume(owner:LifecycleOwner)
    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause(owner:LifecycleOwner)
    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onStop(owner:LifecycleOwner)
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy(owner:LifecycleOwner)
    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    fun onStateChange(owner: LifecycleOwner, event: Lifecycle.Event)
}

2、界说完成类LifeCycleObserverImpl,完成ILifecycleObserver接口

/**
 * ILifecycleObserver接口完成类
 */
class LifeCycleObserverImpl:ILifecycleObserver {
    private val TAG = "LifeCycleObserverImpl"
    override fun onCreate(owner: LifecycleOwner) {
        "onCreate".log(TAG)
    }
    override fun onStart(owner:LifecycleOwner) {
        "onStart".log(TAG)
    }
    override fun onResume(owner:LifecycleOwner) {
        "onResume".log(TAG)
    }
    override fun onPause(owner:LifecycleOwner) {
        "onPause".log(TAG)
    }
    override fun onStop(owner:LifecycleOwner) {
        "onStop".log(TAG)
    }
    override fun onDestroy(owner:LifecycleOwner) {
        "onDestroy".log(TAG)
    }
    override fun onStateChange(owner: LifecycleOwner, event: Lifecycle.Event) {
        "onStateChange,event :${event.name}".log(TAG)
    }
}

3、经过getLifecycle()办法把咱们自界说的生命周期观察者与当时Activity相关起来

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // 经过getLifecycle()办法把咱们自界说的生命周期观察者与当时Activity相关起来
        lifecycle.addObserver(LifeCycleObserverImpl())
    }
} 

4、接下来,发动APP,可以看到有如下的输出日志

2023-06-17 20:07:28.310  6243-6243  LifeCycleObserverImpl   I  onCreate
2023-06-17 20:07:28.311  6243-6243  LifeCycleObserverImpl   I  onStateChange,event :ON_CREATE
2023-06-17 20:07:28.316  6243-6243  LifeCycleObserverImpl   I  onStart
2023-06-17 20:07:28.316  6243-6243  LifeCycleObserverImpl   I  onStateChange,event :ON_START
2023-06-17 20:07:28.319  6243-6243  LifeCycleObserverImpl   I  onResume
2023-06-17 20:07:28.319  6243-6243  LifeCycleObserverImpl   I  onStateChange,event :ON_RESUME

5、点击手机回来按钮,相同可以看到如下日志

2023-06-17 20:16:10.615  6243-6243  LifeCycleObserverImpl   I  onPause
2023-06-17 20:16:10.615  6243-6243  LifeCycleObserverImpl   I  onStateChange,event :ON_PAUSE
2023-06-17 20:16:10.749  6243-6243  LifeCycleObserverImpl   I  onStop
2023-06-17 20:16:10.749  6243-6243  LifeCycleObserverImpl   I  onStateChange,event :ON_STOP
2023-06-17 20:16:10.753  6243-6243  LifeCycleObserverImpl   I  onDestroy
2023-06-17 20:16:10.753  6243-6243  LifeCycleObserverImpl   I  onStateChange,event :ON_DESTROY

经过日志可以看到,咱们自界说的观察者类感知到了MainActivity的生命周期办法,接下来,咱们换一种办法来看一下。

办法二

1、自界说MyDefaultLifecycleObserver,完成DefaultLifecycleObserver

/**
 * 完成DefaultLifecycleObserver
 */
class MyDefaultLifecycleObserver:DefaultLifecycleObserver {
    private val TAG = "MyDefaultLifecycleObserver"
    override fun onCreate(owner: LifecycleOwner) {
        "onCreate".log(TAG)
    }
    override fun onStart(owner: LifecycleOwner) {
        "onStart".log(TAG)
    }
    override fun onResume(owner: LifecycleOwner) {
        "onResume".log(TAG)
    }
    override fun onPause(owner: LifecycleOwner) {
        "onPause".log(TAG)
    }
    override fun onStop(owner: LifecycleOwner) {
        "onStop".log(TAG)
    }
    override fun onDestroy(owner: LifecycleOwner) {
        "onDestroy".log(TAG)
    }
}

2、在MainActivity中经过getLifecycle()办法把咱们自界说的观察者与当时Activity相关起来

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // 经过getLifecycle()办法把咱们自界说的观察者与当时Activity相关起来
        lifecycle.addObserver(MyDefaultLifecycleObserver())
    }
}

3、发动APP,可以看到如下日志

2023-06-17 20:28:55.170  9218-9218  DefaultLif...leObserver I  onCreate
2023-06-17 20:28:55.173  9218-9218  DefaultLif...leObserver I  onStart
2023-06-17 20:28:55.174  9218-9218  DefaultLif...leObserver I  onResume

4、按手机回来键,可以看到如下日志

2023-06-17 20:30:34.493  9218-9218  DefaultLif...leObserver I  onPause
2023-06-17 20:30:34.686  9218-9218  DefaultLif...leObserver I  onStop
2023-06-17 20:30:34.690  9218-9218  DefaultLif...leObserver I  onDestroy

经过以上两种办法,完成了相同的生命周期感知能力,办法二比照办法一,完成更简单,也是官方主张的完成办法

二、原理剖析

剖析原理之前,先对几个类有个感性的知道

1、Lifecycle

Lifecycle是一个笼统类,咱们在Activity中经过getLifecycle()办法得到的实例目标便是一个Lifecycle目标,用于相关生命周期观察者和被观察者,并担任生命周期事情的分发和生命周期状况的处理,它持有生命组件的事情和状况,它们的关系可以用下面这张图来表明:

写一篇最好懂的Lifecycle的基本使用和原理分析

public abstract class Lifecycle {
    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);
    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);
    public enum Event {
        ON_CREATE,
        ON_START,
        ON_RESUME,
        ON_PAUSE,
        ON_STOP,
        ON_DESTROY,
        ON_ANY;
      }
    public enum State {
        DESTROYED,
        INITIALIZED,
        CREATED,
        STARTED,
        RESUMED;
     }
}

2、LifecycleOwner

LifecycleOwner供给了获取Lifecycle的笼统办法getLifecycle(),是生命周期组件的持有者,在AndroidX中的Activity和Fragment默许完成了这个接口

public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();
}

3、LifecycleObserver

生命周期观察者,是个空接口,没有任何办法,只是用于标识完成该接口的类具有生命周期感知能力

public interface LifecycleObserver {
}

先剖析第一种办法

问题一:Lifecycle是怎么感知到Activity或许Fragment的生命周期办法的?

1、回到MainActivity类,定位到这儿:

lifecycle.addObserver(LifeCycleObserverImpl())

2、先看Lifecycle是怎么获取的,进入到getLifecycle()办法,由ComponentActivity完成

@NonNull
@Override
public Lifecycle getLifecycle() {
    return mLifecycleRegistry;
}

3、咱们看mLifecycleRegistry在哪里赋值的,在ComponentActivity中,是ComponentActivity的私有成员

private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

4、LifecycleRegstry完成了Lifecycle接口,看到这儿,咱们先不去看LifecycleRegstry内部详细的详细完成

public class LifecycleRegistry extends Lifecycle {

5、咱们看ComponentActivity的onCreate()办法中有这么一行代码

ReportFragment.injectIfNeededIn(this);

6、进入到办法中看下详细完成,实际上便是在当时Activity中参加了一个通明的Fragment

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) {
        manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
        // Hopefully, we are the first to make a transaction.
        manager.executePendingTransactions();
    }
}

7、来看下ReportFragment类

public class ReportFragment extends android.app.Fragment {
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dispatch(Lifecycle.Event.ON_CREATE);
    }
    @Override
    public void onStart() {
        super.onStart();
        dispatch(Lifecycle.Event.ON_START);
    }
    @Override
    public void onResume() {
        super.onResume();
        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);
    }
}

8、咱们可以看到在ReportFragment的生命周期办法中都调用了dispatch办法并传递了对应的生命周期事情,来看下dispatch办法

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);
        }
    }

9、dispatch又调用了有两个参数的dispatch办法

@SuppressWarnings("deprecation")
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);
        }
    }
}

10、参数activity便是ComponentActivity,由于ComponentActivity完成了LifecycleOwner,因此咱们直接看这行代码

((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);

流程走到了这儿,咱们应该清楚了第一个问题的答案了吧

问题一:Lifecycle是怎么感知到Activity或许Fragment的生命周期办法的?

1、在ComponentActivity添加一个通明的ReportFragment

2、在ReportFragment的生命周期办法中别离调用dispatch办法并传入对应的生命周期事情

3、调用Lifecycle完成类LifecycleRegistry类中的handleLifecycleEvent办法将生命周期事情分发给LifecycleObserver中对应的办法

问题二:Lifecycle是怎么调用咱们自界说类中对应的生命周期办法的?

1、接着上面的流程,咱们看LifecycleRegistry类中的handleLifecycleEvent办法

public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    ...
    moveToState(event.getTargetState());
}

2、先看event.getTargetState()做了什么,逻辑很简单,便是根据当时的生命周期事情获取相应的状况

@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;
    }
}

对照这张图来看会更加直观:

写一篇最好懂的Lifecycle的基本使用和原理分析
3、咱们在回过头来看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;
}

4、继续看sync办法,mState会比较mObserverMap的eldest和newest的状况,看是往前还是往后,比如从STAETED到RESUMED便是往前,反之往后

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;
        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;
}

5、看下forwardPass(lifecycleOwner)的履行逻辑,看注释1和2,在1处有个ObserverWithState,咱们需求要点关注下这个类,也是生命周期事情分发和咱们自界说类中办法被调用的核心,所以咱们来看下ObserverWithState是在哪里创立并保存到mObserverMap里边的?

private void forwardPass(LifecycleOwner lifecycleOwner) {
    // 1、ObserverWithState是在哪里创立并保存的?
    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);
            }
            // 2、履行分发生命周期事情办法
            observer.dispatchEvent(lifecycleOwner, event);
            popParentState();
        }
    }
}

6、回到MainActivity中的这行代码

lifecycle.addObserver(LifeCycleObserverImpl())

7、看下addObserver的完成,直接看注释

public void addObserver(@NonNull LifecycleObserver observer) {
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
    // 把咱们自界说的LifecycleObserver包装成了ObserverWithState
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    // 保存到mObserverMap
    ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
    ...
}

8、看下ObserverWithState是什么,看类名就很好理解,用于包装当时状况和观察者

static class ObserverWithState {
    State mState;
    LifecycleEventObserver mLifecycleObserver;
    ObserverWithState(LifecycleObserver observer, State initialState) {
        mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
        mState = initialState;
    }
}

9、看结构办法中的Lifecycling.lifecycleEventObserver(observer);这行代码,实际回来的是ReflectiveGenericLifecycleObserver

static LifecycleEventObserver lifecycleEventObserver(Object object) {
    ...
    return new ReflectiveGenericLifecycleObserver(object);
}

10、接下来看ReflectiveGenericLifecycleObserver的完成

@Deprecated
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;
    private final androidx.lifecycle.ClassesInfoCache.CallbackInfo mInfo;
    @SuppressWarnings("deprecation")
    ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;// 1
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());// 2
    }
    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
        mInfo.invokeCallbacks(source, event, mWrapped);// 3
    }
}
  • 注释1:wrapped便是咱们自己界说的LifecycleObserver,赋值给了成员变量mWrapped,也就代表ReflectiveGenericLifecycleObserver持有了咱们自己界说的LifecycleObserver目标
  • 注释2:看下CallbackInfo的获取进程
  • 注释3:终究会履行到咱们自界说的LifecycleObserver中的办法,后边再看

11、看下CallbackInfo的获取进程

CallbackInfo getInfo(Class<?> klass) {
    // 先从缓存中获取
    CallbackInfo existing = mCallbackMap.get(klass);// 1
    if (existing != null) {
        return existing;
    }
    // 没有缓存
    existing = createInfo(klass, null);// 2
    return existing;
}
  • 注释1:从缓存中获取CallbackInfo
  • 注释2:创立CallbackInfo,klass是咱们自界说的LifecycleObserver的字节码目标

12、继续跟踪下去

private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) {
    Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
...
    // 1
    Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
    boolean hasLifecycleMethods = false;
    for (Method method : methods) {
        // 2
        OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
        if (annotation == null) {
            continue;
        }
        hasLifecycleMethods = true;
        Class<?>[] params = method.getParameterTypes();
        // 3
        int callType = CALL_TYPE_NO_ARG;
        if (params.length > 0) {// 假如办法有参数
            callType = CALL_TYPE_PROVIDER;
            // 判别第一个参数的类型是不是LifecycleOwner
            if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
                throw new IllegalArgumentException(
                        "invalid parameter type. Must be one and instanceof LifecycleOwner");
            }
        }
        // 4
        Lifecycle.Event event = annotation.value();
        if (params.length > 1) {// 假如参数有多个
            callType = CALL_TYPE_PROVIDER_WITH_EVENT;
            // 判别第二个参数类型是不是Lifecycle.Event
            if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
                throw new IllegalArgumentException(
                        "invalid parameter type. second arg must be an event");
            }
            // 假如办法中参数有多个,那么生命周期事情有必要是Lifecycle.Event.ON_ANY
            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");
        }
        // 5
        MethodReference methodReference = new MethodReference(callType, method);
        // 将包装好的methodReference目标存储到handlerToEvent
        verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
    }
    // 6
    CallbackInfo info = new CallbackInfo(handlerToEvent);
   ...
    return info;
}
  • 注释1:经过反射获取咱们自界说LifecycleObserver中一切的办法
  • 注释2:获取办法上OnLifecycleEvent类型的注解
  • 注释3:用于标识办法的类型,界说了三种,无参办法、有一个参数的办法和两个参数的办法
  • 注释4:获取注解中传入的值,是个枚举类型,也便是Lifecycle中界说的Event类
  • 注释5:将办法类型和method包装成MethodReference,后边在回调咱们界说的办法时会用到callType
  • 注释6:便是咱们要获取的CallbackInfo目标,待会会看它的结构办法

13:、看CallbackInfo的结构办法

CallbackInfo(Map<MethodReference, Lifecycle.Event> handlerToEvent) {
    ...
    mEventToHandlers = new HashMap<>();
    for (Map.Entry<MethodReference, Lifecycle.Event> entry : handlerToEvent.entrySet()) {
        Lifecycle.Event event = entry.getValue();
        List<MethodReference> methodReferences = mEventToHandlers.get(event);
        if (methodReferences == null) {
            methodReferences = new ArrayList<>();
            // 1
            mEventToHandlers.put(event, methodReferences);
        }
        // 2
        methodReferences.add(entry.getKey());
    }
}
  • 注释1:mEventToHandlers是个map,存储键值对,注意看key,使用的key正是咱们在注解当中传入的生命周期事情,后续可以回调到咱们自界说的对应生命周期办法,这个key是关键,再看map中的value存储的是一个List调集,这说明咱们可以用同一个生命周期事情event界说多个不同的办法,在履行到关于的生命周期时,被同一个生命周期事情界说的办法都会被调用到
  • 注释2:methodReferences存储的正是包装好的MethodReference目标

到这儿ObserverWithState的结构流程就走完了,咱们来总结下:

  • 1、在addObserver办法中创立出ObserverWithState
  • 2、把咱们自界说的LifecycleObserver目标传给ObserverWithState
  • 3、经过对Lifecycling.lifecycleEventObserver(observer)的层层调用,经过反射的办法把咱们自界说LifecycleObserver中的办法解析成一个MethodReference并保存存到一个map中,key便是对应的生命周期事情,后边在调用办法时,会根据这个key拿到对应的MethodReference目标,并反射履行这个目标中的method办法,这个后边会讲到

14、知道了ObserverWithState是什么以及知道了它的结构流程以后,再回过头看下forwardPass中的注释2处

// 2、履行分发生命周期事情办法
observer.dispatchEvent(lifecycleOwner, event);

15、看dispatchEvent办法

void dispatchEvent(LifecycleOwner owner, Event event) {
    // 1
    State newState = event.getTargetState();
    mState = min(mState, newState);
    // 2
    mLifecycleObserver.onStateChanged(owner, event);
    mState = newState;
}
  • 注释1:核算mState
  • 注释2:这行代码是调用咱们自界说观察者类中办法的核心代码,onStateChanged是个笼统办法,所以会履行到ReflectiveGenericLifecycleObserver类中的onStateChanged办法

16、看onStateChanged办法,内部调用了CallbackInfo的invokeCallbacks

@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
    mInfo.invokeCallbacks(source, event, mWrapped);
}

17、咱们来看CallbackInfo的invokeCallbacks

void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
    // 1
    invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
    // 2
    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--) {
            // 3
            handlers.get(i).invokeCallback(source, event, mWrapped);
        }
    }
}
  • 注释1:便是上面提到过的,会经过生命周期事情event作为key去拿到对应的List,然后调用invokeMethodsForEvent遍历同一个生命周期事情event下界说的一切的办法
  • 注释2:这个是专门处理被生命周期事情Lifecycle.Event.ON_ANY标注的办法,每一个生命周期它都会履行到
  • 注释3:遍历List,履行MethodReference中的invokeCallback方,接下来看这个办法的完成

18、MethodReference中invokeCallback办法,这儿便是上面提到过的根据不同的callType履行不同的办法,target便是咱们自界说的LifecycleObserver,经过反射的办法履行对应的办法

void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
    try {
        // 这儿便是上面提到过的根据不同的callType履行不同的办法,target便是咱们自界说的LifecycleObserver,经过反射的办法履行对应的办法
        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);
    }
}

到此为止,咱们应该知道了咱们的第二个问题的答案了吧

问题二:Lifecycle是怎么调用咱们自界说类中对应的生命周期办法的?

1、经过反射解析咱们自界说的LifecycleObserver中的办法,并将其包装成一个个MethodReference,并保存到一个map中,办法上的注解中的生命周期事情便是mapkey,MethodReference便是value

2、经过调用dispatchEvent办法,终究调用到MethodReference中的invokeCallback办法,经过callType来区别应该履行的办法,终究经过反射的办法履行到咱们自界说的办法

剖析第二种办法

履行流程跟上面的基本一致,只有略微的区别,所以咱们有了上面的剖析根底,就不必讲得那么详细了,我只讲有区别的地方,其他流程可看参照上面的来,这儿只要看三个地方就行了 1、看ObserverWithState的结构办法

ObserverWithState(LifecycleObserver observer, State initialState) {
    // 1
    mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
    mState = initialState;
}
  • 注释1:lifecycleEventObserver办法中的参数是咱们自界说的MyDefaultLifecycleObserver,完成了FullLifecycleObserver接口

2、接下来看lifecycleEventObserver办法

static LifecycleEventObserver lifecycleEventObserver(Object object) {
    boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
    // 1
    boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
    if (isLifecycleEventObserver && isFullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
                (LifecycleEventObserver) object);
    }
    // 2
    if (isFullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
    }
    if (isLifecycleEventObserver) {
        return (LifecycleEventObserver) object;
    }
   ...
}
  • 注释1:咱们的完成类是FullLifecycleObserver,因此isFullLifecycleObserver是true,会履行到2处
  • 注释2:终究咱们完成的办法便是这个类中被调用履行

3、看下FullLifecycleObserverAdapter的完成

class FullLifecycleObserverAdapter implements LifecycleEventObserver {
    private final FullLifecycleObserver mFullLifecycleObserver;
    private final LifecycleEventObserver mLifecycleEventObserver;
    FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,
            LifecycleEventObserver lifecycleEventObserver) {
        mFullLifecycleObserver = fullLifecycleObserver;
        mLifecycleEventObserver = lifecycleEventObserver;
    }
    @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:
                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);
        }
    }
}

比较于第一种办法,这种办法的完成更直接,不需求用到反射,因此在履行功率上来说,会更优于第一种办法,所以我猜想这或许便是为什么google主张咱们用这种办法来完成的原因吧


总结一下

问题一:Lifecycle是怎么感知到Activity或许Fragment的生命周期办法的?

1、在ComponentActivity添加一个通明的ReportFragment

2、在ReportFragment的生命周期办法中别离调用dispatch办法并传入对应的生命周期事情

3、调用Lifecycle完成类LifecycleRegistry类中的handleLifecycleEvent办法将生命周期事情分发给LifecycleObserver中对应的办法

问题二:Lifecycle是怎么调用咱们自界说类中对应的生命周期办法的?

1、经过反射解析咱们自界说的LifecycleObserver中的办法,并将其包装成一个个MethodReference,并保存到一个map中,办法上的注解中的生命周期事情便是mapkey,MethodReference便是value

2、经过调用dispatchEvent办法,终究调用到MethodReference中的invokeCallback办法,经过callType来区别应该履行的办法,终究经过反射的办法履行到咱们自界说的办法