前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Lifecycle原理分析

Lifecycle原理分析

作者头像
None_Ling
发布2020-11-12 10:41:32
4990
发布2020-11-12 10:41:32
举报
文章被收录于专栏:Android相关

简述

LifeCycle通过在FragmentActivity中会添加ReportFragment用来监听Activity的生命周期 , 而在注册LifeCycleObserver的时候 , 会通过反射将声明了LifecycleEvent的Method找到 , 并且保存到CallbackInfo的数据结构中.

当回调时 , 就会找到CallbackInfo进行状态的回调.

优化

  1. 尽量使用FullLifecycleObserver或者GenericLifecycleObserver
    • 因为使用该类 , 不需要通过反射进行注释的读取
  2. 如果以上不适用 , 则尽量使用GeneratedAdapter , 同时保证只有一个构造函数
    • 因为该类只有callMethod方法 , 不会解析Annotation , 同时如果存在多个构造函数时 , 会根据构造函数创建多个GeneratedAdapter对象保存 , 并且进行回调
  3. 如果以上方案不适用 , 考虑使用LifeCycle , 切莫让LifeCycleObserver接口继承过深
    • 因为如果在该类匹配不到时 , 会遍历父类/继承的接口查找该接口

原理

  1. AppCompatActivity的基类ComponentActivity中 , 会完成 :
  • 创建LifecycleRegistry对象 , 用于管理回调以及生命周期
  • 调用ReportFragment.injectIfNeededIn创建ReportFragment , 用于监听生命周期
代码语言:javascript
复制
public class ComponentActivity extends Activity
        implements LifecycleOwner, KeyEventDispatcher.Component {
    ...
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

     ...
    @Override
    @SuppressWarnings("RestrictedApi")
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
    }
}
  1. 当添加LifecycleObserver的时候 :
  • 创建ObserverWithState变量 , 其中就会通过反射获取注释标注的函数
  • 比较当前状态与监听状态 , 回调当前的状态给LifeCycleObserver
代码语言:javascript
复制
@Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
         // 创建ObserverWithState变量 , 其中就会通过反射获取注释标注的函数
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        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++;
        // 回调当前的状态给LifeCycleObserver
        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--;
    }
  1. ObserverWithState创建的时候
  • 通过Lifecycling.getCallback(observer)生成GenricLifecycleObserver对象
  • 根据LifecycleObserver的class type以及构造函数生成对应的observer
  • 继承自GeneratedAdapter : 会回调callMethod方法
  • 继承自LifecycleObserver : 会回调根据注释标注的方法
代码语言:javascript
复制
static class ObserverWithState {
        State mState;
        GenericLifecycleObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
            mLifecycleObserver = Lifecycling.getCallback(observer);
            mState = initialState;
        }

        void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }

 @NonNull
    static GenericLifecycleObserver getCallback(Object object) {
        if (object instanceof FullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
        }

        if (object instanceof GenericLifecycleObserver) {
            return (GenericLifecycleObserver) object;
        }

        final Class<?> klass = object.getClass();
        int type = getObserverConstructorType(klass);
        if (type == GENERATED_CALLBACK) {
            // 判断Observer类是否为GeneratedAdapter子类
            List<Constructor<? extends GeneratedAdapter>> constructors =
                    sClassToAdapters.get(klass);
            if (constructors.size() == 1) {
                GeneratedAdapter generatedAdapter = createGeneratedAdapter(
                        constructors.get(0), object);
                // 如果是GeneratedAdapter子类 , 并且只有一个构造函数
                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);
            }
            // 生成多个GenerratedAdapter构造函数的对象 , 用于后面callMethod的回调
            return new CompositeGeneratedAdaptersObserver(adapters);
        }
        // 如果只是lifecycleObserverd的话 , 就会走这里
        return new ReflectiveGenericLifecycleObserver(object);
    }
  1. getObserverConstructorType中 , 会调用resolveObserverCallbakType , 用来解析Method
代码语言:javascript
复制
 private static int resolveObserverCallbackType(Class<?> klass) {
        // anonymous class bug:35073837
        if (klass.getCanonicalName() == null) {
            return REFLECTIVE_CALLBACK;
        }

        Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
        // 判断是否为GeneratedAdapter的子类
        if (constructor != null) {
            sClassToAdapters.put(klass, Collections
                    .<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
            return GENERATED_CALLBACK;
        }
        // 判断是否有lifecycle的函数
        boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
        if (hasLifecycleMethods) {
            return REFLECTIVE_CALLBACK;
        }

        Class<?> superclass = klass.getSuperclass();
        List<Constructor<? extends GeneratedAdapter>> adapterConstructors = null;
        // 判断子类是不是LifecycleObserver的子类
        if (isLifecycleParent(superclass)) {
            if (getObserverConstructorType(superclass) == REFLECTIVE_CALLBACK) {
                return REFLECTIVE_CALLBACK;
            }
            adapterConstructors = new ArrayList<>(sClassToAdapters.get(superclass));
        }
        // 判断子类是不是实现了LifecycleObserver的接口
        for (Class<?> intrface : klass.getInterfaces()) {
            if (!isLifecycleParent(intrface)) {
                continue;
            }
            if (getObserverConstructorType(intrface) == REFLECTIVE_CALLBACK) {
                return REFLECTIVE_CALLBACK;
            }
            if (adapterConstructors == null) {
                adapterConstructors = new ArrayList<>();
            }
            adapterConstructors.addAll(sClassToAdapters.get(intrface));
        }
        if (adapterConstructors != null) {
            sClassToAdapters.put(klass, adapterConstructors);
            return GENERATED_CALLBACK;
        }

        return REFLECTIVE_CALLBACK;
    }
  1. 在判断是否有LifecycleMethod的时候 :
  • 判断是否缓存中已经解析过该类
  • 反射得到Method的Annotation
  • 得到OnLifecycleEvent的Annotation
  • 创建MethodReference引用 , 保存Method
代码语言:javascript
复制
boolean hasLifecycleMethods(Class klass) {
        // 判断是否缓存中已经解析过该类
        if (mHasLifecycleMethods.containsKey(klass)) {
            return mHasLifecycleMethods.get(klass);
        }

        Method[] methods = getDeclaredMethods(klass);
        // 遍历所有的Method
        for (Method method : methods) {
            // 反射得到Method的Annotation
            OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
            if (annotation != null) {
                // 根据Annotation创建CallbackInfo
                createInfo(klass, methods);
                return true;
            }
        }
        mHasLifecycleMethods.put(klass, false);
        return false;
    }

private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
        // 获取class的父类
        Class superclass = klass.getSuperclass();
        Map<MethodReference, Lifecycle.Event> 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<MethodReference, Lifecycle.Event> entry : getInfo(
                    intrfc).mHandlerToEvent.entrySet()) {
                // 校验Handle的Method
                verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
            }
        }

        Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
        boolean hasLifecycleMethods = false;
        for (Method method : methods) {
            // 得到OnLifecycleEvent的Annotation
            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");
                }
            }
            // 得到Annotation的Event对象
            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");
            }
            // 创建Method引用
            MethodReference methodReference = new MethodReference(callType, method);  
            // 校验Method后 , 将MethodReference放到handler中
            verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
        }
        // 将CallbackInfo添加到mCallbackMap中
        CallbackInfo info = new CallbackInfo(handlerToEvent);
        mCallbackMap.put(klass, info);
        mHasLifecycleMethods.put(klass, hasLifecycleMethods);
        // 返回解析后的callbackInfo
        return info;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简述
  • 优化
  • 原理
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档