简介

Lifecycle是Jetpack中的一个生命周期组件,可用来感知其他组件(如Activity,Fragment)生命周期的改变,从而可以保证咱们的一些代码操作控制在合理的生命周期内;

如何运用?

增加以下依靠

implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.0")

LifeCycle有两个中心类,一个是LifeCycleOwner,完成了LifeCycleOwner的类可以作为一个生命周期的被观察者,ComponentActivity(Activity通过承继ComponentActivity完成该接口)和Fragment都完成了该接口,该接口只要一个办法getLifeCycle();另一个LifeCycleObserver,望文生义这是一个生命周期观察者,完成了这个接口的类就可以感知到Activity的生命周期了。

自定义观察者,这儿的DefaultLifecleObserver承继自FullLifecycleObserver,FullLifecycleObserver承继自LifeCycleObserver

class LifeObserver: DefaultLifecycleObserver {
    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        Log.d(TAG, "onCreate")
    }
    override fun onStart(owner: LifecycleOwner) {
        Log.d(TAG, "onStart")
        super.onStart(owner)
    }
    override fun onResume(owner: LifecycleOwner) {
        Log.d(TAG, "onResume")
        super.onResume(owner)
    }
    override fun onPause(owner: LifecycleOwner) {
        Log.d(TAG, "onPause")
        super.onPause(owner)
    }
    override fun onStop(owner: LifecycleOwner) {
        Log.d(TAG, "onStop")
        super.onStop(owner)
    }
    override fun onDestroy(owner: LifecycleOwner) {
        Log.d(TAG, "onDestroy")
        super.onDestroy(owner)
    }
    companion object {
        private const val TAG = "LifeCycle";
    }
}

创立一个AppCompatActivity作为被观察者

class MainActivity : AppCompatActivity() {
   //创立一个生命周期观察者
    private val lifeObserver by lazy {
        LifeObserver()
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        Log.d(TAG, "Activity onCreate")
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //与观察者绑定
        lifecycle.addObserver(lifeObserver)
    }
    override fun onStart() {
        Log.d(TAG, "Activity onStart")
        super.onStart()
    }
    override fun onResume() {
        Log.d(TAG, "Activity onResume")
        super.onResume()
    }
    override fun onPause() {
        Log.d(TAG, "Activity onPause")
        super.onPause()
    }
    override fun onStop() {
        Log.d(TAG, "Activity onStop")
        super.onStop()
    }
    override fun onDestroy() {
        Log.d(TAG, "Activity onDestroy")
        super.onDestroy()
    }
    companion object {
        private const val TAG = "LifeCycle"
    }
}

当发动Activity时,在日志中可以看到,Activity生命周期改变时,在LifeObserver中也成功的感知到了生命周期周期的改变

Lifecycle

怎样完成的?

首要来了解几个类:

State:

这是Lifecycle的一个枚举类,里边保护了五个状况DESTORYEDINITALIZEDCREATEDSTARTEDRESUME在状况分发时用的比较多,和Event配合运用

public enum State {
    DESTROYED,
    INITIALIZED,
    CREATED,
    STARTED,
    RESUMED;
}

Event:

它也是Lifecycle的一个内部枚举类,对应 Activity 的各个生命周期产生事件

public enum Event {
    ON_CREATE,
    ON_START,
    ON_RESUME,
    ON_PAUSE,
    ON_STOP,
    ON_DESTROY,
    ON_ANY;
   //在往不行见的方向上,依据state获取生命周期状况,对应下面的状况图,CREATE状况对应Activity下一个生
   命周期为onDestroy, STARTED状况对应的下一个生命周期为onStop, RESUMED状况对应的下一个为onPause
    @Nullable
    public static Event downFrom(@NonNull State state) { 
        switch (state) {
            case CREATED:
                return ON_DESTROY;
            case STARTED:
                return ON_STOP;
            case RESUMED:
                return ON_PAUSE;
            default:
                return null;
        }
    }
    //在可见的方向上来看,INITIALIZED状况下一个生命周期为onCreate,CREATE状况的下一个为
    onStart,START状况对应的下一个为onResume;
    @Nullable
    public static Event upFrom(@NonNull State state) {
        switch (state) {
            case INITIALIZED:
                return ON_CREATE;
            case CREATED:
                return ON_START;
            case STARTED:
                return ON_RESUME;
            default:
                return null;
        }
    }
   //依据当时生命周期Event, 获取方针State 这儿保护了一个状况机,体现了页面正在可见和正在不行见的两种趋势 如下图
    @NonNull
    public State getTargetState() {
        switch (this) {
            case ON_CREATE:
            case ON_STOP:
                return State.CREATED;
            case ON_START:
            case ON_PAUSE:
                return State.STARTED;
            case ON_RESUME:
                return State.RESUMED;
            case ON_DESTROY:
                return State.DESTROYED;
            case ON_ANY:
                break;
        }
        throw new IllegalArgumentException(this + " has no target state");
    }
}

