Lifecycle原理

1、原理解析

1.1 从注册观察者的入口方法开始

1.1.1 LifecycleOwner
/**
 * 接口,用来获取Lifecycle对象
 */
public interface LifecycleOwner {
    @NonNull
    Lifecycle getLifecycle();
}
1.1.2 ComponentActivity、androidx包中的Fragment自身实现了LifecycleOwner接口,并创建了继承了Lifecycle类的LifecycleRegistry对象,lifecycleOwner.getLifecycle()获取的就是LifecycleRegistry对象,通过LifecycleRegistry来进行注册和反注册观察者
 lifecycleOwner.getLifecycle().addObserver(this);
1.1.3 Lifecycle
/**
 * 抽象类,提供注册/反注册方法和记录组件生命周期事件和状态的枚举
 */
 public abstract class Lifecycle {
    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);

    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);

    @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;

        /**
         * DESTROYED<INITIALIZED<CREATED<STARTED<RESUMED
         */
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }
}

1.1.4 LifecycleRegistry
public class LifecycleRegistry extends Lifecycle {

    /**
     * 是一个可以在遍历中删除数据的链表,用来保存ObserverWithState
     */
    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();

 	/**
     *  注册观察者的地方
     */
    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
    	//是否是在主线程,不是,抛异常,终止。
        enforceMainThreadIfNeeded("addObserver");
        //新注册的观察者的 initialState 一般是INITIALIZED
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        //LifecycleObserver 和 State 创建ObserverWithState对象
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        //查看要注册的观察者是否已经存在,存在,终止,不存在,添加到mObserverMap中。
        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;
	    }
	    // 下面的逻辑就是:把之前优先分发的事件,一个个分发给后添加的观察者
	    // 比如在Activity的onResume生命周期中调用LifecycleRegistry.addObserver的时候
	    // 因为新添加的statefulObserver的mState为INITIALIZED
	    // 而targetState已经发生了变化,在LifecycleRegistry中的mState变成了RESUMED
	    // 这里就会满足小于0的条件,并且在map中也有了新加入的这个Observer
	    // 分发一次之后,就会改变targetState的值,如果新的值还是比当前的大,则继续分发
	    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--;
    }

    @Override
    public void removeObserver(@NonNull LifecycleObserver observer) {
        enforceMainThreadIfNeeded("removeObserver");
        mObserverMap.remove(observer);
    }
}

1.2 ComponentActivity

ComponentActivity 实现了LifecycleOwner接口,内部创建了继承Lifecycle类的LifecycleRegistry,add一个空的ReportFragment,并通过ReportFragment来分管理生命周期事件

public class ComponentActivity extends Activity implements LifecycleOwner {

    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    @SuppressLint("RestrictedApi")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
    }
    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

1.3 ReportFragment 在对应的生命周期方法中分发事件,最后其实是调用LifecycleRegistry的handleLifecycleEvent方法来分发事件

ReportFragment

public class ReportFragment extends android.app.Fragment {
  
    public static void injectIfNeededIn(Activity activity) {
    	//Sdk >= 29的时候会,通过Application.ActivityLifecycleCallbacks来监听
    	//生命周期方法分发事件,具体的自己可以去看一下,这也是我们上面例子,代码中打出的log
    	//页面中的onPause、onStop、onDestory 后调用的原因
        if (Build.VERSION.SDK_INT >= 29) {
            LifecycleCallbacks.registerIn(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();
        }
    }

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

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

    private void dispatch(@NonNull Lifecycle.Event event) {
        if (Build.VERSION.SDK_INT < 29) {
            dispatch(getActivity(), event);
        }
    }

      @SuppressWarnings("deprecation")
    static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
        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);
            }
        }
    }
}

1.4 LifecycleRegistry 对事件进行分发,最后会调用子类ObserverWithState的dispatchEvent()

