Jetpack之Lifecycle原理分析
一、Lifecycle介绍
1.1 、Lifecycle是什么?
Lifecycle是Jetpack库中架构组件中的一个,可以用来帮助开发者创建可感知生命周期的组件。
生命周期感知型组件可执行操作来响应另一个组件(如 Activity 和 Fragment)的生命周期状态的变化。这些组件有助于我们写出更有条理且往往更精简的代码,这样的代码更易于维护。
Lifecycle是一个用来存储有关组件(如 Activity 和 Fragment)的生命周期状态信息的类,并且允许其他对象观察此状态。
简单的说,Lifecycle能让我们非常方便的监听到(或者说是观察到)相关组件的生命周期状态信息和变化。
1.2 为什么要用Lifecycle?
在上面我们已经说过,方便感知相关组件(如 Activity 和 Fragment)的生命周期。但是,这并不是我们要用Lifecycle的主要原因,因为我们在Activity的生命周期回调方法中,同样可以处理我们的相关逻辑。比如我们获取位置的一个例子:常见的响应生命周期的方式,是主动的在生命周期方法onStart()中调用我们的开始定位start()方法。
public class MyLocationListener {
public MyLocationListener(Context context, LocationCallback callback) {
}
void start() {
}
void stop() {
}
}
public class MainActivity extends AppCompatActivity {
private MyLocationListener myLocationListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLocationListener = new MyLocationListener(this, location -> {
//update UI
});
}
@Override
protected void onStart() {
super.onStart();
myLocationListener.start();
}
@Override
protected void onStop() {
super.onStop();
myLocationListener.stop();
}
}
但是会存在下面的一些问题:
- 如果组件越来越多,会导致大量的业务组件调用代码存在生命周期回调方法中,耦合太高,难以维护。
- 我们无法保证组件的调用会在activity/Fragment 停止之前执行,也就是说,onStop()方法会在onStart()方法之前结束,会导致组件存留时间比实际需要时间长,可能会引起内存泄露(见下面的测试代码)。
public class MainActivity extends AppCompatActivity {
private MyLocationListener myLocationListener;
private TextView tvHello;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvHello = findViewById(R.id.tv_hello);
myLocationListener = new MyLocationListener(this, location -> {
//update UI
});
}
@Override
protected void onStart() {
super.onStart();
//用延迟来表示条件满足后才开始执行 start()方法
tvHello.postDelayed(() -> myLocationListener.start(), 1000 * 4);
tvHello.postDelayed(MainActivity.this::finish, 1000 * 2);
}
@Override
protected void onStop() {
super.onStop();
myLocationListener.stop();
}
}
所以,我们希望一些依赖系统组件生命周期执行的自定义组件,能够不再依赖生命周期方法的回调,同时在系统组件生命周期发生变化时,我们也能够及时的收到通知,做出响应,即在组件间解耦同时又能响应生命周期变化。为此,Google提供了LifeCycle这样一种解决方案。
二、Lifecycle的使用
1.简单使用
我们还是使用定位的例子,实现LifecycleObserver这样一个接口,在我们需要监听生命周期事件的方法上,加上**@OnLifecycleEvent(Lifecycle.Event.XXX)**事件注解。
public class MyLocationListener2 implements LifecycleObserver {
public MyLocationListener2(Context context, LocationCallback callback) {}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
void start() {
Log.i("MyLocationListener2:", "start()");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void stop() {
Log.i("MyLocationListener2:", "stop()");
}
}
在我们MainActivity中通过 getLifecycle().addObserver()方法,将我们的MyLocationListener2对象作为观察者进行注册。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLifecycle().addObserver(new MyLocationListener2(this, location -> {
//update UI
}));
}
}
我们可以在Activity生命周期发生变化时,自动的执行我们要执行的代码。如果我们要监听其他状态,只需要在MyLocationListener2中增加事件或修改事件类型,这样使组件间耦合降到了最低。
三、Lifecycle源码解析
LifecycleObserver:
LifecycleObserver
是一个接口,没有任何方法,可以理解为用来标记生命周期观察者,当我们的自定义组件需要监听到生命周期时,需要实现该接口。
LifecycleOwner:
lifecycleOwner
同样是一个接口,用来声明具有生命周期的类,提供了getLifecycle()
方法来获取其Lifecycle
对象
/**
* A class that has an Android lifecycle. These events can be used by custom components to
* handle lifecycle changes without implementing any code inside the Activity or the Fragment.
*
* @see Lifecycle
* @see ViewTreeLifecycleOwner
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
Lifecycle:
Lifecycle
是一个抽象类,可以理解为表示具体的生命周期对象,每个 LifecycleOwner
都会持有 Lifecycle
对象。通过 Lifecycle
我们可以获取当前生命周期状态,添加/删除 生命周期观察者等等。Lifecycle
内部有三个抽象方法、两个枚举类和一个变量。其中Event
和State
分别表示生命周期事件和生命周期状态。
public abstract class Lifecycle {
/**
* Lifecycle coroutines extensions stashes the CoroutineScope into this field.
*
* @hide used by lifecycle-common-ktx
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@NonNull
AtomicReference<Object> mInternalScopeRef = new AtomicReference<>();
/**
* Adds a LifecycleObserver that will be notified when the LifecycleOwner changes
* state.
* <p>
* The given observer will be brought to the current state of the LifecycleOwner.
* For example, if the LifecycleOwner is in {@link State#STARTED} state, the given observer
* will receive {@link Event#ON_CREATE}, {@link Event#ON_START} events.
*
* @param observer The observer to notify.
*/
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
/**
* Removes the given observer from the observers list.
* <p>
* If this method is called while a state change is being dispatched,
* <ul>
* <li>If the given observer has not yet received that event, it will not receive it.
* <li>If the given observer has more than 1 method that observes the currently dispatched
* event and at least one of them received the event, all of them will receive the event and
* the removal will happen afterwards.
* </ul>
*
* @param observer The observer to be removed.
*/
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
/**
* Returns the current state of the Lifecycle.
*
* @return The current state of the Lifecycle.
*/
@MainThread
@NonNull
public abstract State getCurrentState();
@SuppressWarnings("WeakerAccess")
public enum Event {
/**
* Constant for onCreate event of the {@link LifecycleOwner}.
*/
ON_CREATE,
/**
* Constant for onStart event of the {@link LifecycleOwner}.
*/
ON_START,
/**
* Constant for onResume event of the {@link LifecycleOwner}.
*/
ON_RESUME,
/**
* Constant for onPause event of the {@link LifecycleOwner}.
*/
ON_PAUSE,
/**
* Constant for onStop event of the {@link LifecycleOwner}.
*/
ON_STOP,
/**
* Constant for onDestroy event of the {@link LifecycleOwner}.
*/
ON_DESTROY,
/**
* An {@link Event Event} constant that can be used to match all events.
*/
ON_ANY;
//......
}
/**
* Lifecycle states. You can consider the states as the nodes in a graph and
* {@link Event}s as the edges between these nodes.
*/
@SuppressWarnings("WeakerAccess")
public enum State {
/**
* Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
* any more events. For instance, for an {@link android.app.Activity}, this state is reached
* <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.
*/
DESTROYED,
/**
* Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is
* the state when it is constructed but has not received
* {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.
*/
INITIALIZED,
/**
* Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
* <ul>
* <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
* <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
* </ul>
*/
CREATED,
/**
* Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
* <ul>
* <li>after {@link android.app.Activity#onStart() onStart} call;
* <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
* </ul>
*/
STARTED,
/**
* Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached after {@link android.app.Activity#onResume() onResume} is called.
*/
RESUMED;
/**
* Compares if this State is greater or equal to the given {@code state}.
*
* @param state State to compare with
* @return true if this State is greater or equal to the given {@code state}
*/
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
下面以Activity 为例来分析:
1.观察者如何注册?
在上面说到,我们在MainActivity中通过 getLifecycle().addObserver()
将我们的组件进行了注册。我们看下代码具体做了什么。首先看下gelifecycle()
方法:
ComponentActivity.java
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
//.....
/**
* {@inheritDoc}
* <p>
* Overriding this method is no longer supported and this method will be made
* <code>final</code> in a future version of ComponentActivity. If you do override
* this method, you <code>must</code>:
* <ol>
* <li>Return an instance of {@link LifecycleRegistry}</li>
* <li>Lazily initialize your LifecycleRegistry object when this is first called.
* Note that this method will be called in the super classes' constructor, before any
* field initialization or object state creation is complete.</li>
* </ol>
*/
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
getLifecycle()
方法返回的是LifecycleRegistry
类的实例对象mLifecycleRegistry
。LifecycleRegistry
是Lifecycle
的一个实现,我们在开发中接触的最多的其实是它。现在,我们接着看看addObserver()
方法是如何保存我们的观察者的,在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--;
}
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
和初始状态initialState包装到ObserverWithState
类的对象,mObserverMap
是FastSafeIterableMap
类的一个实例,是一个可以在遍历中删除元素的集合,采用链表实现,同时支持键值存储。关于FastSafeIterableMap可以看下这篇文章。然后将包装类保存到mObserverMap
集合中。接下来,代码通过calculateTargetState()
方法计算出当前状态targetState
,如果当前的观察者的初始状态 小于 targetState
,则对观察者进行状态同步,下发状态变更事件。到这里,我们的观察者就已经注册完成了。
2.生命周期事件是如何分发的?
在完成生命周期观察者的注册后,那么被观察者是如何将生命周期的变化通知观察者的呢?在介绍LifecycleOwner
的时候,我们知道要实现该类来表示一个类具有Android生命周期,Activity
也是如此,我们可以找到ComponentActivity
。在onCreate()
方法中,我们可以看到下面这个:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
// Restore the Saved State first so that it is available to
// OnContextAvailableListener instances
mSavedStateRegistryController.performRestore(savedInstanceState);
mContextAwareHelper.dispatchOnContextAvailable(this);
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
代码创建了一个ReportFragment
,它是一个没有UI的空白Fragment。看到这个,接着进入ReportFragment
的内部源码,我们应该知道到了ReportFragment
才是生命周期分发的地方。
ReportFragment.java
@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;
}
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);
}
}
}
通过创建一个空白Fragment,然后在Fragment的生命周期方法中去分发生命周期事件。接着看dispatch(getActivity(), event)
的调用,其实调用的还是LifecycleRegistry
的handleLifecycleEvent()
方法。
LifecycleRegistry.java
/**
* Sets the current state and notifies the observers.
* <p>
* Note that if the {@code currentState} is the same state as the last call to this method,
* calling this method has no effect.
*
* @param event The event that was received
*/
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;
}
Lifecycle.java
/**
* Returns the new {@link Lifecycle.State} of a {@link Lifecycle} that just reported
* this {@link Lifecycle.Event}.
*
* Throws {@link IllegalArgumentException} if called on {@link #ON_ANY}, as it is a special
* value used by {@link OnLifecycleEvent} and not a real lifecycle event.
*
* @return the state that will result from this event
*/
@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");
}
在LifecycleRegistry
中接着调用moveToState(event.getTargetState())
,event.getTargetState()
是根据声明周期事件取得对应的状态。,然后更新当前mState
状态,下面调用 sync()
更新观察者状态:
LifecycleRegistry.java
// happens only on the top of stack (never in reentrance),
// so it doesn't have to take in account parents
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.
// 如果 mState 小于 mObserverMap 中的状态值,调用 backwardPass()
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
// 如果 mState 大于 mObserverMap 中的状态值,调用 forwardPass()
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
更新之前,首先判断Activity是否已经回收销毁,然后mObserverMap中获取观察开始更新,这里分为两个操作: backwardPass()
和 forwardPass()
。
-
如果
mState
小于mObserverMap
中的状态值,调用backwardPass()
, -
如果
mState
大于mObserverMap
中的状态值,调用forwardPass()
。
先看下backwardPass()
方法:
LifecycleRegistry.java
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Map.Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
ObserverWithState observer = entry.getValue();
// 向下传递事件,直到 observer 的状态值等于当前状态值
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
Event event = Event.downFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event down from " + observer.mState);
}
pushParentState(event.getTargetState());
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
backwardPass()
会同步 mObserverMap
中的所有观察者到指定生命周期状态,期间每个状态都会依次分发(状态不会跳跃)。分发生命周期事件最终调用到ObserverWithState
的dispatchEvent()
方法。
LifecycleRegistry.java
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;
}
}
接着调用 mLifecycleObserver.onStateChanged()
方法,mLifecycleObserver
是我们在注册观察者的时候在ObserverWithState
构造方法中通过Lifecycling.lifecycleEventObserver(observer)
生成的,我们进入看下:
Lifecycling.java
@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);
}
我们创建生命周期观察者时继承的LifecycleObserver
接口,所以我们直接看getObserverConstructorType()`方法:
Lifecycling.java
private static int getObserverConstructorType(Class<?> klass) {
Integer callbackCache = sCallbackCache.get(klass);
if (callbackCache != null) {
return callbackCache;
}
int type = resolveObserverCallbackType(klass);
sCallbackCache.put(klass, type);
return type;
}
private static int resolveObserverCallbackType(Class<?> klass) {
// anonymous class bug:35073837
if (klass.getCanonicalName() == null) {
return REFLECTIVE_CALLBACK;
}
Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
if (constructor != null) {
sClassToAdapters.put(klass, Collections
.<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
return GENERATED_CALLBACK;
}
//如果类中存在被OnLifecycleEvent注解标记的方法,返回的是true
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;
}
ClassesInfoCache.java
boolean hasLifecycleMethods(Class<?> klass) {
Boolean hasLifecycleMethods = mHasLifecycleMethods.get(klass);
if (hasLifecycleMethods != null) {
return hasLifecycleMethods;
}
Method[] methods = getDeclaredMethods(klass);
for (Method method : methods) {
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation != null) {
// Optimization for reflection, we know that this method is called
// when there is no generated adapter. But there are methods with @OnLifecycleEvent
// so we know that will use ReflectiveGenericLifecycleObserver,
// so we createInfo in advance.
// CreateInfo always initialize mHasLifecycleMethods for a class, so we don't do it
// here.
createInfo(klass, methods);
return true;
}
}
mHasLifecycleMethods.put(klass, false);
return false;
}
getObserverConstructorType
()方法中调用了resolveObserverCallbackType()
方法,在这个方法中,我们关注下hasLifecycleMethods
这个变量值,通过查看ClassesInfoCache
的hasLifecycleMethods()
方法我们可以知道,主要是判断当前观察者类中是否有OnLifecycleEvent
注解标记的方法,如果有的话,调用createInfo
来创建信息,并且返回true。所以在lifecycleEventObserver()
中,type是REFLECTIVE_CALLBACK
类型,表示的是反射类型,返ReflectiveGenericLifecycleObserver
类对象。
/**
* An internal implementation of {@link LifecycleObserver} that relies on reflection.
*/
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
那么mLifecycleObserver.onStateChanged()
调用的就是该对象中的onStateChanged()
方法,后面调用的是CallbackInfo
的invokeCallbacks
方法, 里面的mInfo
就是上一步中createInfo
所创建的。我们进入CallbackInfo:
static class CallbackInfo {
final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;
final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;
CallbackInfo(Map<MethodReference, Lifecycle.Event> handlerToEvent) {
mHandlerToEvent = 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<>();
mEventToHandlers.put(event, methodReferences);
}
methodReferences.add(entry.getKey());
}
}
@SuppressWarnings("ConstantConditions")
void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
//反射调用分发事件
invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
//同时也分发一次ON_ANY 事件
invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
target);
}
private static void invokeMethodsForEvent(List<MethodReference> handlers,
LifecycleOwner source, Lifecycle.Event event, Object mWrapped) {
if (handlers != null) {
for (int i = handlers.size() - 1; i >= 0; i--) {
handlers.get(i).invokeCallback(source, event, mWrapped);
}
}
}
}
MethodReference.java
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);
}
}
在这里,我们可以看到就是通过反射去调用OnLifecycleEvent
标记的方法,做一次事件的分发,同时ON_ANY事件也会每次都触发一次。
看到这里,我们基本上明白了生命周期事件是如何分发的,同时我们也知道为什么OnLifecycleEvent
注解标记方法后,该方法就会在生命周期变化时得到调用。
我们注意到type还有一个GENERATED_CALLBACK
类型,那么这个类型做了什么呢?我们知道上面是通过反射去执行的,反射操作一直是耗性能的操作,所以为了优化性能,Lifecycle可以选择通过apt在编译器生成对应代码,然后直接调用。可以通过添加下面的库来支持,这里就不多做介绍了。
kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
结尾
Lifecycle的介绍暂时就到这里,很多细节的忽略请多包涵,文中若有不对的地方,还请大家多多指正!