Lifecycle原理

1. Lifecycle作用

Lifecycle是用来构建生命周期感知型组件的工具。

使得我们可以用统一的方式来监听 Activity、Fragment、Service、甚至是 Process 的生命周期变化。

2. Lifecycle类

public abstract class Lifecycle {

    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);

    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);

    @MainThread
    @NonNull
    public abstract State getCurrentState();

    public enum Event {
        ON_CREATE,
        ON_START,
        ON_RESUME,
        ON_PAUSE,
        ON_STOP,
        ON_DESTROY,
        ON_ANY
    }

    @SuppressWarnings("WeakerAccess")
    public enum State {
        DESTROYED,
        INITIALIZED,
        CREATED,
        STARTED,
        RESUMED;
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }
}

Event 用于抽象 Activity/Fragment 的生命周期事件。例如,当 Activity 的 onCreate 方法被回调时就会被抽象为 ON_CREATE事件。

State 用于标记 Lifecycle 的当前生命周期状态。例如,当 Activity 即将回调 onDestory 方法时则处于 DESTROYED 状态

image.png

3. 相关接口

3.1 LifecycleOwner

LifecycleOwner 接口用于标记其实现类具备 Lifecycle 对象,实现了该接口即意味着实现类具有生命周期。我们日常使用的 androidx.appcompat.app.AppCompatActivity 和 androidx.fragment.app.Fragment 均实现了该接口。

public interface LifecycleOwner {
    @NonNull
    Lifecycle getLifecycle();
}

public class ComponentActivity|Fragment implements  LifecycleOwner {
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

3.2 LifecycleObserver

LifecycleObserver 生命周期观察者,是一个空接口,仅是用于类型标记。

3.3 LifecycleEventObserver

LifecycleEventObserver 用于监听 Lifecycle 的生命周期变化,可以接收到生命周期事件变化。

public interface LifecycleEventObserver extends LifecycleObserver {
    
    void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
    
}

3.4 FullLifecycleObserver

FullLifecycleObserver 根据 Activity 的生命周期回调方法扩展了几个同名的抽象方法,可以看成是对 LifecycleEventObserver 进行更加具体的事件拆分

interface FullLifecycleObserver extends LifecycleObserver {

    void onCreate(LifecycleOwner owner);

    void onStart(LifecycleOwner owner);

    void onResume(LifecycleOwner owner);

    void onPause(LifecycleOwner owner);

    void onStop(LifecycleOwner owner);

    void onDestroy(LifecycleOwner owner);
}

3.5 FullLifecycleObserverAdapter

FullLifecycleObserverAdapter 实现了 LifecycleEventObserver 接口,用于在收到 Lifecycle 生命周期事件时转发给 FullLifecycleObserver、LifecycleEventObserver。

class FullLifecycleObserverAdapter implements LifecycleEventObserver {

    private final FullLifecycleObserver mFullLifecycleObserver;
    private final LifecycleEventObserver mLifecycleEventObserver;

    FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,
            LifecycleEventObserver lifecycleEventObserver) {
        mFullLifecycleObserver = fullLifecycleObserver;
        mLifecycleEventObserver = lifecycleEventObserver;
    }

    @Override
    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);
        }
    }
}

4. 原理分析

4.1 Activity生命周期监听

public class ComponentActivity implements  LifecycleOwner {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
    }
    
 public class ReportFragment extends android.app.Fragment {
    private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";

    public static void injectIfNeededIn(Activity activity) {
        if (Build.VERSION.SDK_INT >= 29) {
             //当 API 等级为 29+ 时,我们可以直接向 android.app.Activity 注册生命周期回调
            LifecycleCallbacks.registerIn(activity);
        }
        
        //在 API 29 之前,向 activity 添加一个不可见的 framework 中的 fragment,以此来取得 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();
        }
    }
 }

1,设备的系统版本号大于等于29。会向 Activity 注册一个 LifecycleCallbacks ,以此来直接获得各个生命周期事件的回调。

2,设备的系统版本号小于 29。会通过向 Activity 添加一个无 UI 界面的 Fragment(即 ReportFragment),间接获得 Activity 的各个生命周期事件的回调。

3,之所以会进行这两种情况区分,是因为 Activity.registerActivityLifecycleCallbacks 是 SDK 29 开始 android.app.Activity 新添加的方法。

