Lifecycle--生命周期感知型组件,源码分析

为什么要引入Lifecycle?

我们在处理Activity或者Fragment组件的生命周期相关时,会遇到一些问题:
比如Activity#onCreate()中初始化某些成员(MVP架构中的Presenter或者MediaPlayer等),onStop()的时候对这些成员进行对应的处理,在onDestroy()中进行资源的释放。类似下面的代码:

    public class MyPresenter {

        public void onCreate(){
            //初始化操作

        }

        public void onStop(){
            //do something
        }

        public void onDestroy(){
            //释放资源

        }
    }

    class MyActivity extends AppCompatActivity {
        private MyPresenter myPresenter;

        @Override
        public void onCreate(...) {
            //资源初始化
            myPresenter = new MyPresenter();
            myPresenter.onCreate();
        }

        @Override
        public void onStop() {
            super.onStop();
            myPresenter.onStop();
            // 管理响应activity lifecycle的组件
        }
        
        @Override
        public void onDestroy() {
            super.onDestroy();
            myPresenter.onDestroy();
            //资源的释放
        }
    }

此示例看起来没问题,但在真实的应用中,最终会有太多管理界面和其他组件的调用,以响应生命周期的当前状态。管理多个组件会在生命周期方法(如 onStart()onStop())中放置大量的代码,这使得它们难以维护。


使用Lifecycle组件来感知Activity/Fragment生命周期,两步操作就可以了

  1. MyPresenter实现LifecycleObserver接口
public class MyPresenter implements LifecycleObserver{

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void onCreate(){
        //初始化操作
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop(){

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy(){
        //释放资源
    }
}
  1. Activity/Fragment中添加Observer:
 class MyActivity extends AppCompatActivity {
           private MyPresenter myPresenter;
   
           @Override
           public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
               myPresenter = new MyPresenter();
               //添加观察者
               getLifecycle().addObserver(myPresenter);
           }
       }  

Lifecycle组件中的核心类

Lifecycle抽象类,属于观察者模式中的被观察者。内部两个enum分别定义了生命周期事件(Event)以及状态(LifecycleState),定义了观察者(LifecycleObserver)的添加、移除以及当前生命周期状态的获取的方法

LifecycleStateEvent的关系

1594882307855.png

LifecycleRegisterLifecycle的实现类,负责接管生命周期以及LifecycleObserver的注册和通知。

LifecycleObserver是Lifecycle的观察者。

LifecycleOwner描述了一个拥有生命周期的组件,被观察者。

ObserverWithStateLifecycleObserver的封装类,构造函数调用了Lifecycling#lifecycleEventObserver方法。

Lifecycling 把传入的LifecycleObserver对象转化为LifecycleEventObserver对象。

ReflectiveGenericeLifecycleObserver LifecycleEventObserver的子类,内部实现依赖于反射。

ClassesInfoCache 储存了我们在观察者中注解的方法信息,并在生命周期发生改变时通过反射的方式调用对应的方法。


Activity中ReportFragment注入

API 27位于SupportActivity#onCreate();API 28位于ComponentActivity#onCreate()中。

1594864370892.png

添加观察者,LifecycleRegister#addObserver

public void addObserver(@NonNull LifecycleObserver observer) {
        //初始状态值
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        //把observer和state封装为ObserverWithState对象
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        //保存到mObserverMap中,如果已经添加过了直接返回map中保存的值
        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;
        }

        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
        State targetState = calculateTargetState(observer);
        mAddingObserverCounter++;
        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);
        }

        if (!isReentrance) {
            //不是重入,同步
            // we do sync only on the top level.
            sync();
        }
        mAddingObserverCounter--;
    }

ObserverWithState 是LifecycleObserver的封装类

static class ObserverWithState {
        State mState;
        LifecycleEventObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
            //通过Lifecycling获取LifecycleObserver的实现类
            mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
            mState = initialState;
        }
        ...
    }

