美文网首页
Android-Lifecycle分析笔记

Android-Lifecycle分析笔记

作者: waitingal | 来源:发表于2023-09-13 13:36 被阅读0次

# **1.类职责说明**

**Lifecycle**:抽象类,定义了Event 生命周期事件 和 State 生命周期状态 的值,并提供observer的add/remove

**Event**:每个生命周期改变对应的事件

**State**:生命周期所处的状态

        INITIALIZED---初始化状态

        CREATED---onCreate()调用之后,onStop()调用之前的状态

        STARTED---onStart()调用之后,onPause()调用之前的状态

        RESUMED---onResume()时的状态

        DESTROYED---onDestory()调用时的状态

**LifecycleOwner**:接口,只有一个getLifecycle()方法,返回是一个Lifecycle对象,即向外提供一个具体生命周期的宿主

**LifecycleRegistry**:继承Lifecycle,主要是管理observer,以及将LifecycleOwner的生命周期变化事件派发给每个observer

**LifecycleObserver**:观察者,接受来自LifecycleOwner的生命周期变化事件,其主要子类有LifecycleEventObserver 和 FullLifecycleObserver

简单说流程就是LifecycleOwner的生命周期发生变化时,会告知LifecycleRegistry,LifecycleRegistry再将事件传递给每一个LifecycleObserver.

# 2.具体分析

## LifecycleOwner

所有的事件来源于LifecycleOwner,那就从源头出发.

### Fragment

androidx.fragment.app.Fragment

```

public class Fragment implements LifecycleOwner{

    int mState = INITIALIZING;

    LifecycleRegistry mLifecycleRegistry;

    public Fragment() {

        initLifecycle();

    }

    private void initLifecycle() {

        mLifecycleRegistry = new LifecycleRegistry(this);

        ....

    }

    @NonNull

    public Lifecycle getLifecycle() {

        return mLifecycleRegistry;

    }

    void performCreate(Bundle savedInstanceState) {

        onCreate(savedInstanceState);

        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);

}

  void performStart() {

        onStart();

        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);

}

  void performResume() {

        onResume();

        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);

  }

    void performPause() {

        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);

        onPause();

    }

    void performStop() {

        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);

        onStop();

    }

    void performDestroy() {

        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);

        onDestroy();

    }

}

```

在每个生命周期方法前的performxxx()里都告知LifecycleRegistry,生命周期有变化了,至于怎么处理就交给LifecycleRegistry。

(注意Create -> Start -> Resume 是先执行onxxx,再LifecycleRegistry.handleLifecycleEvent,

  Pause -> Stop - > Destroy 则是反过来)

### Activity

androidx.core.app.ComponentActivity

``````

public class ComponentActivity extends Activity implements LifecycleOwner{

        private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

        @Override

        protected void onCreate(@Nullable Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            ReportFragment.injectIfNeededIn(this);

        }

        @NonNull

        @Override

        public Lifecycle getLifecycle() {

            return mLifecycleRegistry;

        }

}

``````

Activity里没有直接使用LifecycleRegistry,而是实例化了一个ReportFragment。

ReportFragment

