Lifecycle原理分析

简述

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 , 用于监听生命周期
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
@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 : 会回调根据注释标注的方法
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> 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
 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
                    .>singletonList(constructor));
            return GENERATED_CALLBACK;
        }
        // 判断是否有lifecycle的函数
        boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
        if (hasLifecycleMethods) {
            return REFLECTIVE_CALLBACK;
        }

        Class> superclass = klass.getSuperclass();
        List> 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
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 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()) {
                // 校验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;
    }

文章来源于互联网:Lifecycle原理分析

阅读全文
下载说明:
1、本站所有资源均从互联网上收集整理而来,仅供学习交流之用,因此不包含技术服务请大家谅解!
2、本站不提供任何实质性的付费和支付资源,所有需要积分下载的资源均为网站运营赞助费用或者线下劳务费用!
3、本站所有资源仅用于学习及研究使用,您必须在下载后的24小时内删除所下载资源,切勿用于商业用途,否则由此引发的法律纠纷及连带责任本站和发布者概不承担!
4、本站站内提供的所有可下载资源,本站保证未做任何负面改动(不包含修复bug和完善功能等正面优化或二次开发),但本站不保证资源的准确性、安全性和完整性,用户下载后自行斟酌,我们以交流学习为目的,并不是所有的源码都100%无错或无bug!如有链接无法下载、失效或广告,请联系客服处理!
5、本站资源除标明原创外均来自网络整理,版权归原作者或本站特约原创作者所有,如侵犯到您的合法权益,请立即告知本站,本站将及时予与删除并致以最深的歉意!
6、如果您也有好的资源或教程,您可以投稿发布,成功分享后有站币奖励和额外收入!
7、如果您喜欢该资源,请支持官方正版资源,以得到更好的正版服务!
8、请您认真阅读上述内容,注册本站用户或下载本站资源即您同意上述内容!
原文链接:https://www.shuli.cc/?p=17024,转载请注明出处。
0

评论0

显示验证码
没有账号?注册  忘记密码?