JetPack之Lifecycles使用和原理分析
作为一个开发人员,学习过的知识是否掌握,通过实践验证,并加以分析,让自己对知识点有更深刻的认知,如果下面内容有不当之处,请多多指教。下面进行Lifecycle主题。
正文
通过下面几点去认识Lifecycle的真面目。
- 使用Lifecycle的含义与意义
- Lifecycle的简单使用
- Lifecycle的组成与实现原理
什么是Lifecycle?
Lifecycle 组件是 google开发出的JetPack架构组件之一,它具有感知生命周期变化。主要是通过观察者模式去感知生命周期变化。
为什么要使用Lifecycle?
- 可以让开发者构建能感知的组件(如指Activity 、Fragment)生命周期的类。
- 生命周期感知型组件可执行操作来响应另一个组件(如 Activity 和 Fragment)的生命周期状态的变化。这些组件有助于您写出更有条理且往往更精简的代码,这样的代码更易于维护。
- 通过生命周期感知型组件,从而实现在活动状态下允许操作,而在销毁状态下需要自动禁止操作,释放资源,防止内存泄露。
通过MVP例子去玩一下Lifecycle
实现这样一个功能:监听某个 Activity 生命周期的变化,在生命周期改变的时候打印日志。
- 定义一个与和生命周期相关的接口IPresenter。
/** * Author: 安仔夏天勤奋 * Date: 2020/3/28 * Desc: */ public interface IPresenter { void onCreate(); void onStart(); void onResume(); void onPause(); void onStop(); void onDestroy(); }
- 定义一个IPresenter的实现类BasePresenter、LifecycleObserver
/** * Author: 安仔夏天勤奋 * Date: 2020/3/28 * Desc: */ public class BasePresenter implements IPresenter, LifecycleObserver { private static final String TAG = "BasePresenter"; @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) @Override public void onCreate() { Log.e(TAG,"=========>>> onCreate"); } @OnLifecycleEvent(Lifecycle.Event.ON_START) @Override public void onStart() { Log.e(TAG,"=========>>> onStart"); } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) @Override public void onResume() { Log.e(TAG,"=========>>> onResume"); } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) @Override public void onPause() { Log.e(TAG,"=========>>> onPause"); } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) @Override public void onStop() { Log.e(TAG,"=========>>> onStop"); } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) @Override public void onDestroy() { Log.e(TAG,"=========>>> onDestroy"); } }
需要去实现生命周期,那么就要实现LifecycleObserver接口,同时在每一个方法实现上增加@OnLifecycleEvent(Lifecycle.Event.XXXX)注解,OnLifecycleEvent对应了Activity的生命周期方法。
-
在Activity中绑定BasePresenter
public class MainActivity extends AppCompatActivity { BasePresenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); presenter = new BasePresenter(); //添加一个观察者presenter,这样就与父类的被观察都LifecycleOwner建立了关系 getLifecycle().addObserver(presenter); } }
-
Activity启动和退出时的日志打印
BasePresenter: =========>>> onCreate BasePresenter: =========>>> onStart BasePresenter: =========>>> onResume BasePresenter: =========>>> onPause BasePresenter: =========>>> onStop BasePresenter: =========>>> onDestroy
从上面的代码看是不是很简单,的确挺简单的。还可以继承BasePresenter扩展成跟自己业务对应的Presenter去监听生命周期,然后复写需要的生命周期方法即可。从上面代码也可以看出,监听感知 Activity 的生命周期,只需要在Activity中调用一句 getLifecycle().addObserver(presenter) 就可以了。Lifecycle 是怎样实现感知生命周期的呢,监听流程是怎么样的呢,下面开始源码解析了。
Lifecycle的组成与实现原理
从上面例子不难看出,我们的切入点就是getLifecycle().addObserver(presenter)。其实是通过观察者LifecycleObserver和被观察者LifecycleOwner(在底层的Activity/Fragment都实现了)进行绑定,从而实现监听生命周期变化,也是一种观察者模式啦。至于怎么观察监听的,下面会详细说明。从上述例子还是很难理解 MainActivity、LifecycleOwner、Lifecycle 和 LifecycleObserver 之间的关系,我们通过辅助类图整理他们的关系,当我们在整理绘制类图的过程中,理深刻地了解框架大概包含哪些组成部分,有哪些比较重要的成员变量和方法。
分析Lifecycle组件内的类与接口的关系
从上面的类图可以分析出:
-
MainActivity 继承AppCompatActivity,AppCompatActivity继承FragmentActivity ,也就是MainActivity 继承自 FragmentActivity,而 FragmentActivity 是 LifecycleOwner 的实现类。所以MainActivity 通过 getLifecycle()方法返回的是 Lifecycle 的子类 LifecycleRegistry实例。
-
LifecycleRegistry是控制中心。它负责控制state的转换、接受分发event事件。在 LifecycleRegistry 类中的静态内部类 ObserverWithState 持有LifecycleEventObserver 对象的实例,LifecycleEventObserver 是 LifecycleObserver 的子类。
-
LifecycleOwner 是一个接口,它有一个 getLifecycle()方法要子类去实现。LifecycleOwner是担当生命周期的事件分发者,在 Activity/Fragment 他们的生命周期发生变化的时发出相应的 Event 给 LifecycleRegistry。
-
LifecycleObserver是担当生命周期的观察者,通过注解将处理函数与希望监听的Event绑定,当相应的Event发生时,LifecycleRegistry会通知相应的函数进行处理。
-
Lifecycle 是一个抽象类,它有两个枚举类型的内部类 Event和 State,分别对应着事件类型和组件的状态;
通过类图分析我们可以知道了Activity、LifecycleRegistry、LifecycleOwner 、LifecycleObserver、Lifecycle 之间的对应关系。但是我们还不知道注册/注销监听流程和生命周期分发流程。
分析Lifecycle组件的监听流程/生命周期分发流程
通过整理类图,我们脑海里有了一个大概的类与接口对应关系和重要的变量与方法调度概念。在整理类图的过程,要记录调度次序,看下面的时序图。
Lifecycle组件的监听流程
从时序图中我们可以看出,在FragmentActivity中创建了一个LifecycleRegistry对象。FragmentActivity的父类ComponentActivity中实现了LifecycleOwner接口,这样LifecycleRegistry就与LifecycleOwner绑定了。在父类构造方法中调用了getLifecycle().addObserver(observer),那么 addObserver 就可以作为源码分析的切入口。通过一步步追踪,最终确定addObserver 实际上是调用了 LifecycleRegistry 的 addObserver (observer)方法,并将 LifecycleObserver 的对象作为参数传递进去,这样就完成了一个完整的注册监听过程。
MainActivity 中调用 getLifecycle()方法得到 LifecycleRegistry 对象,LifecycleRegistry 对象的初始化在 FragmentActivity 中完成。
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));
}
}
当getLifecyle().addObserver监听的时候,会先初始化状态值,然后把状态值与传入的observer绑定并保存到mObserverMap。
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
//得到初始化状态值,把状态与传入的observer绑定并保存到mObserverMap
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++;
//当生命周期发生改变的时候,就会遍历这个ObserverWithState集合
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--;
}
// 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.
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;
}
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));
//如果下一个状态与当前状态不等,则分发事件
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
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();
}
}
}
生命周期时分发事件
在 Activity 生命周期变化时,在每个生命周期回调函数中调用 LifecycleRegistry的 handleLifecycleEvent()方法,在 handleLifecycleEvent()方法的层层调用中,最后通过 observer.dispatchEvent(lifecycleOwner, event) 方法中onStateChanged(owner, event)将生命周期的变化传递到 LifecycleObserver 的实现类BasePresenter 中。
需要注意的是启动Activity时调用onCreat()方法的时候会注入ReportFragment,这个Fragment没有界面。这样就绑定了一个Fragment去管理生命周期了。在ReportFragment中做一些分发事件。
public class ReportFragment extends Fragment {
//省略代码...
public static void injectIfNeededIn(Activity activity) {
// ProcessLifecycleOwner should always correctly work and some activities may not extend
// FragmentActivity from support lib, so we use framework fragments for activities
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();
}
}
//省略代码...
@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(Lifecycle.Event event) {
Activity activity = getActivity();
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);
}
}
}
//省略代码...
}
接下来我们看看handleLifecycleEvent()方法中做了那些事情。
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
//去拿下一个状态
State next = getStateAfter(event);
//移动到下一个状态
moveToState(next);
}
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);
}
拿取状态时,是按照事件取对应的状态,如果事件是ON_CREATE、ON_STOP,状态为CREATED,如果事件是ON_START、ON_PAUSE,状态为STARTED,如果事件是ON_RESUME,状态为RESUMED,如果事件是ON_DESTROY,状态为DESTROYED。根据获取的状态移动到下一个状态。
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是有一个init初始状态值,随着Activity的生命周期变化时,状态都随之改变。addObserver初始时会同步状态,和Activity的生命周期变化时同步状态。下面看一个状态时序图可以更加好理解。
当生命周期发生变化时,会调用mLifecycleObserver.onStateChanged(owner, event)进行分发事件。
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
//LifecycleObserver有多个实现类
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
然而mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer)的实现类有很多个,通过追踪,最终都会走到ReflectiveGenericLifecycleObserver类,在构建ReflectiveGenericLifecycleObserver类时,将ObserverWithState传入的observer(这个observer其实就是自己写的BasePresenter)通过ClassesInfoCache类的getInfo(observer)方法生产出CallbackInfo信息。CallbackInfo信息是通过反射拿到外面定义的BasePresenter类中标了OnLifecycleEvent注解的通通解析出来put进来。
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(LifecycleOwner source, Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
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;
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");
}
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;
}
总结
- 当自己还不太熟悉第三方架构时,先查阅API,简单地实现一个DEMO。
- 自己多画类图,时序图,这样对自己在后面看源码时减少阻力。
- 多思考这个架构用了那些模式。
- Lifecycle组件架构用了观察者模式,注解,反射等。