亲宝软件园·资讯

展开

Android Lifecycle

猪飞啦~ 人气:0

提纲

1,什么是Lifecycle?

2,如何使用Lifecycle?

3,LifecycleOwner,Lifecycle,LifecycleObserver之间是什么关系?

3,Activity是如何实现Lifecycle的?

4,Fragment是如何实现Lifecycle的?

5,Lifecycle是如何下发宿主生命周期给观察者的?

什么是Lifecycle

Lifecycle是Jetpack组件库中的架构组件,顾名思义就是一个生命周期组件,它可感知宿主的生命周期,并根据生命周期反推出生命周期所属的状态下发给观察者。

如何使用Lifecycle

1,实现其生命周期回调接口,成为生命周期观察者

2,在Activity/Fragment中获取Lifecycle实例并添加观察者

3,实例代码如下,个人比较推荐第一种方式,第二种方式比较繁琐,需要在方法上通过注解来表明想要观察的生命周期事件

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        //订阅生命周期
        lifecycle.addObserver(MyLifecycleEventObserver())
        lifecycle.addObserver(MyLifecycleObserver())
    }
    /**
     * 方式一(个人比较推荐)
     */
    class MyLifecycleEventObserver : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            when (event) {
                Lifecycle.Event.ON_CREATE -> println("onCreate")
                Lifecycle.Event.ON_START -> println("onStart")
                Lifecycle.Event.ON_RESUME -> println("onResume")
                Lifecycle.Event.ON_PAUSE -> println("onPause")
                Lifecycle.Event.ON_STOP -> println("onStop")
                Lifecycle.Event.ON_DESTROY -> println("onDestroy")
            }
        }
    }
    /**
     * 方式二
     */
    class MyLifecycleObserver : LifecycleObserver {
        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        fun onCreate(event: Lifecycle.Event) {
            println("onCreate")
        }
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun onStart(event: Lifecycle.Event) {
            println("onStart")
        }
        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        fun onResume(event: Lifecycle.Event) {
            println("onResume")
        }
    }
}

关系梳理

LifecycleOwner,Lifecycle,LifecycleObserver之间是什么关系?

1,LifecycleOwner:生命周期持有者,我们的Activity/Fragment都实现了这个接口并重写了它的抽象方法getLicycle()返回一个Licycle实例。

2,Lifecycle:LifecycleRegsitry是它的唯一实现类,主要用来负责注册观察者,下发宿主状态给观察者

3,LicycleObserver:是一个接口,主要用来接收宿主的生命周期状态,实现该接口即可成为一个生命周期观察者

4,他们之间的持有关系如下图:

Activity是如何实现Lifecycle的

CompatActivity

如果我们的Activity是继承自CompatActivity,那么CompatActivity需要在Activity上添加一个ReportFragment来实现生命周期下发

(1)在CompatActivity中创建LifecycleRegistry类型的成员变量mLifecycleRegistry

(2)在CompatActivity的onCreate()方法中往Activity中添加一个ReportFragment来下发命周期

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner {
    //创建Lifecycle实例
    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSavedStateRegistryController.performRestore(savedInstanceState);
        //往Activity添加一个ReportFragment来达到下发生命周期的目的
        ReportFragment.injectIfNeededIn(this);
        if (mContentLayoutId != 0) {
            setContentView(mContentLayoutId);
        }
    }
}

(3) 将Fragment与Activity进行绑定,添加到Activity中,用于感知Activity生命周期变化

(4)当Activity生命周期发生变化,对应的生命周期回调方法被调用,下发生命周期给观察者

public class ReportFragment extends Fragment {
    public static void injectIfNeededIn(Activity activity) {
        //往Activity中存放一个ReportFragment
        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();
        }
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dispatchCreate(mProcessListener);
        dispatch(Lifecycle.Event.ON_CREATE);
    }
    @Override
    public void onStart() {
        super.onStart();
        dispatchStart(mProcessListener);
        dispatch(Lifecycle.Event.ON_START);
    }
    @Override
    public void onResume() {
        super.onResume();
        dispatchResume(mProcessListener);
        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);
        // just want to be sure that we won't leak reference to an activity
        mProcessListener = null;
    }
    /**
     * 下发生命周期事件
     */   
    private void dispatch(Lifecycle.Event event) {
        //获取Activity的Lifecycle实例,下发生命周期事件
        Activity activity = getActivity();
        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);
            }
        }
    }
}