```public class ReportFragment extends android.app.Fragment {

public static void injectIfNeededIn(Activity activity) {

        if (Build.VERSION.SDK_INT >= 29) {

            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();

            manager.executePendingTransactions();

        }

    }

    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);

            }

        }

    }

    private void dispatch(@NonNull Lifecycle.Event event) {

        if (Build.VERSION.SDK_INT < 29) {

            dispatch(getActivity(), event);

        }

    }

    @Override

    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);

        dispatch(Lifecycle.Event.ON_CREATE);

    }

    @Override

    public void onStart() {

        super.onStart();

        dispatch(Lifecycle.Event.ON_START);

    }

    @Override

    public void onResume() {

        super.onResume();

        dispatch(Lifecycle.Event.ON_RESUME);

    }

    @Override

    public void onPause() {

        super.onPause();

        dispatch(Lifecycle.Event.ON_PAUSE);

    }

    @Override

    public void onStop() {

        super.onStop();

        dispatch(Lifecycle.Event.ON_STOP);

    }

    @Override

    public void onDestroy() {

        super.onDestroy();

        dispatch(Lifecycle.Event.ON_DESTROY);

    }

    @RequiresApi(29)

    static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {

        static void registerIn(Activity activity) {

            activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());

        }

        @Override

        public void onActivityCreated(@NonNull Activity activity,

                @Nullable Bundle bundle) {

        }

        @Override

        public void onActivityPostCreated(@NonNull Activity activity,

                @Nullable Bundle savedInstanceState) {

            dispatch(activity, Lifecycle.Event.ON_CREATE);

        }

        @Override

        public void onActivityStarted(@NonNull Activity activity) {

        }

        @Override

        public void onActivityPostStarted(@NonNull Activity activity) {

            dispatch(activity, Lifecycle.Event.ON_START);

        }

        @Override

        public void onActivityResumed(@NonNull Activity activity) {

        }

        @Override

        public void onActivityPostResumed(@NonNull Activity activity) {

            dispatch(activity, Lifecycle.Event.ON_RESUME);

        }

        @Override

        public void onActivityPrePaused(@NonNull Activity activity) {

            dispatch(activity, Lifecycle.Event.ON_PAUSE);

        }

        @Override

        public void onActivityPaused(@NonNull Activity activity) {

        }

        @Override

        public void onActivityPreStopped(@NonNull Activity activity) {

            dispatch(activity, Lifecycle.Event.ON_STOP);

        }

        @Override

        public void onActivityStopped(@NonNull Activity activity) {

        }

        @Override

        public void onActivitySaveInstanceState(@NonNull Activity activity,

                @NonNull Bundle bundle) {

        }

        @Override

        public void onActivityPreDestroyed(@NonNull Activity activity) {

            dispatch(activity, Lifecycle.Event.ON_DESTROY);

        }

        @Override

        public void onActivityDestroyed(@NonNull Activity activity) {

        }

    }

}

```

这里有个api版本判断,<29的 Activity会实例化ReportFragment,使用ReportFragment的生命周期变化  来告知LifecycleRegistry。

至于>=29的,使用LifecycleCallbacks.registerIn给activity注册一个LifecycleCallbacks回调,在回调的生命周期方法里将activity和Event传给dispatch方法,dispatch方法里依然使用LifecycleRegistry.handleLifecycleEvent进行处理。

那activity是怎样回调到LifecycleCallbacks?

以下是api=30的Activity简化的源码

android.app.Activity

```

public class Activity{

    private final ArrayList<Application.ActivityLifecycleCallbacks> mActivityLifecycleCallbacks =

            new ArrayList<Application.ActivityLifecycleCallbacks>();

    public void registerActivityLifecycleCallbacks(

            @NonNull Application.ActivityLifecycleCallbacks callback) {

        synchronized (mActivityLifecycleCallbacks) {

            mActivityLifecycleCallbacks.add(callback);

        }

    }           

    public void unregisterActivityLifecycleCallbacks(

            @NonNull Application.ActivityLifecycleCallbacks callback) {

        synchronized (mActivityLifecycleCallbacks) {

            mActivityLifecycleCallbacks.remove(callback);

        }

    }

    private Object[] collectActivityLifecycleCallbacks() {

        Object[] callbacks = null;

        synchronized (mActivityLifecycleCallbacks) {

            if (mActivityLifecycleCallbacks.size() > 0) {

                callbacks = mActivityLifecycleCallbacks.toArray();

            }

        }

        return callbacks;

    }

    final void performCreate(Bundle icicle, PersistableBundle persistentState) {

        dispatchActivityPreCreated(icicle);

        if (persistentState != null) {

            onCreate(icicle, persistentState);

        } else {

            onCreate(icicle);

        }

        dispatchActivityPostCreated(icicle);

    }

    protected void onCreate(@Nullable Bundle savedInstanceState) {

        dispatchActivityCreated(savedInstanceState);

    }

    private void dispatchActivityPreCreated(@Nullable Bundle savedInstanceState) {

        getApplication().dispatchActivityPreCreated(this, savedInstanceState);

        Object[] callbacks = collectActivityLifecycleCallbacks();

        if (callbacks != null) {

            for (int i = 0; i < callbacks.length; i++) {

                ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPreCreated(this,

                        savedInstanceState);

            }

        }

    }

    private void dispatchActivityCreated(@Nullable Bundle savedInstanceState) {

        getApplication().dispatchActivityCreated(this, savedInstanceState);

        Object[] callbacks = collectActivityLifecycleCallbacks();

        if (callbacks != null) {

            for (int i = 0; i < callbacks.length; i++) {

                ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityCreated(this,

                        savedInstanceState);

            }

        }

    }

    private void dispatchActivityPostCreated(@Nullable Bundle savedInstanceState) {

        Object[] callbacks = collectActivityLifecycleCallbacks();

        if (callbacks != null) {

            for (int i = 0; i < callbacks.length; i++) {

                ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPostCreated(this,

                        savedInstanceState);

            }

        }

        getApplication().dispatchActivityPostCreated(this, savedInstanceState);

    }

}

```