public class LifecycleRegistry extends Lifecycle {

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        enforceMainThreadIfNeeded("handleLifecycleEvent");
        moveToState(event.getTargetState());
    }
    
 	private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            return;
        }
        mHandlingEvent = true;
        sync();
        mHandlingEvent = false;
    }
    
    // 把生命周期状态同步给所有观察者
 	private void sync() {
 		...
        while (!isSynced()) {
            mNewEventOccurred = false;
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
            Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }
    
    //正序遍历,分发事件
   private void forwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
            Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                pushParentState(observer.mState);
                final Event event = Event.upFrom(observer.mState);
                if (event == null) {
                    throw new IllegalStateException("no event up from " + observer.mState);
                }
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }
      //倒序遍历,分发事件
	 private void backwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
                mObserverMap.descendingIterator();
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Map.Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                Event event = Event.downFrom(observer.mState);
                if (event == null) {
                    throw new IllegalStateException("no event down from " + observer.mState);
                }
                pushParentState(event.getTargetState());
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }

	//最后会调用ObserverWithState的dispatchEvent来分发事件
	static class ObserverWithState {
        State mState;
        LifecycleEventObserver mLifecycleObserver;

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

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

1.5 ObserverWithState的dispatchEvent 方法分发事件过程解析

ObserverWithState对象创建的时候,会通过Lifecycling.lifecycleEventObserver(observer)方法创建一个LifecycleEventObserver对象,事件分发的dispatchEvent()方法中最终也是调用了
LifecycleEventObserver对象的onStateChanged方法

	//LifecycleRegistry 子类
	static class ObserverWithState {
        State mState;
        LifecycleEventObserver mLifecycleObserver;

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

        void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = event.getTargetState();
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }
public interface LifecycleEventObserver extends LifecycleObserver {
    /**
     * Called when a state transition event happens.
     *
     * @param source The source of the event
     * @param event The event
     */
    void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}

看一下Lifecycling类的lifecycleEventObserver方法

    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);
        }
         //如果观察者是通过FullLifecycleObserver接口实现的,接口回调出发事件
        if (isFullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
        }
        //如果观察者是通过LifecycleEventObserver接口实现的,接口回调出发事件
        if (isLifecycleEventObserver) {
            return (LifecycleEventObserver) object;
        }
		
		//如果是LifecycleObserver接口+注解形式实现
		//反射来判断类型
		//如果是GENERATED_CALLBACK类型,根据constructors数据的size来判断是
		//返回SingleGeneratedAdapterObserver 或 CompositeGeneratedAdaptersObserver
		//否则返回ReflectiveGenericLifecycleObserver
        final Class<?> klass = object.getClass();
        int type = getObserverConstructorType(klass);
        if (type == GENERATED_CALLBACK) {
            List<Constructor<? extends GeneratedAdapter>> 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.如果观察者实现的是FullLifecycleObserver接口,会返回FullLifecycleObserverAdapter对象,最终调用FullLifecycleObserverAdapter的onStateChanged方法,并通过接口回掉来处理事件

interface FullLifecycleObserver extends LifecycleObserver {

    void onCreate(LifecycleOwner owner);

    void onStart(LifecycleOwner owner);

    void onResume(LifecycleOwner owner);

    void onPause(LifecycleOwner owner);

    void onStop(LifecycleOwner owner);

    void onDestroy(LifecycleOwner owner);
}
class FullLifecycleObserverAdapter implements LifecycleEventObserver {

    private final FullLifecycleObserver mFullLifecycleObserver;
    private final LifecycleEventObserver mLifecycleEventObserver;

    FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,
            LifecycleEventObserver lifecycleEventObserver) {
        mFullLifecycleObserver = fullLifecycleObserver;
        mLifecycleEventObserver = lifecycleEventObserver;
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        switch (event) {
            case ON_CREATE:
                mFullLifecycleObserver.onCreate(source);
                break;
            case ON_START:
                mFullLifecycleObserver.onStart(source);
                break;
            case ON_RESUME:
                mFullLifecycleObserver.onResume(source);
                break;
            case ON_PAUSE:
                mFullLifecycleObserver.onPause(source);
                break;
            case ON_STOP:
                mFullLifecycleObserver.onStop(source);
                break;
            case ON_DESTROY:
                mFullLifecycleObserver.onDestroy(source);
                break;
            case ON_ANY:
                throw new IllegalArgumentException("ON_ANY must not been send by anybody");
        }
        if (mLifecycleEventObserver != null) {
            mLifecycleEventObserver.onStateChanged(source, event);
        }
    }
}