AppCompatActivity

如果我们的Activity是继承自AppCompatActivity ,不需要往Activity中添加一个ReportFragment来感知生命周期并下发生命周期事件,AppCompatActivity 继承自FragmentActivity,下发生命周期事件都在FragmentActivity的生命周期回调方法中进行

(1)创建LifecycleRegistry类型的变量mFragmentLifecycleRegistry

(2)在其生命周期回调方法中调用mFragmentLifecycleRegistry的handlerLifecycleEvent()方法进行下发生命周期事件

public class FragmentActivity extends ComponentActivity implements
        ActivityCompat.OnRequestPermissionsResultCallback,
        ActivityCompat.RequestPermissionsRequestCodeValidator {
    //创建Lifecycle实例
    final LifecycleRegistry mFragmentLifecycleRegistry = new LifecycleRegistry(this);
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        //下发生命周期事件
        mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
    }
        @Override
    protected void onDestroy() {
        super.onDestroy();
        mFragments.dispatchDestroy();
        //下发生命周期事件
        mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
    }
    @Override
    protected void onPause() {
        super.onPause();
        mResumed = false;
        mFragments.dispatchPause();
        //下发生命周期事件
        mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
    }
    protected void onResumeFragments() {
        //下发生命周期事件
        mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
        mFragments.dispatchResume();
    }
}

Fragment是如何实现Lifecycle的

其实Fragment实现Lifecycle,下发其生命周期的操作跟AppCompatActivity 是一样的套路,在其生命周期回调方法中进行生命周期事件下发

(1)创建Fragment时调用initLifecycle()方法给LifecycleRegistry类型的mLifecycleRegistry变量赋值

(2)在其生命周期回调方法中调用mLifecycleRegistry的handlerLifecycleEvent()方法下发生命周期事件给观察者

public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
        ViewModelStoreOwner, SavedStateRegistryOwner {
    LifecycleRegistry mLifecycleRegistry;
    public Fragment() {
        initLifecycle();
    }
    private void initLifecycle() {
        //创建Lifecycle实例
        mLifecycleRegistry = new LifecycleRegistry(this);
    }
    void performCreate(Bundle savedInstanceState) {
        onCreate(savedInstanceState);
        //下发生命周期事件给观察者
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
    }
    void performStart() {
        onStart();
        //下发生命周期事件给观察者
        mChildFragmentManager.dispatchStart();
    }
    void performResume() {
        onResume();
        //下发生命周期事件给观察者
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
    }
}

Lifecycle是如何下发宿主生命周期给观察者的

(1)在我们调用Lifecycle的addObserver()方法时就已经开始下发生命周期事件了,接下来让我们先从addObserver()这个入口看看其实现逻辑,大致逻辑如下

public class LifecycleRegistry extends Lifecycle {
    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        //首次添加观察者,如果宿主状态不是DESTROYED,那么观察者初始状态都是INITIALIZED
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        //把传进去的生命周期观察者以及初始状态包装成ObserverWithState对象
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        //把包装好的ObserverWithState对象存放到观察者集合中,如果此前已经添加过则会返回此前添加的值,否则返回null
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
        //判断此前是否添加过,如果添加过则直接结束方法
        if (previous != null) {
            return;
        }
        //获取宿主实例
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            // it is null we should be destroyed. Fallback quickly
            return;
        }
        //计算观察者的目标状态
        State targetState = calculateTargetState(observer);
        //循环比对观察者的状态和宿主的状态,如果没有对齐则下发对应的生命周期事件
        //拿观察者的状态和宿主的状态做比较 如果小于0代表状态还没有对齐,需要继续下发生命周期状态给观察者
        //假设是在Activity的onResume()方法中注册的观察者,那么就需要给观察者下发onCreate,onStart,onResume这些事件
        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);
        }
    }
}