以上只列出Created,其他的生命周期相关代码也是如此.

使用mActivityLifecycleCallbacks记录观察者,

performCreate 执行onCreate前通知观察者 -> mActivityLifecycleCallbacks.onActivityPreCreated

onCreate 通知观察者正在执行onCreate -> mActivityLifecycleCallbacks.onActivityCreated

通知观察者onCreate完成-> mActivityLifecycleCallbacks.onActivityPostCreated

### LifecycleOwner总结:

**Fragment**:在生命周期中直接使用LifecycleRegistry进行分发通知

**api<29的Activity**:实例化一个不可见的Fragment,用该Fragment的生命周期方法来使用  mLifecycleRegistry进行分发通知

**api>=29的Activity**:在生命周期中先使用LifecycleCallbacks回调,LifecycleCallbacks再使用LifecycleRegistry进行分发通知

## LifecycleRegistry

用于注册观察者,将生命周期事件分发给观察者.

### addObserver

```

public void addObserver(@NonNull LifecycleObserver observer) {

        //检测是否在主线程执行,不是主线程会抛出异常

        enforceMainThreadIfNeeded("addObserver");

        //初始化一个生命周期状态值 除非LifecycleOwner宿主处于DESTROYED状态,否则都初始化为INITIALIZED

        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;

        //用当前的observer观察者和初始化状态值 包装成一个ObserverWithState类

        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);

        //将observer观察者与/ObserverWithState put到map中

        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

        //putIfAbsent 中会判断是否已存在这个observer,存在则返回对应的ObserverWithState,说明已经添加过了 可以直接return

        if (previous != null) {

            return;

        }

        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();

        if (lifecycleOwner == null) {

            // it is null we should be destroyed. Fallback quickly

            return;

        }

        //控制是否可进行同步 具体可在LifecycleRegistry完整源码中搜索有mAddingObserverCounter与mHandlingEvent赋值的地方

        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;

        //计算出当前观察者应该要到达的状态

        //假设LifecycleOwner宿主生命周期已经走到onResume(),那么mState = State.RESUMED,

        //那么 targetState = State.RESUMED

        State targetState = calculateTargetState(observer);

        mAddingObserverCounter++;

        //如果当前statefulObserver.mState 还没前进到 目标状态 ,需要进行while

        while ((statefulObserver.mState.compareTo(targetState) < 0 && mObserverMap.contains(observer))) {

            //记录当前statefulObserver.mState状态

            pushParentState(statefulObserver.mState);

            /**获取statefulObserver.mState要到达下一个状态所需要执行的事件

            * 如开始statefulObserver.mState = INITIALIZED

            * 要到达下一个状态就要执行ON_CREATE事件

            */

            final Event event = Event.upFrom(statefulObserver.mState);

            if (event == null) {

                throw new IllegalStateException("no event up from " + statefulObserver.mState);

            }

            //利用包装类进行事件派发,并更新为下一个状态

            statefulObserver.dispatchEvent(lifecycleOwner, event);

            //删除记录的最后一个状态

            popParentState();

            //再一次更新目标状态

            targetState = calculateTargetState(observer);

        }

        if (!isReentrance) {

            //同步操作

            sync();

        }

        mAddingObserverCounter--;

    }

    private State calculateTargetState(LifecycleObserver observer) {

        //mObserverMap是一个双向链表,这里是获取当前的observer的前一个observer

        Map.Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);

        //如果有前一个observer就将它最后所记录到的状态赋值给siblingState,否则赋值null

        State siblingState = previous != null ? previous.getValue().mState : null;

        //mParentStates用于记录当前观察者上一个状态

        State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)

                : null;

        return min(min(mState, siblingState), parentState);

    }

    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;

            }

        }

```

    addObserver流程总结:

    1.线程检查

    2.初始化initialState = INITIALIZED(宿主状态不是DESTROYED)

    3.将observer和initialState包装成ObserverWithState实例

    4.将observer和ObserverWithState放到mObserverMap中

    5.获取observe应该要到达的目标状态(或理解为宿主当前状态)

    6.判断observe最新状态是否少于目标状态,是则根据当前状态去获取到达下一个状态所需要执行的Event

    7.ObserverWithState.dispatchEvent将Event派发,并根据Event对应的状态赋值给ObserverWithState.mState

    8.如果更新后的ObserverWithState.mState还是少于目标状态,则继续执行while体,直到ObserverWithState.mState不少于目标状态