2.如果观察者实现的是LifecycleEventObserver接口那么直接返回,并调用onStateChanged()方法通过接口回调来分发事件,这种方式在ComponentActivity类中有实现,如下:

 public ComponentActivity() {
        Lifecycle lifecycle = getLifecycle();
        ...
        if (Build.VERSION.SDK_INT >= 19) {
            getLifecycle().addObserver(new LifecycleEventObserver() {
                @Override
                public void onStateChanged(@NonNull LifecycleOwner source,
                        @NonNull Lifecycle.Event event) {
                    if (event == Lifecycle.Event.ON_STOP) {
                        Window window = getWindow();
                        final View decor = window != null ? window.peekDecorView() : null;
                        if (decor != null) {
                            decor.cancelPendingInputEvents();
                        }
                    }
                }
            });
        }
        getLifecycle().addObserver(new LifecycleEventObserver() {
            @Override
            public void onStateChanged(@NonNull LifecycleOwner source,
                    @NonNull Lifecycle.Event event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    // Clear out the available context
                    mContextAwareHelper.clearAvailableContext();
                    // And clear the ViewModelStore
                    if (!isChangingConfigurations()) {
                        getViewModelStore().clear();
                    }
                }
            }
        });
        getLifecycle().addObserver(new LifecycleEventObserver() {
            @Override
            public void onStateChanged(@NonNull LifecycleOwner source,
                    @NonNull Lifecycle.Event event) {
                ensureViewModelStore();
                getLifecycle().removeObserver(this);
            }
        });
    }

3.如果观察者的实现方式不是继承的上面的两个接口,而是通过LifecycleObserver接口+注解的
方式实现的话,就会走到下面的逻辑。
首先根据反射判断是什么type,type定义了两种

public class Lifecycling {
    private static final int REFLECTIVE_CALLBACK = 1;
    private static final int GENERATED_CALLBACK = 2;
    
 	private static Map<Class<?>, Integer> sCallbackCache = new HashMap<>();
    private static Map<Class<?>, List<Constructor<? extends GeneratedAdapter>>> sClassToAdapters =
            new HashMap<>();
}

方法getObserverConstructorType()返回的type若等于GENERATED_CALLBACK则会采用SingleGeneratedAdapterObserver或者CompositeGeneratedAdaptersObserver来实现观察者,这个方法有是通过resolveObserverCallbackType()来解析type的:

 private static int getObserverConstructorType(Class<?> klass) {
 		//看Map中是否已经有这个类的类型,有直接返回
        Integer callbackCache = sCallbackCache.get(klass);
        if (callbackCache != null) {
            return callbackCache;
        }
        //没有,判断是什么类型并保存到map中
        int type = resolveObserverCallbackType(klass);
        sCallbackCache.put(klass, type);
        return type;
    }

上面函数主要是在判断该观察者对象是否有相应的GeneratedAdapter类生成,是通过generatedConstructor方法实现的,若有相应的GeneratedAdapter类生成,则通过反射生成相应的构造器:

private static int resolveObserverCallbackType(Class<?> klass) {
        // 1.根据本类klass对象来判断是否有APT生成相应的GeneratedAdapter对象
        if (klass.getCanonicalName() == null) {
            return REFLECTIVE_CALLBACK;
        }

        Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
        if (constructor != null) {
            sClassToAdapters.put(klass, Collections
                    .<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
            return GENERATED_CALLBACK;
        }

        boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
        if (hasLifecycleMethods) {
            return REFLECTIVE_CALLBACK;
        }
		// 2.根据父类superclass对象来判断是否有APT生成相应的GeneratedAdapter对象
        Class<?> superclass = klass.getSuperclass();
        List<Constructor<? extends GeneratedAdapter>> adapterConstructors = null;
        if (isLifecycleParent(superclass)) {
            if (getObserverConstructorType(superclass) == REFLECTIVE_CALLBACK) {
                return REFLECTIVE_CALLBACK;
            }
            adapterConstructors = new ArrayList<>(sClassToAdapters.get(superclass));
        }
		//3.根据其实现接口来判断是否有APT生成相应的GeneratedAdapter对象
        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;
    }
private static Constructor<? extends GeneratedAdapter> generatedConstructor(Class<?> klass) {
        try {
            Package aPackage = klass.getPackage();
            String name = klass.getCanonicalName();
            final String fullPackage = aPackage != null ? aPackage.getName() : "";
            final String adapterName = getAdapterName(fullPackage.isEmpty() ? name :
                    name.substring(fullPackage.length() + 1));

            @SuppressWarnings("unchecked") final Class<? extends GeneratedAdapter> aClass =
                    (Class<? extends GeneratedAdapter>) Class.forName(
                            fullPackage.isEmpty() ? adapterName : fullPackage + "." + adapterName);
            Constructor<? extends GeneratedAdapter> constructor =
                    aClass.getDeclaredConstructor(klass);
            if (!constructor.isAccessible()) {
                constructor.setAccessible(true);
            }
            return constructor;
        } catch (ClassNotFoundException e) {
            return null;
        } catch (NoSuchMethodException e) {
            // this should not happen
            throw new RuntimeException(e);
        }
    }

调用GeneratedAdapter的callMethods()的方法来进行事件分发。

@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
public interface GeneratedAdapter {

    /**
     * Called when a state transition event happens.
     *
     * @param source The source of the event
     * @param event The event
     * @param onAny approveCall onAny handlers
     * @param logger if passed, used to track called methods and prevent calling the same method
     *              twice
     */
    void callMethods(LifecycleOwner source, Lifecycle.Event event, boolean onAny,
            MethodCallsLogger logger);
}

其实,调用resolveObserverCallbackType()方法,该过程中已经生成了相应GeneratedAdapter的构造器,并返回一个SingleGeneratedAdapterObserver对象或CompositeGeneratedAdaptersObserver对象,在SingleGeneratedAdapterObserver中onStateChanged()方法中调用相应GeneratedAdapter对象的callMethods()来分发生命周期事件(通过Apt生成一个相应的Adapter对象,最后调用这个对象的callMethods的方法)。

4.以上情况都不是,最后会返回ReflectiveGenericLifecycleObserver对象,并调用LifecycleObserver.onStateChanged(owner, event)方法 。
创建CallBackInfo时候,通过反射来解析具有OnLifecycleEvent注解的方法,最后通过CallBackInfo.invokeCallbacks 反射调用注解方法

ReflectiveGenericLifecycleObserver

class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;
    private final CallbackInfo mInfo;

    ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }

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