4.2 sdk >=29

static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {

        static void registerIn(Activity activity) {
       // Register an {@link Application.ActivityLifecycleCallbacks} instance that receives lifecycle callbacks for only this Activity.
            activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
        }

        @Override
        public void onActivityPostCreated(@NonNull Activity activity,
                @Nullable Bundle savedInstanceState) {
            dispatch(activity, Lifecycle.Event.ON_CREATE);
        }    
}

static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
        //从Activity中取出LifecycleRegistry,调用handleLifecycleEvent方法
        if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }
        

activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks()); Activity生命周期回调的时候会回调LifecycleCallbacks的对应生命周期方法。

dispatch方法:从Activity中取出LifecycleRegistry,调用handleLifecycleEvent方法。

4.2 sdk < 29

 public class ReportFragment extends android.app.Fragment {
    @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);
    }
    
      private void dispatch(@NonNull Lifecycle.Event event) {
        if (Build.VERSION.SDK_INT < 29) {
            dispatch(getActivity(), event);
        }
    }
}
    

直接在ReportFragment的对应生命周期中调用了dispatch去分发生命周期。

5. Fragment生命周期监听

public class Fragment implement LifecycleOwner{
            
    LifecycleRegistry mLifecycleRegistry;
           
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
    
     void performStart() {
        ...
        onStart();
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
        ...
    }
        
}

Fragment 是在其生命周期方法中直接调用了内部LifecycleRegistry的的handleLifecycleEvent进行生命周期时间分发。

6. LifecycleRegistry

LifecycleRegistry 向 Observer 发布 Event 值的触发条件有两种:

1,新添加了一个 Observer,需要向其同步 Activity 当前的 State 值。例如,当 Activity 处于 RESUMED 状态时向其添加了一个 LifecycleEventObserver ,此时就必须向 LifecycleEventObserver 同步当前的最新状态值,所以 LifecycleEventObserver 就会先后收到 CREATED、STARTED、RESUMED 三个 Event

2,Activity 的生命周期状态发生了变化,需要向 Observer 同步最新的 State 值

6.1 LifecycleRegistry#addObserver

    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

        if (previous != null) {
            //如果 observer 之前已经传进来过了,则不重复添加,直接返回
            return;
        }
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            //如果 LifecycleOwner 对象已经被回收了,则直接返回
            return;
        }

        //如果 isReentrance 为 true,意味着当前存在重入的情况:
        //1. mAddingObserverCounter != 0。会出现这种情况,是由于开发者先添加了一个 LifecycleObserver ,当还在向其回调事件的过程中,在回调方法里又再次调用了 addObserver 方法添加了一个新的 LifecycleObserver
        //2.mHandlingEvent 为 true。即此时正处于向外回调 Lifecycle.Event 的状态
        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;

        State targetState = calculateTargetState(observer);

        //递增加一,标记当前正处于向新添加的 LifecycleObserver 回调 Event 值的过程
        mAddingObserverCounter++;

        //statefulObserver.mState.compareTo(targetState) < 0 成立的话说明 State 值还没遍历到目标状态
        //mObserverMap.contains(observer) 成立的话说明 observer 还没有并移除
        //因为有可能在遍历过程中开发者主动在回调方法里将 observer 给移除掉了,所以这里每次循环都检查下
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) {
           
            //向 observer 回调进入“statefulObserver.mState”前需要收到的 Event 值
            statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
           
        }
        if (!isReentrance) {
            sync();
        }
        mAddingObserverCounter--;
    }

1,addObserver() 方法的主要逻辑是:将传入的 observer 对象包装为 ObserverWithState 类型,方便将 1,注解形式的LifecycleObserver和 2,接口实现的 LifecycleObserver,进行状态回调时的入口统一为 dispatchEvent() 方法。

2,此外,由于当添加 LifecycleObserver 时 Lifecycle 可能已经处于非 INITIALIZED 状态了,所以需要通过循环检查的方式来向 ObserverWithState 逐步下发 Event 值。

