JetPack组件--LifeCycle生命周期组件详解

//doSomething

}

}

class MainActivity : AppCompatActivity() {

private val mPresenter = MyPresenter()

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

mPresenter.start()

}

override fun onDestroy() {

super.onDestroy()

mPresenter.stop()

}

}

这种写法虽然能满足我们自己页面分发生命周期的需求,但需要手动调用,就往往可能出现忘记调用,导致bug出现。

而且当Activity是第三方页面,就无法使用这种方式进行生命周期进行分发了。

2,Application.ActivityLifecycleCallbacks

在LifeCycle出现之前,Android系统提供了Application.ActivityLifecycleCallbacks这样接口让我们能够感知应用内所有的Activity生命周期的变化,具体用法如下:

class MyPresenter: Application.ActivityLifecycleCallbacks {

/**

  • Called when the Activity calls [super.onCreate()][Activity.onCreate].

*/

override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {

// dosomething

}

/**

  • Called when the Activity calls [super.onDestroy()][Activity.onDestroy].

*/

override fun onActivityDestroyed(activity: Activity) {

// dosomething

}

/**

  • 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生命周期组件

LifeCycle组件常见类简介


  • LifecycleObserver接口( Lifecycle观察者) 这是一个空接口,主要起标记作用。依赖注解方法可以被LifeCycle类的addObserver(@NonNull LifecycleObserver observer)方法注册,被注册后就能收到持有LifeCycle的LifeCycleOwner分发生命周期事件。其常见子接口有LifecycleEventObserverFullLifecycleObserver

  • 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这几种取值

LifecycleRegistry主要源码解析


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的流程已经分析完了。

文末

面试:如果不准备充分的面试,完全是浪费时间,更是对自己的不负责!

不管怎么样,不论是什么样的大小面试,要想不被面试官虐的不要不要的,只有刷爆面试题题做好全面的准备,当然除了这个还需要在平时把自己的基础打扎实,这样不论面试官怎么样一个知识点里往死里凿,你也能应付如流啊

《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值