通常情况下Jetpack组件都是混合一起使用的,这里我们为了讲解,可能会单独使用。
Lifecycles是AAC中最基本的组件之一,主要是用来管理Activity与Fragment生命周期状态的信息,并允许其他对象观察此状态。后续的LiveData和ViewModel,都是基于它实现的。
以前我们使用MVP中的presenter,通过接口的方式感知生命周期,这种方式low了,所以了官网就封装了Lifecycles组件给开发者使用,即屏蔽了细节,又降低了使用难度。
先看一下Lifecycles简单的使用:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lifecycles);
getLifecycle().addObserver(new MyObserver());
}
创建观察者
public class MyObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void create(){
Logger.i("ON_CREATE");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void resume(){
Logger.i("ON_RESUME");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void start(){
Logger.i("ON_START");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void stop() {
Logger.i("ON_STOP");
}
}
启动Android之后就可以看见日志的输出了:
30594-30594/cn.iwcode.androidjetpack I/Jetpack: ON_CREATE
30594-30594/cn.iwcode.androidjetpack I/Jetpack: ON_START
30594-30594/cn.iwcode.androidjetpack I/Jetpack: ON_RESUME
那么问题就来了,lifecycle是如何感知Activity的生命周期的,又是如何调用注解修饰的方法的?
我们先从源码上来分析:首先来看添加观察者的这一行代码,让我们点进去看一下getLifecycle
getLifecycle().addObserver(new MyObserver());
public class ComponentActivity extends androidx.core.app.ComponentActivity implements ...
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
...
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
...
}
这个getLifecycle()是在ComponentActivity类中,addObserver是添加观察者的,但是我们并没有看见有关于生命周期的回调呀!怪事呀,那生命周期是在哪里回调了?
这时我在观察者中打印了一下堆栈信息,发现了一个ReportFragment。
public class ReportFragment extends Fragment {
private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
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;
}
看到这里就明白了,原来是Lifecycle利用了Fragment来实现监听生命周期的,然后使用dispatch分发事件,最终会调用LifecycleRegistry的handleLifecycleEvent的。LifecycleRegistry 是 Lifecycle 的实现,并负责管理 Observer。
Lifecycle 中定义了 Event 和 State
Event:从框架和Lifecycle类派发的生命周期事件。
State:由Lifecycle对象跟踪的组件的当前状态。
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
@SuppressWarnings("WeakerAccess")
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
Event和State对应关系 图片来自官方
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-t1NYNudr-1571974210773)(https://developer.android.google.cn/images/topic/libraries/architecture/lifecycle-states.svg)]
我们接下来看一下注解的方法是如何被调用的,从上面的分析我们了解到生命周期的分发调用了LifecycleRegistry的handleLifecycleEvent方法,这里我们就继续看这个方法:
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
// 根据event获取State状态
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;
}
getStateAfter(event)
根据当前的Event获取对应的State,接着调用了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.");
}
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;
}
sync中对比了当前的mState以及上一个State,是前进还是后退,比如:
onResume -> onPause (forwardPass),onPause -> onResume (backwardPass)
这里我们来看backwardPass方法,获取到观察者,然后调用observer.dispatchEvent函数。
这里就不跟了,有兴趣的可以继续往下看。
在Observer用注解修饰的方法,会被通过反射的方式获取,并保存下来,然后在生命周期发生改变的时候再找到对应 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));
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
Lifecycle 是一个专门用来处理生命周期的库,它能够帮助我们将 Acitivity、Framgent 的生命周期处理与业务逻辑处理进行完全解耦,让我们能够更加专注于业务;通过解耦让 Activity、Fragment 的代码更加可读可维护。
同时 Lifecycle 作为 AAC 的基石,为 LiveData、ViewModel 的登场打下坚实的基础。