LifecycleObserver实现类的获取流程:

  1. Lifecycling#lifecycleEventObserver 获取对应的LifecycleObserver的实现类
    @NonNull
    static LifecycleEventObserver lifecycleEventObserver(Object object) {
        boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
        boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
        if (isLifecycleEventObserver && isFullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
                    (LifecycleEventObserver) object);
        }
        if (isFullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
        }

        if (isLifecycleEventObserver) {
            return (LifecycleEventObserver) object;
        }

        final Class klass = object.getClass();
        //构造函数的类型
        int type = getObserverConstructorType(klass);
        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);
        }
        //反射生成
        return new ReflectiveGenericLifecycleObserver(object);
    }
  1. ReflectiveGenericLifecycleObserver构造函数通过ClassesInfoCache类的单例调用getInfo()获取CallbackInfo对象的实例
ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }
  1. ClassesInfoCache 内部有两个Map,实现了类信息的缓存
/**
 * Reflection is expensive, so we cache information about methods
 * for {@link ReflectiveGenericLifecycleObserver}, so it can call them,
 * and for {@link Lifecycling} to determine which observer adapter to use.
 */
 //从描述可以看出,反射的代价是昂贵的,所以这里缓存了methods信息
 
 //存储当前类的CallbackInfo的信息
 private final Map mCallbackMap = new HashMap<>();
 //存储当前类是否有使用了注解的生命周期方法
 private final Map mHasLifecycleMethods = new HashMap<>();
 
 CallbackInfo getInfo(Class klass) {
        CallbackInfo existing = mCallbackMap.get(klass);
        //缓存中有,直接返回
        if (existing != null) {
            return existing;
        }
        //缓存中没有,进行创建
        existing = createInfo(klass, null);
        return existing;
    }

//通过反射查找被@OnLifecycleEvent注解修饰的方法,然后保存起来
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
        Class superclass = klass.getSuperclass();
        Map handlerToEvent = new HashMap<>();
        if (superclass != null) {
            CallbackInfo superInfo = getInfo(superclass);
            if (superInfo != null) {
                handlerToEvent.putAll(superInfo.mHandlerToEvent);
            }
        }

        Class[] interfaces = klass.getInterfaces();
        for (Class intrfc : interfaces) {
            for (Map.Entry entry : getInfo(
                    intrfc).mHandlerToEvent.entrySet()) {
                verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
            }
        }

        Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
        boolean hasLifecycleMethods = false;
        for (Method method : methods) {
            //获取方法上的@OnLifecycleEvent注解信息
            OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
            if (annotation == null) {
                continue;
            }
            hasLifecycleMethods = true;
            Class[] params = method.getParameterTypes();
            int callType = CALL_TYPE_NO_ARG;
            if (params.length > 0) {
                callType = CALL_TYPE_PROVIDER;
                if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
                    throw new IllegalArgumentException(
                            "invalid parameter type. Must be one and instanceof LifecycleOwner");
                }
            }
            Lifecycle.Event event = annotation.value();

            //参数校验
            if (params.length > 1) {
                callType = CALL_TYPE_PROVIDER_WITH_EVENT;
                if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
                    throw new IllegalArgumentException(
                            "invalid parameter type. second arg must be an event");
                }
                if (event != Lifecycle.Event.ON_ANY) {
                    throw new IllegalArgumentException(
                            "Second arg is supported only for ON_ANY value");
                }
            }
            if (params.length > 2) {
                throw new IllegalArgumentException("cannot have more than 2 params");
            }
            MethodReference methodReference = new MethodReference(callType, method);
            verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
        }
        CallbackInfo info = new CallbackInfo(handlerToEvent);
        mCallbackMap.put(klass, info);
        mHasLifecycleMethods.put(klass, hasLifecycleMethods);
        return info;
    }

FastSafeIterableMap#putIfAbsent

@Override
    public V putIfAbsent(@NonNull K key, @NonNull V v) {
        Entry current = get(key);
        //map中存在,直接返回
        if (current != null) {
            return current.mValue;
        }
        //不存在,存入map中
        mHashMap.put(key, put(key, v));
        return null;
    }