CallbackInfo对象的创建过程

private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) {
		//1.递归解析父类
        Class<?> superclass = klass.getSuperclass();
        Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
        if (superclass != null) {
        	//因为会有多重继承,因此会递归解析父类,getInfo()方法还会调用createInfo()方法
            CallbackInfo superInfo = getInfo(superclass);
            if (superInfo != null) {
                handlerToEvent.putAll(superInfo.mHandlerToEvent);
            }
        }
		//2.递归解析接口。Java中接口也可以继承,这里getInterfaces()方法处理两种情况:a. klass对应一个类,b. kclass对应一个接口
        Class<?>[] interfaces = klass.getInterfaces();
        for (Class<?> intrfc : interfaces) {
            for (Map.Entry<MethodReference, Lifecycle.Event> entry : getInfo(
                    intrfc).mHandlerToEvent.entrySet()) {
                //接口中解析的方法可能与父类中解析的是重复定义的,会做去重后再添加到handlerToEvent中
                verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
            }
        }
		//3. 解析本类对象具有OnLifecycleEvent注解的方法
        Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
        boolean hasLifecycleMethods = false;
        for (Method method : methods) {
            OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
            if (annotation == null) {
                continue;
            }
            hasLifecycleMethods = true;
            Class<?>[] params = method.getParameterTypes();
            //OnLifecycleEvent注解的方法最多允许两个Event参数,定义参数超过两个会抛出异常
            int callType = CALL_TYPE_NO_ARG;
            if (params.length > 0) {
                callType = CALL_TYPE_PROVIDER;
                //第一个参数类型期望为LifecycleOwner类型
                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;
                //第二个参数类型期望为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);
            //去重添加到handlerToEvent中
            verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
        }
        CallbackInfo info = new CallbackInfo(handlerToEvent);
        mCallbackMap.put(klass, info);
        mHasLifecycleMethods.put(klass, hasLifecycleMethods);
        return info;
    }

CallbackInfo通过反射调用注解方法

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

     
    }

上面这些是根据ComponentActivity的实现方式来分析的,Fragment的实现方式与之类似,却别就是没有用ReportFragment来管理事件的分发,而是在对应的生命周期方法中通过LifecycleRegistry直接来分发的。

总结

关键类和接口

1.1 、Lifecycle
用于有关组件(如 Activity 或 Fragment)的生命周期状态的信息,并允许其他对象观察此状态。

1.2、LifecycleOwner :
实现该接口的类持有生命周期(Lifecycle对象),该接口的生命周期(Lifecycle对象)的改变会被其注册的观察者LifecycleObserver观察到并触发其对应的事件。

1.3、LifecycleObserver:
实现该接口的类,通过注解的方式,可以通过被LifecycleOwner类的addObserver(LifecycleObserver o)方法注册,被注册后,LifecycleObserver便可以观察到LifecycleOwner的生命周期事件。

1.4、LifecycleRegistry:
Lifecycle的具体实现类,注册和反注册观察者,并进行事件的分发。

1.5、ObserverWithState:
持有观察者,并进行事件分发

1.6、Lifecycling:
处理具体的分发事件逻辑。

原理概括

Activity/Fragment实现LifecycleOwner接口,通过LifecycleRegistry在对应生命周期分发事件,最后回调观察者中对应订阅方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值