### handleLifecycleEvent

handleLifecycleEvent是接受LifecycleOwner宿主生命周期事件的入口

```

public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {

        enforceMainThreadIfNeeded("handleLifecycleEvent");

        //event.getTargetState() 根据LifecycleOwner宿主生命事件获取对应的状态值

        moveToState(event.getTargetState());

    }

    private void moveToState(State next) {

        if (mState == next) {

            return;

        }

        //用mState记录LifecycleOwner宿主最新的状态

        mState = next;

        //如果正在同步中 或者 正在走addObserver流程 则return 以免重复执行同步

        if (mHandlingEvent || mAddingObserverCounter != 0) {

            mNewEventOccurred = true;

            // we will figure out what to do on upper level.

            return;

        }

        mHandlingEvent = true;

        //执行同步操作

        sync();

        mHandlingEvent = false;

    }

    //判断所有的ObserverWithState中的状态是否一致,是否与记录LifecycleOwner宿主最新的状态mState一致

    //return true 说明所有ObserverWithState中的状态与mState一致,则表示同步完成

    private boolean isSynced() {

        //没有

        if (mObserverMap.size() == 0) {

            return true;

        }

        //链表头

        State eldestObserverState = mObserverMap.eldest().getValue().mState;

        //链表未

        State newestObserverState = mObserverMap.newest().getValue().mState;

        return eldestObserverState == newestObserverState && mState == newestObserverState;

    }

    private void sync() {

        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();

        //LifecycleOwner宿主为空,抛异常

        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.

            //记录LifecycleOwner宿主的mState 是否少于 链表头元素记录的mState,

            //是则需要执行状态回退事件

            //如LifecycleOwner宿主从onResume()->onPause(),状态由State.RESUMED -> State.STARTED

            //而元素记录的mState还是State.RESUMED,那么就要执行状态回退

            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {

                backwardPass(lifecycleOwner);

            }

            //记录LifecycleOwner宿主的mState 是否大于 链表未位元素记录的mState,

            //是则需要执行状态前进事件

            Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();

            if (!mNewEventOccurred && newest != null

                    && mState.compareTo(newest.getValue().mState) > 0) {

                forwardPass(lifecycleOwner);

            }

        }

        mNewEventOccurred = false;

    }

    private void backwardPass(LifecycleOwner lifecycleOwner) {

        //获取mObserverMap的倒序迭代器

        Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> descendingIterator =

                mObserverMap.descendingIterator();

        //进行迭代获取每一个entry       

        while (descendingIterator.hasNext() && !mNewEventOccurred) {

            Map.Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();

            ObserverWithState observer = entry.getValue();

            //获取到entry后 根据状态 循环对比 大于宿主mState的 就回退一级,直到不大于宿主mState

            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();

            }

        }

    }

    private void forwardPass(LifecycleOwner lifecycleOwner) {

        //获取mObserverMap的迭代器

        Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =

                mObserverMap.iteratorWithAdditions();

        //进行迭代获取每一个entry   

        while (ascendingIterator.hasNext() && !mNewEventOccurred) {

            Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();

            ObserverWithState observer = entry.getValue();

            //获取到entry后 根据状态 循环对比 少于宿主mState的 就前进一级,直到不少于宿主mState

            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred

                    && mObserverMap.contains(entry.getKey()))) {

                pushParentState(observer.mState);

                //根据状态获取前进事件

                final Event event = Event.upFrom(observer.mState);

                if (event == null) {

                    throw new IllegalStateException("no event up from " + observer.mState);

                }

                //派发事件

                observer.dispatchEvent(lifecycleOwner, event);

                popParentState();

            }

        }

    }

    //根据状态 获取回退事件

    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;

            }

        }

    //根据状态 获取前进事件

    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;

            }

        }

```

    handleLifecycleEvent流程总结

    1.主线程检查

    2.LifecycleOwner宿主传进来的事件转为State

    3.判断当前记录的mState是否与State一致,如一致则直接return

    4.更新mState,并判断是否正在同步中或者正在走addObserver流程,是则return 以免重复执行同步

    5.sync()执行同步

    5.1.isSynced()判断mObserverMap链表的头尾state值是否相同,是否与最新的mState相等

    5.2.使用最新的mState与链表头的state值比较,如mState<链表头的state,需执行回退事件

      5.2.1.获取mObserverMap的降序迭代器,迭代获取每一个entry

      5.2.2.while循环判断entry状态是否大于宿主mStste,是则回退一级,直到不大于宿主mState

      5.2.3.使用Event.downFrom获取回退事件,使用ObserverWithState.dispatchEvent进行事件派发

    5.3.使用使用最新的mState与链表末尾的state值比较,如mState>链表末尾的state,需执行前进事件

      5.3.1.获取mObserverMap的迭代器,迭代获取每一个entry

      5.3.2.while循环判断entry状态是否少于宿主mStste,是则前进一级,直到不少于宿主mState

      5.3.3.使用Event.upFrom获取前进事件,使用ObserverWithState.dispatchEvent进行事件派发