3,假设当前 LifecycleRegistry 的 mState 处于 RESUMED 状态,此时通过 addObserver 方法新添加的 LifecycleObserver 会被包装为 ObserverWithState,且初始化状态为 INITIALIZED。由于 RESUMED 大于INITIALIZED,ObserverWithState 就会按照 INITIALIZED -> CREATED -> STARTED -> RESUMED 这样的顺序先后收到事件通知

4,假设当前 LifecycleRegistry 的 mState 处于 STARTED 状态。如果 LifecycleRegistry 收到 ON_RESUME 事件,mState 就需要变更为 RESUMED;如果 LifecycleRegistry 收到 ON_STOP 事件,mState 就需要变更为 CREATED;所以说,LifecycleRegistry 的 mState 会先后向不同方向迁移

5,ObserverWithState 将外界传入的 LifecycleObserver 对象传给 Lifecycling 进行类型包装,将反射逻辑和接口回调逻辑都给汇总综合成一个新的 LifecycleEventObserver 对象,从而使得 Event 分发过程都统一为 mLifecycleObserver.onStateChanged

6.2 LifecycleRegistry#handleLifecycleEvent

ReportFragment 最终在向外传出 Lifecycle.Event 值时,调用的都是 LifecycleRegistry 的 handleLifecycleEvent(Lifecycle.Event) 方法,该方法会根据接收到的 Event 值换算出对应的 State 值,然后更新本地的 mState,再向所有 Observer 进行事件通知,最终还是会调用到 ObserverWithState 的 dispatchEvent 方法。

 public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        enforceMainThreadIfNeeded("handleLifecycleEvent");
        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;
    }
    
     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.");
        }
        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);
            }
            Map.Entry newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }
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);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }

6.3 Lifecycling#lifecycleEventObserver

static LifecycleEventObserver lifecycleEventObserver(Object object) {
        boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
        boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
        //同时实现了 LifecycleEventObserver 和 FullLifecycleObserver 接口
        //则将其包装为 FullLifecycleObserverAdapter 对象来进行事件转发
        if (isLifecycleEventObserver && isFullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
                    (LifecycleEventObserver) object);
        }
        //实现FullLifecycleObserver接口
        if (isFullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
        }
        //实现LifecycleEventObserver接口
        if (isLifecycleEventObserver) {
            return (LifecycleEventObserver) object;
        }

        //实现LifecycleObserver接口,使用注解
        final Class klass = object.getClass();
        int type = getObserverConstructorType(klass);
        //使用apt生成xx_LifecycleAdapter类
        if (type == GENERATED_CALLBACK) {
            List> constructors =
                    sClassToAdapters.get(klass);
            if (constructors.size() == 1) {
                GeneratedAdapter generatedAdapter = createGeneratedAdapter(
                        constructors.get(0), object);
                return new SingleGeneratedAdapterObserver(generatedAdapter);
            }
            GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
            for (int i = 0; i < constructors.size(); i++) {
                adapters[i] = createGeneratedAdapter(constructors.get(i), object);
            }
            return new CompositeGeneratedAdaptersObserver(adapters);
        }
        //未使用apt生成xx_LifecycleAdapter类
        return new ReflectiveGenericLifecycleObserver(object);
    }

通过Lifecycling#lifecycleEventObserver生成了五种Adapter,将生命周期事件转发给它们进行分发。

1,FullLifecycleObserverAdapter(可分发FullLifecycleObserver接口和LifecycleEventObserver接口:在FullLifecycleObserverAdapter会根据event事件调用FullLifecycleObserver对应的事件方法; 调用LifecycleEventObserver.onStateChanged分发事件。

2,LifecycleEventObserver: 调用LifecycleEventObserver.onStateChanged分发事件。

3,SingleGeneratedAdapterObserver,CompositeGeneratedAdaptersObserver(通过apt生成的生命周期事件分发类),调用GeneratedAdapter.callMethods进行事件分发,GeneratedAdapter内部会根据event选择调用对应方法。

4,ReflectiveGenericLifecycleObserver(通过反射生成的生命周期事件分发类),内部持有一个CallbackInfo,通过反射收集了event-list的map,根据event找到对应方法进行分发。

7.参考

  1. https://juejin.cn/post/6847902220755992589#heading-13
  2. https://blog.csdn.net/weixin_40888127/article/details/108520307

你可能感兴趣的:(Lifecycle原理)