1. 什么是Lifecycle,怎么使用
Lifecyle 是Google Jetpack 中提供给我们使用的用来监听Activity和Fragment 生命周期的组件,在以前我们想知道Activity 或者Frament 运行到哪个生命周期并做出对应的操作的时候,我们需要在其中重写对应的生命周期方法,比如下面的代码:
class MainActivity2 : AppCompatActivity() {
private val monitor:Monitor = Monitor()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
}
override fun onStart() {
super.onStart()
monitor.onStart()
}
override fun onResume() {
super.onResume()
monitor.onResume()
}
override fun onPause() {
super.onPause()
monitor.onPause()
}
override fun onStop() {
super.onStop()
monitor.onStop()
}
override fun onDestroy() {
super.onDestroy()
monitor.onDestroy()
}
}
如果我们还有其他的监听操作,那每个生命周期的回调都要写一套,这样的方式太过繁琐,有了Lifecycle 我们的工作量就大大减轻了。
如何使用:
1. 创建一个观察者类
class MyObservable :DefaultLifecycleObserver{
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
println("${owner}------onCreate")
}
override fun onStart(owner: LifecycleOwner) {
super.onStart(owner)
println("${owner}------onStart")
}
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
println("${owner}------onResume")
}
override fun onPause(owner: LifecycleOwner) {
super.onPause(owner)
println("${owner}------onPause")
}
override fun onStop(owner: LifecycleOwner) {
super.onStop(owner)
println("${owner}------onStop")
}
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
println("${owner}------onDestroy")
}
2. 在Activity 初始化时注册观察者
class MainActivity2 : AppCompatActivity() {
init {
lifecycle.addObserver(MyObservable())
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
}
}
这样当Activity 运行到响应的生命周期时,便会调用我们注册的观察者对应的生命周期回调,运行结果如下:
2. lifecycle 的原理
首先Lifecycle是基于观察者模式实现的,观察者模式包含两种对象:观察者对象和目标对象,目标对象和观察者对象存在着一对多的关系,当目标对象状态发生变化时,所有依赖他的观察者对象会收到相应的通知并做出他们自己的行为。那Lifecycle 中的观察者和目标对象是谁呢?这里就需要将涉及的几个重要的类说明一下,方便后续说到源码的时候能够更好的理解。
Lifecycle: 一个持有Android 生命周期事件和状态的抽象类,声明了添加和移除观察者的方法,实现类为LifeRegistry,内部维护着两个枚举 Event 和State
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;
}
}
- State:Lifecycle的生命周期所处的状态。
- Event:Lifecycle生命周期对应的事件,这些事件会映射到Activity和Fragment中的回调事件中。
State 的状态是有固定顺序的,并且会根据Event 事件进行变化,因此State 有了生命周期的概念。
他们之间的对应关系如下:
LifecycleRegsitry: Lifecycle实现类,维护着观察者列表,当目标对象生命周期发生变化时,通知观察者。
LifecycleOwner: 安卓生命周期的持有者,Fragment和FragmentActivity类实现了LifecycleOwner接口,它具有访问生命周期的getLifecycle方法,使用时需要在自己的类中实现LifecycleOwner。
LifecycleObserver: 生命周期观察者,是个空接口,不能直接使用,平时使用DefaultLifecycleObserver 或者LifecycleEventObserver监听生命周期事件与状态的改变。
接下来我们从添加观察者开始查看源码
lifecycle.addObserver(MyObservable())
getLifecyle 这里直接来到了ComponentActivity
//ComponentActivity
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
上面我们说过LifecycleRegistry 是Lifecycle 真正的实现类,这时候代码就来到了LifecycleRegistry 的addObserver()方法。
public void addObserver(@NonNull LifecycleObserver observer) {
//注释1 将观察者对象封装为ObserverWithState,并给与一个初始状态
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//注释2 将ObserverWithState 对象存入HashMap 中
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
...省略代码
}
这里注释1 是将观察者对象封装为ObserserWithState,顾名思义就是持有状态的观察者,并给予一个初始状态,注释2就是将封装好的对象存入HashMap 中。
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
}
ObserverWithState 持有当前的目标对象的状态以及一个LifecycleEventObserver实例,这个实例是当LifecycleRegistry 进行事件分发时真正的回调,后面我们在说到事件分发的时候也会提到。
到这里观察者对象就已经被LifecyleRegistry 持有了,那当生命周期发生变化时,LifecycleRegistry 又是如何通知观察者呢?
这里我们要看一下ComponentActivity的onCreate() 方法
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);
//注释1 注入ReportFragment
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
注释1可以看到这里调用了ReportFragment.injectIfNeedIn(this),然后通过FramentManager将ReportFragment 添加到了Activity中
public static void injectIfNeededIn(Activity activity) {
...
// 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();
}
}
那么当Activity 生命周期发生变化时,ReportFragment 的生命周期方法自然会被回调 ,这样就算间接的监听了Activity的生命周期,然后ReportFrament 的各个生命周期中都调用了dispatch() 方法
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);
}
接着看dispatch()
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);
}
}
}
这里判断了Activity 类型,因为Activity 实现了LifecyleOwner, 然后方法来到了LifecyleRegistry 的handleLifecycleEvent()方法
//LifecycleRegistry.java
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
moveToState(event.getTargetState());
}
private void moveToState(State next) {
if (mState == next) {
return;
}
mState = next;
...
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
接着更新当前的状态mState , 然后调用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);
}
Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
这里根据当前状态和第一个和最后一个观察者的状态进行比较,如果当前状态小于第一个观察者状态,则进行状态回退操作; 如果当前状态大于最后一个观察者状态,则执行状态前进操作。
private void forwardPass(LifecycleOwner lifecycleOwner) {
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);
}
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
forwardPass 中将所持有的观察者们进行遍历,然后调用了ObserverWithState 对象的 dispatchEvent()方法
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = event.getTargetState();
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
这里来到了mLifecyceObser.onStateChanged() 方法 ,mLifecycleObserver 是一个LifecycleEventObserver 对象,他是一个接口 ,定义了onStateChange() 方法,他的子类有
GenericLifecyleObserver(已废弃),CompositGeneratedAdapterObserver,FullLifecycleObserverAdapter。mLifeycleObserver 是在构建ObserserWithState 时创建的
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
接着我们看下Lifecycling.lifecycleEventObserver()
static LifecycleEventObserver lifecycleEventObserver(Object object) {
//注释1 举例中MyObserver 集成了DefaultLifecyleObserver, DefaultLifecycleObserver
是FullLifecyleObserver的子类
boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
if (isLifecycleEventObserver && isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
(LifecycleEventObserver) object);
}
if (isFullLifecycleObserver) {
//注释2 将MyObserver实例当做参数构造FullLifecycleObserverAdapter实例
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);
}
这个方法则根据传入的观察者对象类型,返回不同的LifecycleEventObserver对象,注释1在我们前面举例如何使用Lifecycle 时创建的MyObserver 继承了DefaultLifecycleObserver, 而DefaultLifecycleObserver 是FullLifecycleObserver 的子类,所以这里会返回的LifecycleEventObserver实例是FullLifecycleObserverAdapter实例,
可以看到注释2创建实例的时候将原本的Observer 当做了构造参数,这里就来到了FullLifecycleObserverAdapter 实例 的onStateChanged()方法 。
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);
}
终于这里根据不同事件调用了我们创建的观察者MyObserver 的不同方法,到此整个Lifecycle的原理分析结束了。
最后有一点说明的是Lifecycle 现在已经集成到了androidx.core 中,所以不用再单独在build.gradle 中添加依赖,而且随着版本升级,源码也存在了一定的变动,如果有异议,请参考具体的版本。