### ObserverWithState.dispatchEvent

所有事件最终是通过ObserverWithState.dispatchEvent方法执行派发

```

static class ObserverWithState {

        //记录最新已派发处理的状态

        State mState;

        //观察者

        LifecycleEventObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {

            //将LifecycleObserver观察者类型转化为LifecycleEventObserver类型

            //实现LifecycleObserver方式有

            //  方式1:implements LifecycleEventObserver接口

            //  方式2:implements FullLifecycleObserver接口

            //  方式3:implements LifecycleEventObserver 和 FullLifecycleObserver接口

            //  方式4:implements LifecycleObserver,使用@OnLifecycleEvent注解

            //根据不同的实现方式转化为不同的适配类,每个适配类均 implements LifecycleEventObserver,

            mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);

            mState = initialState;

        }

        void dispatchEvent(LifecycleOwner owner, Event event) {

            //根据最新需要处理的Event获取其对应的状态值

            State newState = event.getTargetState();

            mState = min(mState, newState);

            //通知观察者生命周期变化

            mLifecycleObserver.onStateChanged(owner, event);

            //记录最新已派发的状态

            mState = newState;

        }

    }

```

    ObserverWithState总结

      1.构造函数里 根据LifecycleObserver观察者的实现方式 统一转化为LifecycleEventObserver类型,方便事件派发

      2.分发事件时,先获取要派发事件对应的状态,然后使用mLifecycleObserver派发,最后记录新的状态

相关文章

网友评论

      本文标题:Android-Lifecycle分析笔记

      本文链接:https://www.haomeiwen.com/subject/kjlpvdtx.html