LifeCycle源码解析

简介

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源码解析_第1张图片

怎么实现的?

首先来了解几个类:

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源码解析_第2张图片

LifecycleRegistry:

这个类是LifeCycle的实现类,在Activity中获取的lifecycle就是获取的这个类的对象,它里面主要维护了一个mState状态,还有mObserverMap变量,用来存储观察者

private State mState;

private FastSafeIterableMap 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 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 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> descendingIterator =
            mObserverMap.descendingIterator();
    while (descendingIterator.hasNext() && !mNewEventOccurred) {
        Map.Entry 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> ascendingIterator =
            mObserverMap.iteratorWithAdditions();
    while (ascendingIterator.hasNext() && !mNewEventOccurred) {
        Map.Entry 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监听应用组件的生命周期,在应用组件生命周期发生变化时,普通组件也能够及时收到通知,组件便能够在其内部管理自己的生命周期,从而降低模块间的耦合度,并降低内存泄漏发生的可能性。

你可能感兴趣的:(Android学习,android,kotlin,开发语言)