为什么要用Lifecyle
Android开发中,咱们经常需求在功用组件中感知到对应宿主(Activity,Fragment)的生命周期的改变,例如当Activity可见时,在presenter目标中改写数据,毁掉时释放某些资源等等
Lifecycle出来之前,咱们一般都用最粗暴的办法,在Activity中手动把在每个生命周期回调分发到功用组件(例如逻辑层presenter)中
但是这种办法存在一些问题,首先代码会显得很臃肿不高雅,每个地方都需求手动处理,多人维护不免出现遗失
别的还存在一个逻辑上的隐患,假定在onCreate中去敞开运用某个资源,对应在onStop中咱们需求去释放这个资源,但是onCreate中的操作是个耗时操作,就会存在onStop现已回调完成后,onCreate中的办法却又去敞开了这个资源,这种状况这个资源就得不到释放了,会引起内存走漏
基于这些问题,google为咱们供给了Lifecyle,能够简化功用组件感知生命周期的进程,经过观察者形式,主动分发对应生命周期事情
Lifecycle的运用
增加依靠
// 非Androidx 项目
implementation "android.arch.lifecycle:extensions:1.1.1"
// Androidx 项目
implementation 'androidx.appcompat:appcompat:1.4.1'
假如项目还没迁移到AndroidX,建议尽早迁移
运用
分两大步骤
- 把功用组件包装为生命周期观察者
- 把观察者与生命周期组件绑定
界说观察者
运用Lifecycle供给的两个接口DefaultLifecycleObserver
和LifecycleEventObserver
,让功用组件具有感知生命周期的才能
DefaultLifecycleObserver
供给了onCreate~OnDestroy各个生命周期的回调办法,并供给了默许完成,按需重写
LifecycleEventObserver
只供给了一个onStateChanged接口,可根据传入的参数判断当时所在的生命周期状况
旧版本的Lifecycle运用的是
LifecycleObserver
接口,然后在功用组件中经过注解的办法去增加各个生命周期的回调逻辑,这种运用起来很费事,目前现已声明为抛弃了
class MyLifecycleObserver : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
Log.i(TAG, "onCreate")
}
override fun onResume(owner: LifecycleOwner) {
Log.i(TAG, "onResume")
}
override fun onPause(owner: LifecycleOwner) {
Log.i(TAG, "onPause")
}
override fun onDestroy(owner: LifecycleOwner) {
Log.i(TAG, "onDestroy")
}
companion object {
const val TAG = "MyLifecycleObserver"
}
}
这样这个MyLifecycleObserver就具有了感知生命周期的才能,当他跟对应生命周期宿主绑定之后,就能在对应接口中收到回调
观察者和生命周期绑定
绑定的进程可了解为给生命周期宿主(Activity等)增加观察者的进程,运用LifecycleOwner接口的getLifecycle函数,获取到当时宿主的Lifecycle目标,经过这个Lifecycle目标的addObserver办法,就能把生命周期组件和功用组件相关起来,树立观察关系,AppCompatActivity已完成了LifecycleOwner(父类ComponentActivity
完成的)
class LifecycleActivity : AppCompatActivity() {
private val mBinding by lazy {
ActivityLifecycleBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle/?) {
super.onCreate(savedInstanceState)
Log.i(TAG, "activity onCreate")
setContentView(mBinding.root)
lifecycle.addObserver(MyLifecycleObserver())
}
override fun onResume() {
super.onResume()
Log.i(TAG, "activity onResume")
}
override fun onPause() {
super.onPause()
Log.i(TAG, "activity onResume")
}
override fun onDestroy() {
super.onDestroy()
Log.i(TAG, "activity onDestroy")
}
companion object {
const val TAG = "LifecycleActivity"
}
}
运行结果
I/LifecycleActivity: activity onCreate
I/MyLifecycleObserver: onCreate
I/LifecycleActivity: activity onResume
I/MyLifecycleObserver: onResume
I/MyLifecycleObserver: onPause
I/LifecycleActivity: activity onPause
I/MyLifecycleObserver: onDestroy
I/LifecycleActivity: activity onDestroy
能够看到MyLifecycleObserver
和Activity的生命周期回调保持了同步,不过仔细的童鞋或许现已注意到这儿有一个点很有意思,在OnResume之前,都是Activity中的日志先打印,然后才打印Observer中的日志,而在OnResume之后,却是observer中的先履行,这是为啥勒?看图(这个图很关键)
图中states
是Lifecycle为生命周期界说的5中状况INITIALIZED,DESTROYED,CREATED,STARTED,RESUMED
以RESUMED状况为例,ON_RESUME
即代表onResume办法的回调履行,这个办法履行完成之后,Activity才进入到了RESUMED状况,而关于ON_PAUSE,也便是onPause刚开始履行的时分还是在Resumed态,履行后就进入了STARTED状况。
所以对应便是onResumed履行之后,lifecycle才会分发对应的ON_RESUME事情到observer中,而onPause刚开始履行,就会把ON_PAUSE事情分发到observer中,这样做的好处是当observer收到对应的事情时,对应Activity所在的生命周期状况是准确的
Lifecyle原理
从两个角度进行剖析
- 观察者跟生命周期组件怎么树立绑定
- 生命周期事情怎么回调到观察者
注册观察者
观察者跟生命周期组件怎么树立绑定,也便是看看addObserver的背面都干了什么,上面的比如中,咱们在addObserver的时分,是先调用了getLifecycle函数,跟一下这个函数,发现是一个接口LifecycleOwner供给的,而Activity完成了这个接口
LifecyclerOwner
一个非常简略的接口,只供给了一个函数,getLifecycle,回来一个Lifecycle目标,而Lifecycle类是Lifecycle库的核心,用于把生命周期分发出去,这儿接口和类的姓名就很好了解,LifecycleOwner表明生命周期一切者
public interface LifecycleOwner {
/**
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
所以具有生命周期的类都能够去完成这个接口,在AndroidX内已有三个类完成了LifecycleOwner接口,分别是Activity,Fragment,以及ProcessLifecycleOwner
,ProcessLifecycleOwner
用于监听应用的生命周期,包含前后台切换,不过需求额外引入依靠
implementation "androidx.lifecycle:lifecycle-process:$lifecycle"
Lifecycle Lifecycle是一个抽象类,界说了一个具有生命周期的目标
这个类主要界说了两个枚举类,Event
和State
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY;
}
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
}
Event表明会分发给其他组件的生命周期事情,ON_ANY表明恣意事情都会触发
State表明当时生命周期一切者所在的状况,跟上面提到的那张图是对应上的
不知道大家会不会有疑问,为什么要搞出这两个值,直接分发详细的event事情不就够了?不香么?这儿留个疑问,后边会讲到
别的还有两个抽象办法addObserver和removeObserver
// 增加观察者
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
// 移除观察者
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
LifecycleRegistry Lifecycle的完成类,负责增加观察者,分发生命周期事情给观察者,看看addObserver的逻辑
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
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;
}
// 省掉部分代码
}
这儿省掉了一些逻辑,看要点,很显然把observer放到了一个mObserverMap傍边,实际上这个不是真正意义上的Map,而是一个自界说的可在遍历进程中增删observer的数据结构,此处先不深凿了,注意这儿把增加进来的Observer目标包装到了一个ObserverWithState目标中,注意这个目标,后边会用到
事情怎么分发
那么到底是怎么感知到Activity等组件的生命周期的改变,并分发给一切observer的了?
直接看看ComponentActivity的源码
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
getLifecycle回来了一个LifecycleRegistry
目标,再看看onCreate回调
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
但是并没有看到LifecycleRegistry目标,不过这个ReportFragment是lifecycle库下的类,那跟他必定有点儿关系了,点进去看看
public class ReportFragment extends android.app.Fragment {
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
// On API 29+, we can register for the correct Lifecycle callbacks directly
LifecycleCallbacks.registerIn(activity);
}
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);
}
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);
}
}
}
}
公然,这不就跟glide感知生命周期的做法一样,用了一个没有界面的Fragment,经过fragment感知宿主Activity的生命周期改变,然后分发出去
感知到生命周期的改变之后,会把对应生命周期事情的event经过LifecycleRegistry的handleLifecycleEvent分发出去,再跟下这块儿代码
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;
}
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;
}
经过Event的getTargetState()
获取到到当时的生命周期状况State值,然后就预备向observer分发当时的生命周期状况,这儿会把当时所拿到的最新State状况和Observer目前的State状况进行比较,假如最新状况比Observer的状况要小,这儿小需求看枚举的比较,界说在前面的比界说在后边的小,这儿要对照state状况和那张图一起看就很好了解
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
}
假定旧的状况是RESUMED,而最新的是STARTED,这时就表明新的状况比旧的状况要小,就会走到backwardPass函数里边,反之则会走到forwardPass
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();
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进行了遍历,把当时遍历到的observer对应state取出来,经过Event.downFrom计算出需求分发的事情,最终经过dispatchEvent分发出去
所以前面抛出的那个问题,为什么需求state和event,这儿看到他的妙处了吧,因为不是每一个observer都是处于同一状况的,因为有或许observer的状况还没更新完,新的事情又来了,这样就会重新遍历,所以会出现有的observer的状况更最新的状况之间不是连续的,这样经过最新的State值和当时的State值,就能够把这之间的一切生命周期事情都回调一遍,不然有的生命周期事情就或许错过了,那写在里边的逻辑永久得不到履行,当然addObserver的时分,也是运用这个,让刚新注册的observer,能把注册之前走过的一切生命周期事情都走一遍,所以这是一种粘性事情
再看看addObserver的这部分代码,经过while循环,把之前的一切事情都分发了一遍
public void addObserver(@NonNull LifecycleObserver observer) {
//省掉部分代码
mAddingObserverCounter++;
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--;
}
再来看看dispatchEvent
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = event.getTargetState();
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
很简略,调用了LifecycleEventObserver的onStateChanged
办法分发了出去,不过咱们前面说过,咱们一般还会运用完成DefaultLifecycleObserver的办法,这种是怎么回调到的?
咱们能够看到DefaultLifecycleObserver
是承继FullLifecycleObserver
的,而LifecycleEventObserver有一个完成类FullLifecycleObserverAdapter
@Override
public void onStateChanged(LifecycleOwner source, 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);
}
}
看到这很容易猜想到,DefaultLifecycleObserver的完成类,会被包装到这儿面,然后分发
还记得之前提到的,在addObserver的时分,会把增加进来的observer目标包装到ObserverWithState
中么,看看这个类的结构函数
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
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);
}
// 省掉部分代码
}
公然 ,在这儿,经过Lifecycling,把add进来的observer包装到了FullLifecycleObserverAdapter中,并把FullLifecycleObserverAdapter目标回来赋值给了ObserverWithState
目标的mLifecycleObserver
属性,所以最终dispatchEvent
中调用的的mLifecycleObserver.onStateChanged(owner, event)
就经过Adapter回调给了对应的observer的函数
到这儿,从绑定observer到回调生命周期的流程就走通了