FastSafeIterableMap是SafeIterableMap的子类, SafeIterableMap实现了Iterable接口,它是一个链表结构,模拟了Map的特性,支持在对元素遍历期间做修改,但需要注意的是该类不是线程安全的。 SafeIterableMap源码分析请参考
Android源码系列之从源码的角度深入理解SafeIterableMap


下面从ReportFragment#onStart()方法,跟踪Lifecycle是如何实现生命周期的感知并把状态同步到观察者中的注解方法上的流程

ReportFragment#onStart()

@Override
public void onStart() {
    super.onStart();
    dispatchStart(mProcessListener);
    //分发事件
    dispatch(Lifecycle.Event.ON_START);
}

ReportFragment#dispatch() 内部最后都是调用LifecycleRegistry#handleLifecycleEvent()

private void dispatch(Lifecycle.Event event) {
        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);
            }
        }
    }

LifecycleRegistry#handleLifecycleEvent()处理生命周期事件:

 public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        //根据Event得到LifecycleState的值
        State next = getStateAfter(event);
        moveToState(next);
    }

LifecycleStateEvent的关系图解描述的就是这个方法

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);
    }
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;
    }
    // happens only on the top of stack (never in reentrance),
    // so it doesn't have to take in account parents
    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) {
                //遍历mObserverMap中元素,从链表的尾部开始同步状态
                backwardPass(lifecycleOwner);
            }
            Entry newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                //遍历mObserverMap中元素,从链表的头部开始同步状态
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }
//遍历mObserverMap中元素,从链表的尾部开始同步状态
private void backwardPass(LifecycleOwner lifecycleOwner) {
        Iterator> descendingIterator =
                mObserverMap.descendingIterator();
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Entry entry = descendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                Event event = downEvent(observer.mState);
                pushParentState(getStateAfter(event));
                //分发事件
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }

LifecycleRegistry$ObserverWithState#dispatchEvent

void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            //通知观察者生命周期状态变更,调到LifecycleEventObserver的子类的onStateChanged()
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }

文中LifecycleEventObserver的子类为ReflectiveGenericLifecycleObserver,具体为什么是它,参考上面提到的LifecycleObserver实现类的获取流程

@Override
public void onStateChanged(LifecycleOwner source, Event event) {
    mInfo.invokeCallbacks(source, event, mWrapped);
}

ClassesInfoCache$CallbackInfo#invokeCallbacks

@SuppressWarnings("ConstantConditions")
void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target)        {
     invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
     invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source,  event,target);
}
private static void invokeMethodsForEvent(List handlers,
                LifecycleOwner source, Lifecycle.Event event, Object mWrapped) {
            if (handlers != null) {
                for (int i = handlers.size() - 1; i >= 0; i--) {
                    handlers.get(i).invokeCallback(source, event, mWrapped);
                }
            }
        }

ClassesInfoCache$MethodReference#invokeCallback 反射调用方法

void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
            //noinspection TryWithIdenticalCatches
            try {
                switch (mCallType) {
                    case CALL_TYPE_NO_ARG:
                        mMethod.invoke(target);
                        break;
                    case CALL_TYPE_PROVIDER:
                        mMethod.invoke(target, source);
                        break;
                    case CALL_TYPE_PROVIDER_WITH_EVENT:
                        mMethod.invoke(target, source, event);
                        break;
                }
            } catch (InvocationTargetException e) {
                throw new RuntimeException("Failed to call observer method", e.getCause());
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }

至此,生命周期组件(Activity/Fragment)和观察者生命周期的同步流程结束了。

总结

Lifecycle组件通过在Activity/Fragmen中注入空的Fragment(ReportFragment),实现了对生命周期的感知。使用反射把使用了@OnLifecycleEvent注解的方法信息保存下来,基于观察者模式,在Activity/Fragment生命周期改变的时候同步状态到观察者。

你可能感兴趣的:(Lifecycle--生命周期感知型组件,源码分析)