美文网首页
Lifecycle用法与解析

Lifecycle用法与解析

作者: 沈杰3 | 来源:发表于2018-03-21 17:51 被阅读0次

    Android Architecture Component -- Lifecycle 浅析

    LifecycleAndroid Architecture Components 的一个组件,用于将系统组件(Activity、Fragment等等)的生命周期分离到 Lifecycle 类,Lifecycle 允许其他类作为观察者,观察组件生命周期的变化。

    public class LifecycleObserverDemo implements LifecycleObserver {
    
        @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
        void onAny(LifecycleOwner owner, Lifecycle.Event event) {
            System.out.println("onAny:" + event.name());
        }
        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        void onCreate() {
            System.out.println("onCreate");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        void onDestroy() {
            System.out.println("onDestroy");
        }
    }
    
    

    然后在 LifecycleRegistryOwner 比如 LifecycleActivity 加入这么一行代码:

        getLifecycle().addObserver(new LifecycleObserverDemo());
    

    然后?然后就没了,运行起来可以看到 LifecycleActivity 的生命周期发生变化时,LifecycleObserverDemo 总能得到通知。而 LifecycleActivity 只有寥寥几行代码,并没有覆盖任何回调方法。那么 Lifecycle 是怎么做到的,是不是有点黑魔法的感觉?

    代码解析

    FragmentActivity继承自SupportActivity

    ReportFragment

    ReportFragment的主要作用是:

    1. 生命周期中分发各个Lifecycle.Event, 到FragmentActivity
      dispatch(Lifecycle.Event.ON_CREATE);

    在SupportActivity.onCreate中加入ReportFragment

        @Override
        @SuppressWarnings("RestrictedApi")
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ReportFragment.injectIfNeededIn(this);
        }
    
    .......
    
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            dispatchCreate(mProcessListener);
            dispatch(Lifecycle.Event.ON_CREATE);//Event.ON_CREATE是在onActivityCreated之后才发送的,其他还是在生命周期中发送
        }
    
        @Override
        public void onStart() {
            super.onStart();
            dispatchStart(mProcessListener);
            dispatch(Lifecycle.Event.ON_START);
        }
    
        @Override
        public void onResume() {
            super.onResume();
            dispatchResume(mProcessListener);
            dispatch(Lifecycle.Event.ON_RESUME);
        }
    
        @Override
        public void onPause() {
            super.onPause();
            dispatch(Lifecycle.Event.ON_PAUSE);
        }
    
        @Override
        public void onStop() {
            super.onStop();
            dispatch(Lifecycle.Event.ON_STOP);
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            dispatch(Lifecycle.Event.ON_DESTROY);
            // just want to be sure that we won't leak reference to an activity
            mProcessListener = null;
        }
    .......
    
    
    

    注意RecordFragment控制的是FragmentActivity的生命周期,对于其中的其他的Fragment,在Fragment中有mLifecycleRegistry变量来控制,代码如下:

        void performCreate(Bundle savedInstanceState) {
            if (mChildFragmentManager != null) {
                mChildFragmentManager.noteStateNotSaved();
            }
            mState = CREATED;
            mCalled = false;
            onCreate(savedInstanceState);
            mIsCreated = true;
            if (!mCalled) {
                throw new SuperNotCalledException("Fragment " + this
                        + " did not call through to super.onCreate()");
            }
            mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        }
    
    

    addObserver, 注册

    LifecycleRegistry.java 重点类,Observer管理,event关于与分发

        @Override
        public void addObserver(@NonNull LifecycleObserver observer) {
            State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
            ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); //反射出observer中的注解为@OnLifecycleEvent的方法,并初始化Observer的状态INITIALIZED. 整个反射的过程,请查看ReflectiveGenericLifecycleObserver,ClassesInfoCache.createInfo
            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--;
        }
    
    
    .........
    
     /**
         * Sets the current state and notifies the observers.
         * <p>
         * Note that if the {@code currentState} is the same state as the last call to this method,
         * calling this method has no effect.
         *
         * @param event The event that was received
         */
        public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
            State next = getStateAfter(event);
            moveToState(next);
        }
    
    ...........
    
    
    

    ObserverWithState.java,Observer和state组成的类,在LifecycleRegistry中会调用observer.dispatchEvent

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

    ClassInfoCache.java CallbackInfo,通过反射获取event和method,并建立缓存,最终会根据传进来的event,调用对应的方法。

      @SuppressWarnings("WeakerAccess")
        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()) {
                    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);
                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);
                    }
                }
            }
        }
    
    //MethodReference
     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);
                }
            }
    
    

    相关文章

      网友评论

          本文标题:Lifecycle用法与解析

          本文链接:https://www.haomeiwen.com/subject/liiiqftx.html