Android开发Jetpack组件Lifecycle原理篇

Android开发Jetpack组件Lifecycle原理篇 目录 前言 1.Lifecycle的生命周期状态事件和状态 2.Lifecycle如何观察Activity和Fragment的生命周期 前言 在上一篇文章中,我们学习了如何去使用Lifecycle: 当然之会使用是不够的,还需要了解它的原理,这是成为优秀工程师必
目录
  • 前言
  • 1.Lifecycle的生命周期状态事件和状态
  • 2.Lifecycle如何观察Activity和Fragment的生命周期

前言

在上一篇文章中,我们学习了如何去使用Lifecycle; 当然之会使用是不够的,还需要了解它的原理,这是成为优秀工程师必备的;这篇文章就来学习Lifecycle的基本原理

1.Lifecycle的生命周期状态事件和状态

**Lifecycle使用两个枚举来跟踪其关联组件的生命周期状态,这两个枚举分别是Event和State;**State指的是Lifecycle的生命周期所处的状态;Event代表Lifecycle生命周期对应的事件,这些事件会映射到Activity和Fragment中的回调事件中

Android 9.0的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();
    @SuppressWarnings("WeakerAccess")
    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;
        }
    }
}

Lifecycle是一个抽象类; 其内部不仅包括了添加和移除观察者的方法,还包括了此前说到的Event和State枚举。可以看到Event中的事件和Activity的生命周期几乎是对应的,除了ON_ANY,它可用于匹配所有事件

2.Lifecycle如何观察Activity和Fragment的生命周期

在Android Support Library 26.1.0 及其之后的版本,Activity和Fragment已经默认实现了LifecycleOwner接口,LifecycleOwner可以理解为被观察者,那么Lifecycle是如何观察Activity和Fragment的生命周期的呢?

在上一篇文章举的例子中,MainActivity继承了AppCompatActivity,而AppCompatActivity继承了FragmentActivity。在Android 8.0时,FragmentActivity继承自SupportActivity,而在Android 9.0,FragmentActivity继承自ComponentActivity 。SupportActivity和ComponentActivity的代码区别不大,这里以ComponentActivity举例,如下所示

@RestrictTo(LIBRARY_GROUP)
public class ComponentActivity extends Activity implements LifecycleOwner {
    private SimpleArrayMap<Class<? extends ExtraData>, ExtraData> mExtraDataMap =
            new SimpleArrayMap<>();
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);//1
    @RestrictTo(LIBRARY_GROUP)
    public void putExtraData(ExtraData extraData) {
        mExtraDataMap.put(extraData.getClass(), extraData);
    }
    @Override
    @SuppressWarnings("RestrictedApi")
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);//2
    }
    @CallSuper
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        mLifecycleRegistry.markState(Lifecycle.State.CREATED);//3
        super.onSaveInstanceState(outState);
    }
    @RestrictTo(LIBRARY_GROUP)
    public <T extends ExtraData> T getExtraData(Class<T> extraDataClass) {
        return (T) mExtraDataMap.get(extraDataClass);
    }
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;//4
    }
    @RestrictTo(LIBRARY_GROUP)
    public static class ExtraData {
    }
}

注释1处创建了LifecycleRegistry,它是Lifecycle的实现类;注释4处实现了LifecycleOwner接口定义的getLifecycle方法,返回了LifecycleRegistry。在注释3处,将Lifecycle的State设置为CREATED;

正常来说应该在ComponentActivity的各个生命周期方法中改变Lifecycle的State,显然在ComponentActivity中没有做这些,而是将这个任务交给了ReportFragment,注释2处的将ComponentActivity注入到ReportFragment中

@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";
    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();
            manager.executePendingTransactions();
        }
    }
    static ReportFragment get(Activity activity) {
        return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
                REPORT_FRAGMENT_TAG);
    }
   ...
    @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);//1
    }
    @Override
    public void onResume() {
        super.onResume();
        dispatchResume(mProcessListener);
        dispatch(Lifecycle.Event.ON_RESUME);
    }
  ...
    private void dispatch(Lifecycle.Event event) {
        Activity activity = getActivity();
        if (activity instanceof LifecycleRegistryOwner) {//2
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
            return;
        }
        if (activity instanceof LifecycleOwner) {//3
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }
  ...
}

ReportFragment的onStart方法中会调用注释1处的dispatch方法; 在dispatch方法的注释2处,判断Activity是否实现了LifecycleRegistryOwner接口,LifecycleRegistryOwner继承了LifecycleOwner接口

这两个接口不同的是: LifecycleRegistryOwner定义的getLifecycle方法返回的是LifecycleRegistry类型,而LifecycleOwner定义的getLifecycle方法返回的是Lifecycle类型。注释3处如果Activity实现了LifecycleOwner接口,会调用LifecycleRegistry的handleLifecycleEvent方法

     public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }

getStateAfter方法会获取“即将的事件” :当前事件执行后,即将会处于什么事件,代码如下所示

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

这个和文章开头给出的State与Event关系的时序图对照看会比较好理解; 比如当前执行了ON_CREATE事件或者ON_STOP事件,那么状态就会处于CREATED;回到handleLifecycleEvent方法,其内部还会调用moveToState方法

   private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            return;
        }
        mHandlingEvent = true;
        sync();
        mHandlingEvent = false;
    }