Lifecycle

LifecycleRegistry:

这个类是LifeCycle的完成类,在Activity中获取的lifecycle便是获取的这个类的方针,它里边首要保护了一个mState状况,还有mObserverMap变量,用来存储观察者

private State mState;

private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>();

private LifecycleRegistry(@NonNull LifecycleOwner provider, boolean enforceMainThread) {
    mLifecycleOwner = new WeakReference<>(provider);//持有宿主的弱引用
    mState = INITIALIZED;
    mEnforceMainThread = enforceMainThread;
}

ObserverWithState:

这个类便是在map中存储的value类型,它是由增加的observer与observer的初始state封装而成

ObserverWithState(LifecycleObserver observer, State initialState) {
    mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
    mState = initialState;
}
static LifecycleEventObserver lifecycleEventObserver(Object object) {
    boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
    //mLifecycleObserver属于FullLifecycleObserver类
    boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
    if (isLifecycleEventObserver && isFullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
                (LifecycleEventObserver) object);
    }
    if (isFullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
    }
    ....
FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,
        LifecycleEventObserver lifecycleEventObserver) {
    mFullLifecycleObserver = fullLifecycleObserver;
    mLifecycleEventObserver = lifecycleEventObserver;
}

所以终究在mObserverMap中以注册的obsever为key,ObserverWithState为value, 在ObserverWithState中 又把observer以FullLifecycleObserver类型赋值给FullLifecycleObserverAdapter方针的mFullLifecycleObserver,终究把这个FullLifecycleObserverAdapter方针赋值给了ObserverWithState的mLifecycleObserver

了解完上述类之后,咱们来看看lifecycle到底是怎样工作的?

查看ComponentActivity的getLifeCycle()

private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
...
public Lifecycle getLifecycle() {
    return mLifecycleRegistry;
}

回来的是一个LifeCycleRegistry方针,这个LifeCycleRegistry上面提到过,承继自LifeCycle,在他的构造办法中会将Acitivity的弱引用赋值给mLifecycleOwner,而且初始化当时的状况机mState为INITIALIZED

所以当咱们在activity中调用addOnserver()办法时实践调用的是LifeCycleRegistry中的办法,咱们来看看addObserver()里边干了什么

@Override
public void addObserver(@NonNull LifecycleObserver observer) {
    enforceMainThreadIfNeeded("addObserver");
    //mState代表当时宿主的状况,假如当时状况为DESTROYED,则给观察者的状况也赋值为  
    DESTROYED,后边就不再分产生命周期了,不然观察者的状况都赋值为INITIALIZED,
    这样做的原因是,假如在onResume时注册观察者,假如直接赋ONRESUME状况,后边做事件同步时就
    丢掉了ONCREATE,ONSTART事件
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
    //将initialState,和observer封装成ObserverWithState方针,这个方针结构上面讲过
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    //observer作为key,方才封装的方针作为value存储到map中,假如map中现已存在,则回来map中存储的值,不然回来null,这个mObserverMap的key是一个链表的结构,记载了链表的start节点和end节点;它的value是一个双向链表的结构,每个value值记载着它的上一个节点和下一个节点
    ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
    if (previous != null) {
        return;
    }
    //mLifecycleOwner便是当时宿主的弱引用,若为空,阐明该类现已被开释,则直接回来
    LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        // it is null we should be destroyed. Fallback quickly
        return;
    }
    boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
    //核算出方针状况,怎样核算后边会说
    State targetState = calculateTargetState(observer);
    mAddingObserverCounter++;
    //循环遍历,这个循环首要做的事情便是避免在running(onStart,onResume)状况刺进观察者时,使之前的
    一些生命周期没有分发给这个oberver
    while ((statefulObserver.mState.compareTo(targetState) < 0
            && mObserverMap.contains(observer))) {
        //记载刺进的状况,这儿详细完成是里边有一个mParentStates.add(mState)。 mParentStates是一个ArrayList
        ,用于存储一些旧的状况,这儿mParentStates存储的是INITALIZED
        pushParentState(statefulObserver.mState);  
       //传入的参数是:INITIALIZED,从upFrom中取出的下一次的Event是“ON_CREATE”
        final Event event = Event.upFrom(statefulObserver.mState);
        if (event == null) {
            throw new IllegalStateException("no event up from " + statefulObserver.mState);
        }
     //走完这代码,statefulObserver.mState就变成了CREATED
        statefulObserver.dispatchEvent(lifecycleOwner, event);
        //与pushParentState对应,mParentStates.remove;此时mParentStates的size为0
        popParentState();
        targetState = calculateTargetState(observer);
    }
    if (!isReentrance) {
        // we do sync only on the top level.
        sync();
    }
    mAddingObserverCounter--;
}

核算方针状况

