/**
- Called when the Activity calls [super.onPause()][Activity.onPause].
*/
override fun onActivityPaused(activity: Activity) {
}
/**
- Called when the Activity calls [super.onStart()][Activity.onStart].
*/
override fun onActivityStarted(activity: Activity) {
}
/**
-
Called when the Activity calls
-
[super.onSaveInstanceState()][Activity.onSaveInstanceState].
*/
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
}
/**
- Called when the Activity calls [super.onStop()][Activity.onStop].
*/
override fun onActivityStopped(activity: Activity) {
}
/**
- Called when the Activity calls [super.onResume()][Activity.onResume].
*/
override fun onActivityResumed(activity: Activity) {
}
}
class MainActivity : AppCompatActivity() {
private val mPresenter = MyPresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//注意这是application的方法
application.registerActivityLifecycleCallbacks(mPresenter)
// api大于等于29支持直接通过activity注册生命回调的方法
// registerActivityLifecycleCallbacks(mPresenter)
}
override fun onDestroy() {
super.onDestroy()
//不需要使用,需要解除注册
application.unregisterActivityLifecycleCallbacks(mPresenter)
}
}
采用这种方式注册后,我们就能在Activity生命周期变化的时候收到回调,从而执行相应的逻辑。因为是同步回调,所以我们要注意不能在回调方法中执行耗时操作,防止出现卡顿。
因为是注册在Application上的,mPresenter对象可以监听到Application的所有Activity的生命周期回调。
而在sdk>=29版本上,Activity也提供了自身的registerActivityLifecycleCallbacks方法,调用Activity这个方法注册的观察者将只会收到注册的Activity生命周期事件的回调。
Application.ActivityLifecycleCallbacks的优点:
通过定义Application.ActivityLifecycleCallbacks接口屏蔽了不同观察者的差异。同时在Activity的各个生命回调方法中分发事件,从根本保障了各个观察者都能在生命周期变化时接收到事件。比较通用,既能用于监听我们自身的Activity生命事件,也能监听第三方Activity事件。
Application.ActivityLifecycleCallbacks缺点:
有了Application.ActivityLifecycleCallbacks,解决了Activity生命周期分发的问题,但它仅适用于Activity的生命周期分发,而Android具有生命周期的对象也不止有Activity(例如Service,Fragment)等。
所以谷歌推出了我们今天的主角 --JetPack之LifeCycle生命周期组件
-
LifecycleObserver接口( Lifecycle观察者) 这是一个空接口,主要起标记作用。依赖注解方法可以被LifeCycle类的addObserver(@NonNull LifecycleObserver observer)方法注册,被注册后就能收到持有LifeCycle的LifeCycleOwner分发生命周期事件。其常见子接口有LifecycleEventObserver和FullLifecycleObserver
-
LifecycleOwner接口(Lifecycle持有者) 需要分发生命周期的对象(如Activity和Fragment)需要实现的接口,该接口只有一个方法,为Lifecycle getLifecycle(),即提供生命周期对象,并需要通过Lifecycle在其生命周期发生变化的时候通知LifecycleObserver
-
Lifecycle(生命周期) 这是一个抽象类,提供了添加移除LifeCycleObserver接口的方法以及记录了当前LifeCycle的生命周期状态
-
State(当前生命周期所处的状态) 是一个枚举类,表示生命周期的各种状态。有DESTROYED,INITIALIZED,CREATED,STARTED,RESUMED这几种取值
-
Event(当前生命周期改变对应的事件) 是一个枚举类,表示生命周期改变对应的事件。有ON_CREATE,ON_START,ON_RESUME,ON_PAUSE,ON_STOP,ON_DESTROY,ON_ANY这几种取值
LifeCycleRegister是LifeCycle的实现类,实现了添加移除LifeCycleObserver的逻辑和生命周期状态管理,并且能够在LifeCycleOwner的生命周期发生变化时及时通知LifeCycleObserver。 有了LifeCycleRegister类,大大简化开发者使用LifeCyclerOwner的成本。使得Activity,Fragment不需要直接和LifeCycleObserver打交道。只需要在生命周期变化时调用LifeCycleRegister的handleLifecycleEvent(@NonNull Lifecycle.Event event) 方法即可。
下面先看它的构造方法:
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
//持有的是LifeCycleOwner对象的弱引用,防止因为LifeCycleRegistery被长生命周期对象持有而
//造成LifeCycleOwner内存泄漏
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
构造方法很简单,只是保存了传入来的LifeCycleOwner对象并且将当前状态置为INITIALIZED
接下来看一下它添加观察者的方法
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//将LifecycleObserver和它的状态封装成ObserverWithState对象
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
//表示statefulObserver已经添加过了,故直接返回
if (previous != null) {
return;
}
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
//lifecycleOwner为null,表示LifecycleOwner已被回收,故不需要观察了,返回
if (lifecycleOwner == null) {
// it is null we should be destroyed. Fallback quickly
return;
}
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
//计算出新加入的observer需要转变到的目标状态
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
//当observer的mState小于目标状态时且observer没有被移除时,向observer分发生命周期事件
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);
}
//为false,代表当前没有在sync()以及没有同时并发添加Observer
//主要为了防止重复调用sync()方法
if (!isReentrance) {
// we do sync only on the top level.
//同步所有观察者状态,使它们保持一致
sync();
}
mAddingObserverCounter–;
}
//返回当前状态的下一个状态
private static Event upEvent(State state) {
switch (state) {
case INITIALIZED:
case DESTROYED:
return ON_CREATE;
case CREATED:
return ON_START;
case STARTED:
return ON_RESUME;
case RESUMED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException("Unexpected state value " + state);
}
从上面的代码分析可以看出当我们在onResume方法中添加Observer,Observer将会连续收到ON_CREATE,ON_START,ON_RESUME事件的回调。
下面看下它分发事件的方法
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
//根据event获取对应的state
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);
}
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) {
Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn’t try dispatch "
- “new events from it.”);
return;
}
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;
}
在backwardPass(lifecycleOwner)和forwardPass(lifecycleOwner)方法调用了ObserverWithState的 dispatchEvent(LifecycleOwner owner, Event event) 方法
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
//把事件通知LifeCycleObsever
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
至此LifeCycleRegister接收事件并把它分发给LifeCycleObserver的流程已经分析完了。
从前面可知,LifeCycleObserver只是一个空接口。它的子接口有LifecycleEventObserver和FullLifecycleObserver,甚至还可以采用注解的方式来声明生命周期回调函数。 那ObserverWithState是如何兼容不同类型的LifeCycleObserver呢?
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
//省略…
}
借用业志陈的从源码看 Jetpack(1)-Lifecycle 源码详解的一段结论
ObserverWithState 将外界传入的 LifecycleObserver 对象传给 Lifecycling 进行类型包装,将反射逻辑和接口回调逻辑都给汇总综合成一个新的 LifecycleEventObserver 对象,从而使得 Event 分发过程都统一为一个入口。
ObserverWithState将复杂的反射逻辑和接口回调处理和类型包装封装到LifeCycling类中,将生成新的 LifecycleEventObserver 对象的过程和LifeCycleRegistry解耦,体现了单一职责。使得LifeCycleRegistry仅需通过onStateChanged 方法就能完成生命周期事件的分发。
static LifecycleEventObserver lifecycleEventObserver(Object object) {
boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
//实现了LifecycleEventObserver接口和FullLifecycleObserver接口
if (isLifecycleEventObserver && isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
(LifecycleEventObserver) object);
}
//只实现了FullLifecycleObserver接口
if (isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
}
//只实现了LifecycleEventObserver接口
if (isLifecycleEventObserver) {
return (LifecycleEventObserver) object;
}
尾声
以薪资待遇为基础,以发展为最终目标,要在高薪资的地方,谋求最好的发展!
下面是有几位Android行业大佬对应上方技术点整理的一些进阶资料。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门,即可获取!
FullLifecycleObserverAdapter((FullLifecycleObserver) object,
(LifecycleEventObserver) object);
}
//只实现了FullLifecycleObserver接口
if (isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
}
//只实现了LifecycleEventObserver接口
if (isLifecycleEventObserver) {
return (LifecycleEventObserver) object;
}
尾声
以薪资待遇为基础,以发展为最终目标,要在高薪资的地方,谋求最好的发展!
下面是有几位Android行业大佬对应上方技术点整理的一些进阶资料。
[外链图片转存中…(img-EHm8LVlt-1715782215184)]
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门,即可获取!