如果当前所处的状态和即将要处于的状态一样就不做任何操作,sync方法如下所示

  private void sync() {
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
                    + "new events from it.");
            return;
        }
        while (!isSynced()) {
            mNewEventOccurred = false;
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

sync方法中会根据当前状态和mObserverMap中的eldest和newest的状态做对比 ,判断当前状态是向前还是向后; 比如由STARTED到RESUMED是状态向前,反过来就是状态向后,这个不要和Activity的生命周期搞混;向前还是向后的代码大同小异,这里以向后为例

    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();//1
            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                pushParentState(observer.mState);
                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));//2
                popParentState();
            }
        }
    }

注释1处的用于获取ObserverWithState,后面会在提到它。 注释2处的upEvent方法会得到当前状态的向前状态

ObserverWithState的dispatchEvent方法如下所示

    static class ObserverWithState {
        State mState;
        GenericLifecycleObserver mLifecycleObserver;
        ObserverWithState(LifecycleObserver observer, State initialState) {
            mLifecycleObserver = Lifecycling.getCallback(observer);//1
            mState = initialState;
        }
        void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }

从名称就可以看出来,它内部包括了State和GenericLifecycleObserver,GenericLifecycleObserver是一个接口,它继承了LifecycleObserver接口; ReflectiveGenericLifecycleObserver和CompositeGeneratedAdaptersObserver是GenericLifecycleObserver的实现类,这里主要查看ReflectiveGenericLifecycleObserver的onStateChanged方法是如何实现的

class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {
    private final Object mWrapped;
    private final CallbackInfo mInfo;
    ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }
    @Override
    public void onStateChanged(LifecycleOwner source, Event event) {
        mInfo.invokeCallbacks(source, event, mWrapped);//1
    }
}

注释1处会调用CallbackInfo的invokeCallbacks方法,在讲这个方法前,需要先了解CallbackInfo是怎么创建的,是由createInfo方法创建的,如下所示

 private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
        Class superclass = klass.getSuperclass();
        Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
       ...
        Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
        boolean hasLifecycleMethods = false;
        for (Method method : methods) {
            OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);//1
            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();//2
            ...
            MethodReference methodReference = new MethodReference(callType, method);//3
            verifyAndPutHandler(handlerToEvent, methodReference, event, klass);//4
        }
        CallbackInfo info = new CallbackInfo(handlerToEvent);//5
        mCallbackMap.put(klass, info);
        mHasLifecycleMethods.put(klass, hasLifecycleMethods);
        return info;
    }

关键点在注释1处; 不断的遍历各个方法,获取方法上的名为OnLifecycleEvent的注解,这个注解正是实现LifecycleObserver接口时用到的。

注释2处获取该注解的值; 也就是在@OnLifecycleEvent中定义的事件

注释3处新建了一个MethodReference; 其内部包括了使用了该注解的方法

注释4处的verifyAndPutHandler方法用于将MethodReference和对应的Event存在类型为Map<MethodReference, Lifecycle.Event> 的handlerToEvent中

注释5处新建CallbackInfo,并将handlerToEvent传进去

接着回头看CallbackInfo的invokeCallbacks方法,代码如下所示

static class CallbackInfo {
        final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;
        final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;
        CallbackInfo(Map<MethodReference, Lifecycle.Event> handlerToEvent) {
            mHandlerToEvent = handlerToEvent;
            mEventToHandlers = new HashMap<>();
            for (Map.Entry<MethodReference, Lifecycle.Event> entry : handlerToEvent.entrySet()) {//1
                Lifecycle.Event event = entry.getValue();
                List<MethodReference> methodReferences = mEventToHandlers.get(event);
                if (methodReferences == null) {
                    methodReferences = new ArrayList<>();
                    mEventToHandlers.put(event, methodReferences);
                }
                methodReferences.add(entry.getKey());
            }
        }
        @SuppressWarnings("ConstantConditions")
        void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
            invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);//2
            invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
                    target);
        }
        private static void invokeMethodsForEvent(List<MethodReference> 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);//1
                }
            }
        }

注释1处的循环的意义在于将handlerToEvent进行数据类型转换,转化为一个HashMap,key的值为事件,value的值为MethodReference。注释2处的invokeMethodsForEvent方法会传入mEventToHandlers.get(event),也就是事件对应的MethodReference的集合。invokeMethodsForEvent方法中会遍历MethodReference的集合,调用MethodReference的invokeCallback方法

 @SuppressWarnings("WeakerAccess")
    static class MethodReference {
        final int mCallType;
        final Method mMethod;
        MethodReference(int callType, Method method) {
            mCallType = callType;
            mMethod = method;
            mMethod.setAccessible(true);
        }
        void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
            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);
            }
        }
      ...
    }

MethodReference类中有两个变量,一个是callType,它代表调用方法的类型,另一个是Method; 它代表方法,不管是哪种callType都会通过invoke对方法进行反射。 简单来说,实现LifecycleObserver接口的类中,注解修饰的方法和事件会被保存起来,通过反射对事件的对应方法进行调用

到此这篇关于Android开发Jetpack组件Lifecycle使用原理篇的文章就介绍到这了,更多相关Android Jetpack组件Lifecycle内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