Lifecycle
1.引入库
"androidx.lifecycle:lifecycle-runtime:2.2.0"
"androidx.lifecycle:lifecycle-common-java8:2.2.0"
"androidx.lifecycle:lifecycle-extensions:2.2.0"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.2.0"
kapt "androidx.lifecycle:lifecycle-compiler:2.2.0"
2.Android Activity中的Lifecycle源码解析
public abstract class Lifecycle {
//添加观察者
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
//移除观察者
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
//获取当前状态
public abstract State getCurrentState();
//生命周期事件,对应Activity生命周期方法
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY //可以响应任意一个事件
}
//生命周期状态. (Event是进入这种状态的事件)
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
//判断至少是某一状态
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
Event触发的时机:
- ON_CREATE、ON_START、ON_RESUME事件,是在LifecycleOwner对应的方法执行 之后 分发。
- ON_PAUSE、ON_STOP、ON_DESTROY事件,是在LifecycleOwner对应的方法调用 之前 分发。
在Android中,androidx.activity.ComponentActivity和androidx.core.app.ComponentActivity都会实现LifecycleOwner接口,而这个接口中只有一个方法,就是
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
而在androidx.activity.ComponentActivity和androidx.core.app.ComponentActivity中,该方法的实现,其实都是一样的。
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
(1)androidx.activity.ComponentActivity和androidx.core.app.ComponentActivity创建LifecycleRegistry对象
但是这两个Activity,其实都有自己的mLifecycleRegistry对象。
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
LifecycleRegistry对象其实可以理解为观察者模式中的Observable,也就是被观察者,而LifecycleRegistry对象的创建,其实是传入一个LifecycleOwner实现类对象,而androidx.activity.ComponentActivity和androidx.core.app.ComponentActivity实现了LifecycleOwner接口,所以传入的是this。
(2)LifecycleRegistry.addObserver()
LifecycleRegistry中聚合了多个LifecycleObserver,生命周期改变时,通知LifecycleObserver进行相应方法的调用。
在LifecycleRegistry类中的addObserver方法中,其实就是通过封装LifecycleObserver生成了一个ObserverWithState对象,然后放入FastSafeIterableMap中,而FastSafeIterableMap其实就是一个自定义列表,用于保存观察者并且可在遍历期间处理删除/添加。
其实在自定义的某个类去实现LifecycleObserver接口的时候,在activity中,是需要通过getLifecycle().addObserver()进行注册的,这个过程其实就是调用了LifecycleRegistry的addObserver()方法。
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// 这里要注意一点,在new OserverWithState传入LifecycleObserver对象的时候
// 会把LifecycleObserver对象传给Lifecycling.lifecycleEventObserver(observer)
// 在这里会封装成ReflectiveGenericLifecycleObserver对象
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++;
// 这里其实就是粘性问题:即把之前优先分发的事件,一个个分发给后添加的观察者
// 比如在Activity的onResume生命周期中调用LifecycleRegistry.addObserver的时候
// 因为新添加的statefulObserver的mState为INITIALIZED
// 而targetState已经发生了变化,在LifecycleRegistry中的mState变成了RESUMED
// 这里就会满足小于0的条件,并且在map中也有了新加入的这个Observer
// 分发一次之后,就会改变targetState的值,如果新的值还是比当前的大,则继续分发
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--;
}
(3)LifecycleRegistry.ObserverWithState这个内部类封装LifecycleObserver
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
(4)Lifecycling.lifecycleEventObserver()创建不同的LifecycleEventObserver实现对象
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);会将LifecycleObserver对象封装在ReflectiveGenericLifecycleObserver对象中。但是这里的需要判断是实现了哪个接口,比如androidx.activity.ComponentActivity中的构造函数中,因为是直接new LifecycleEventObserver匿名内部类实现接口对象,则isLifecycleEventObserver为true,就不会new ReflectiveGenericLifecycleObserver(),而在自定义一个类的时候,一般实现LifecycleObserver接口,则就会new ReflectiveGenericLifecycleObserver()
// 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);
}
// TODO: 自定义实现LifecycleObserver接口的时候,是创建该Observer实例
// ReflectiveGenericLifecycleObserver.java
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
// 首先会创建一个CallbackInfo对象
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
// ClassesInfoCache.java
// 所有观察者的回调信息
final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;
// 观察者是否有注解了生命周期的方法
final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;
// 其实这里就是创建了一个CallbackInfo对象,而这个对象其实就是收集实现了LifecycleObserver接口的类中
// 使用了OnLifecycleEvent注解进行注释的方法集合,用于对应的LifecycleObserver实现类生命周期的分发
CallbackInfo getInfo(Class klass) {
CallbackInfo existing = mCallbackMap.get(klass);
if (existing != null) {
return existing;
}
existing = createInfo(klass, null);
return existing;
}
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();
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");
}
}
Lifecycle.Event event = annotation.value();
// 第二个参数必须是Event
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");
}
MethodReference methodReference = new MethodReference(callType, method);
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
}
CallbackInfo info = new CallbackInfo(handlerToEvent);
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
比如:
androidx.activity.ComponentActivity的构造函数:这里是new LifecycleEventObserver
public ComponentActivity() {
Lifecycle lifecycle = getLifecycle();
//noinspection ConstantConditions
if (lifecycle == null) {
throw new IllegalStateException("getLifecycle() returned null in ComponentActivity's "
+ "constructor. Please make sure you are lazily constructing your Lifecycle "
+ "in the first call to getLifecycle() rather than relying on field "
+ "initialization.");
}
if (Build.VERSION.SDK_INT >= 19) {
getLifecycle().addObserver(new LifecycleEventObserver() {
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_STOP) {
Window window = getWindow();
final View decor = window != null ? window.peekDecorView() : null;
if (decor != null) {
decor.cancelPendingInputEvents();
}
}
}
});
}
getLifecycle().addObserver(new LifecycleEventObserver() {
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_DESTROY) {
if (!isChangingConfigurations()) {
getViewModelStore().clear();
}
}
}
});
if (19 <= SDK_INT && SDK_INT <= 23) {
getLifecycle().addObserver(new ImmLeaksCleaner(this));
}
}
自定义的BasePresenter:这里是实现LifecycleObserver接口
public class BasePresenter<T extends IBaseView> implements LifecycleObserver {
WeakReference<T> iGoodsView;
/**
* 绑定view
*/
public void attachView(T view){
iGoodsView=new WeakReference<>(view);
}
/**
* 解绑
*/
public void detachView(){
if(iGoodsView!=null){
iGoodsView.clear();
iGoodsView=null;
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreateX(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
void onStartX(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void onStop(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void onResume(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
void onPause(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestory(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
void onAny(LifecycleOwner owner) {
}
}
所以上面的两种不同的实现,BasePresenter实现的是LifecycleObserver,所以这个LifecycleObserver的最终实现是ReflectiveGenericLifecycleObserver。而ComponentActivity因为是new LifecycleEventObserver,所以这个匿名内部类对象就是最终实现。
(5)androidx.core.app.ComponentActivity的onCreate方法创建一个空白Fragment
在androidx.core.app.ComponentActivity的onCreate方法中,会调用
@SuppressLint("RestrictedApi")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
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();
}
}
这里使用ReportFragment,如果是api29以及以上的,则可以直接注册回调来获取Activity的生命周期回调。如果是api29以下的,则需要手动给Activity添加一个空白的Fragment,类似于Glide监听生命周期回调的做法。
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) {
}
}
LifecycleCallbacks的定义如上,是在ReportFragment中定义的,其实就是使用了Application.ActivityLifecycleCallbacks来实现了。
其实就是在androidx.core.app.ComponentActivity中添加一个ReportFragment,而ReportFragment的生命周期方法,其实都调用了一个dispatch方法。
// ReportFragment.java
private void dispatch(Lifecycle.Event event) {
Activity activity = getActivity();
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
// 因为Activity实现了LifecycleOwner接口
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
所以在ReportFragment的生命周期方法,其实就会通过调用对应的dispatch方法进而调用到了Activity的getLifecycle()方法获取到一个LifecycleRegistry对象,然后调用LifecycleRegistry的handleLifecycleEvent()方法。
// LifecycleRegistry.java
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
// 事先获取到Activity的下一个状态
State next = getStateAfter(event);
moveToState(next);
}
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;
}
这里需要事先获取到Activity的下一个生命周期状态,而这个状态过程其实与Fragment的类似,都是先升序,然后再降序的一个过程。即ON_CREATE是CREATED,ON_RESUME是RESUMED,然后ON_PAUSE是变成STARTED
// LifecycleRegistry.java
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);
}
而上面调用的sync()方法,其实其内部会调用两个方法backwardPass()和forwardPass(),一个是逆推,一个是顺推,其实就是可以认为一个是正序,一个是倒序。
比如forwardPass(),其实其内部就是遍历刚才缓存Observer的集合,找到每个Observer
// LifecycleRegistry.java
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);
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}
而这里的dispatchEvent,其实就是ObserverWithState的方法,因为ObserverWithState内部封装了LifecycleEventObserver对象,而LifecycleEventObserver对象又是封装了LifecycleObserver对象的。
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
比如Activity的,其实onStateChanged是在androidx.activity.ComponentActivity的构造器中添加注册的LifecycleEventObserver监听接收对应的处理回调,在这里就会根据是ON_STOP还是ON_DESTROY进行回调的处理,也就是生命周期的处理。
这样的生命周期回调,在自定义类实现LifecycleObserver接口的时候,也可以采用注解的方式注册对应的LifecycleEventObserver监听,这样的生命周期的回调,其实就是回调到对应的注解和事件的方法中。这样是采用了类似于apt注解处理器的方式,生成了对应的java类
这里需要注意,如果是自定义添加监听的时候,是实现了LifecycleEventObserver,那么在分发的时候,调用ObserverWithState的dispatchEvent方法去分发,就会直接回调到了自定义LifecycleEventObserver实现类中的onStateChanged中;而如果是使用LiveData添加观察者的话,则是封装成LifecycleBoundObserver对象,然后通过其onStateChanged方法继续进一步的处理分发,调用到对应的Observer的onChanged方法进行最终的处理
如果这里的分发是分发到上面的那个自定义的BasePresenter,则需要经过ReflectiveGenericLifecycleObserver
// ClassesInfoCache.java的内部类CallbackInfo
void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
// 这里的mEventToHandlers其实就是BasePresenter那些添加了注释的方法集合
invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
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);
}
}
}
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);
}
}
从上面的原理解析,可以知道,Lifecycle的生命周期的感知和分发,其实也是依赖于一个ReportFragment,这其实也是一个空的Fragment,这样的做法,其实与Glide的生命周期的监听是类似的做法,都是采用一个空的Fragment来监听生命周期的变化,然后在不同的生命周期做不同的操作。