private State calculateTargetState(LifecycleObserver observer) {
   //获取到上一个存储的observer
    Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);
    //拿到上一个存储的observer的状况
    State siblingState = previous != null ? previous.getValue().mState : null;
    // mParentStates 列表不为空时,将最近增加的 state 值赋给 parentState
    //mParentStates有值的情况下代表正在同步状况
    State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)
            : null;
    //最近正在增加的state, 宿主当时的状况,以及上一个增加的observer的状况取最小值
    return min(min(mState, siblingState), parentState);
}

生命周期状况分发

AppcompatActivity.onCreate()

注册了一个空白的Fragment,通过fragment来出产生命周期状况分发
ReportFragment.injectIfNeededIn(this);
public static void injectIfNeededIn(Activity 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();
    }
}

在ReportFragment的生命周期办法中去完成分发以OnStart为例

@Override
public void onStart() {
    super.onStart();
    dispatchStart(mProcessListener);
    dispatch(Lifecycle.Event.ON_START);
}

在每个生命周期办法中都会调用dispatch办法去分发状况,而在dispatch中又调用了LifecycleRegistry的handleLifecycleEvent

if (activity instanceof LifecycleOwner) {
    Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
    if (lifecycle instanceof LifecycleRegistry) {
        ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
    }
}
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    enforceMainThreadIfNeeded("handleLifecycleEvent");
     //event.getTargetState获取当时的状况,当时Event是onStart,对应的State为STARTED
    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;
}

获取到当时的状况之后,通过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.");
    }
    //当map中最早同步的state与最后同步的state一致,而且state为最新的状况时停止同步
    while (!isSynced()) {
        mNewEventOccurred = false;
        // no need to check eldest for nullability, because isSynced does it for us.
        //这儿将当时状况和map中存储的状况进行比较,小于0阐明流程是向着正在不行见方向开展
       比方当时状况是STARTED,上一次状况为RESUME,判断成果小于0,阐明正在不行见
        if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
            backwardPass(lifecycleOwner); 
        }
        Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
        //大于0阐明流程是向着可见方向开展
        if (!mNewEventOccurred && newest != null
                && mState.compareTo(newest.getValue().mState) > 0) {
            forwardPass(lifecycleOwner);
        }
    }
    mNewEventOccurred = false;
}

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);  //依据之前的state获取生命周期状况(往不行见的方向)
            if (event == null) {
                throw new IllegalStateException("no event down from " + observer.mState);
            }
            pushParentState(event.getTargetState());
            observer.dispatchEvent(lifecycleOwner, event); //分产生命周期
            popParentState();
        }
    }
}

对应上图的状况图,在往不行见的方向上,CREATE状况对应Activity下一个生命周期为onDestroy, STARTED状况对应的下一个生命周期为onStop, RESUMED状况对应的下一个为onPause

public static Event downFrom(@NonNull State state) {
    switch (state) {
        case CREATED:
            return ON_DESTROY;
        case STARTED:
            return ON_STOP;
        case RESUMED:
            return ON_PAUSE;
        default:
            return null;
    }
}

再来看看往可见的方向的分发forwardPass


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);  //在可见的方向上获取下一个生命周期Event
            if (event == null) {
                throw new IllegalStateException("no event up from " + observer.mState);
            }
            observer.dispatchEvent(lifecycleOwner, event); //分发
            popParentState();
        }
    }
}

同样对应状况图,在可见的方向上来看,INITIALIZED状况下一个生命周期为onCreate,CREATE状况的下一个为onStart,START状况对应的下一个为onResume;

public static Event upFrom(@NonNull State state) {
    switch (state) {
        case INITIALIZED:
            return ON_CREATE;
        case CREATED:
            return ON_START;
        case STARTED:
            return ON_RESUME;
        default:
            return null;
    }
}

获取到对应的生命周期Event之后就开端分发啦,observer.dispatchEvent(lifecycleOwner, event)这儿的observer是ObserverWithState方针,也便是在addObserver时,将observer与State封装而成的方针,lifecycleOwner参数便是咱们的Activity

void dispatchEvent(LifecycleOwner owner, Event event) {
    State newState = event.getTargetState();
    mState = min(mState, newState);
    //mLifecycleObserver便是一开端提到的FullLifecycleObserverAdapter方针,它里边有一个mFullLifecycleObserver(也便是咱们自己增加的observer)
    mLifecycleObserver.onStateChanged(owner, event); 
    mState = newState;
}

看一下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);
    }
}

mLifecycleObserver的onStateChange便是依据event去调用咱们自定义的observer的生命周期办法,至此LifeCycle的整个工作流程也就分析完了

总结

普通组件在运用过程中一般需求依靠于系统组件(Activity/Fragment/LifecycleService)的生命周期,导致系统组件的生命周期回调办法过于臃肿。例如一般在onCreate()中对组件进行初始化,在onPause()中停止组件,在onDestroy()中对组件进行资源回收等。 运用LifeCycle监听使用组件的生命周期,在使用组件生命周期产生改变时,普通组件也可以及时收到告诉,组件便可以在其内部管理自己的生命周期,从而下降模块间的耦合度,并下降内存走漏产生的可能性。