(2)分析完addObserver()做了哪些事,那么我们再来分析下handlerLifecycleEvent()方法做了什么事

public class LifecycleRegistry extends Lifecycle {
    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        //根据生命周期事件推算出其状态
        State next = getStateAfter(event);
        //移动到新状态
        moveToState(next);
    }
    private void moveToState(State next) {
        //如果当前状态和新状态相等 结束方法
        if (mState == next) {
            return;
        }
        //记录新状态
        mState = next;
        //如果当前正在下发生命周期事件 或 当前正在添加观察者 结束方法
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            return;
        }
        //同步新状态给观察者
        mHandlingEvent = true;
        sync();
        mHandlingEvent = false;
    }
    private void sync() {
        //获取宿主实例
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        //停止循环的条件是已经同步状态完成 或 没有观察者
        while (!isSynced()) {
            mNewEventOccurred = false;
            //获取观察者集合中最先添加的那个元素 拿当前状态和观察者状态作比较 判断当前是不是向后移动状态 STARTED -> ON_STOP
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
            //获取观察者集合中最新添加的那个元素 拿当前状态和观察者状态作比较 判断当前是不是向前移动状态 STARTED -> ON_RESUME
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }
    /**
     * 向前移动状态
     */
    private void forwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
        //遍历所有观察者
        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
            Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
            ObserverWithState observer = entry.getValue();
            //拿观察者的状态和宿主的状态做比较 如果小于0代表状态还没有对齐
            //假设当前宿主在RESUMED状态 观察者在CREATED状态 则需要下发:ON_START,ON_RESUME生命周期事件 需要循环两次
            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                pushParentState(observer.mState);
                //根据观察者状态反推向前移动事件 下发生命周期事件
                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
                popParentState();
            }
        }
    }
    /**
     * 通过观察者状态反推向前移动事件
     */
    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);
    }
    /**
     * 向后移动状态
     */
    private void backwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
                mObserverMap.descendingIterator();
        //遍历所有观察者
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
            ObserverWithState observer = entry.getValue();
            //拿观察者的状态和宿主的状态做比较 如果大于0代表状态还没有对齐
            //假设当前观察者在RESUMED状态 宿主在DESTROYED状态 那么需要下发:ON_PAUSE,ON_STOP,ON_DESTROY这些生命周期事件 循环三次
            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                //根据观察者状态反推出向后移动事件
                Event event = downEvent(observer.mState);
                pushParentState(getStateAfter(event));
                //下发该生命周期事件给观察者
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }
    /**
     * 通过观察者状态反推向后移动的事件
     */
    private static Event downEvent(State state) {
        switch (state) {
            case INITIALIZED:
                throw new IllegalArgumentException();
            case CREATED:
                return ON_DESTROY;
            case STARTED:
                return ON_STOP;
            case RESUMED:
                return ON_PAUSE;
            case DESTROYED:
                throw new IllegalArgumentException();
        }
        throw new IllegalArgumentException("Unexpected state value " + state);
    }
}

(3)接下来我们看看ObserverWitchState的dispatchEvent()方法是如何下发生命周期事件给观察者的,我们知道在调用Lifecycle的addObserver()方法时就把我们传进去的LifecycleObserver封装成了一个ObserverWitchState对象,并存放到生命周期观察者集合中

static class ObserverWithState {
        //记录当前状态
        State mState;
        //生命周期观察者
        LifecycleEventObserver mLifecycleObserver;
        ObserverWithState(LifecycleObserver observer, State initialState) {
            mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
            mState = initialState;
        }
        //下发生命周期事件给生命周期观察者
        void dispatchEvent(LifecycleOwner owner, Event event) {
            //根据生命周期事件推算出生命周期状态
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            //调用生命周期观察者的onStateChanged()方法通知生命周期观察者生命周期发生变化
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
}
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);
}

(4)到此结束,希望对读者有所帮助

加载全部内容

相关教程
猜你喜欢
用户评论