剖析Lifecycle源码

Lifecycle简介

lifecycle是谷歌公司开发的jetpack系列的一个组件,它主要作用是管理Android生命周期,通过该组件,我们可以实现让一个类实例监听Activity或者Fragment的生命周期,例如在MVP架构中就可以使用Lifecycle来实现P层监听V层的生命周期,相较于传统监听生命周期的方式,Lifecycle可以减少大量的侵入代码,就拿MVP架构来说,传统监听生命周期的方式主要是通过重写Activity或者Fragment的生命周期方法,并且在方法内部调用Presenter的对应方法来实现。而Lifecycle就简单多了,下面说一下Lifecycle用法;

Lifecycle用法

还是以MVP架构做示范:
Presenter:

//Presenter需要实现LifecycleObserver接口才能监听Activity的生命周期
public class Presenter implements LifecycleObserver {

    private String TAG = "presenter";

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private void onCreate(){
        Log.d(TAG,"onCreate");
    }
    
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private void onStart(){
        Log.d(TAG,"onStart");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private void onResume(){
        Log.d(TAG, "onResume: ");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    private void onPause(){
        Log.d(TAG, "onPause: ");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private void onStop(){
        Log.d(TAG, "onStop: ");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private void onDestroy(){
        Log.d(TAG, "onDestroy: ");
    }

   @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    private void onAny(LifecycleOwner owner,Lifecycle.Event event){
        Log.d(TAG, "onAny: ");
    }
}

Activity:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //通过这一行代码就能让Presenter对象监听自己的生命周期
        getLifecycle().addObserver(new Presenter());
    }
}

Lifecycle的基本用法很简单,监听Activity生命周期的对象需要实现LifecycleObserver接口,想让方法监听Activity的某个生命周期只需要加上OnLifecycleEvent注解:
该注解的value有七种取值,与Activity生命周期的对应关系如下:

  • Lifecycle.Event.ON_CREATE :onCreate;
  • Lifecycle.Event.ON_START : onStart;
  • Lifecycle.Event.ON_Resume :onResume;
  • Lifecycle.Event.ON_PAUSE :onPause;
  • Lifecycle.Event.ON_STOP :onStop;
  • Lifecycle.Event.ON_DESTROY : onDestory;
  • Lifecycle.Event.ON_ANY : Activity的所有生命周期。

而在Activity中只需调用getLifecycle().addObserver(new Presenter());即可实现让Presenter监听Activity生命周期。
下面就通过Lifecycle的源码了解其工作原理

原理剖析

Lifecycle既然能够实现多个对象同时监听Activity的生命周期,其实就很容易想到观察者设计模式,Lifecycle整体框架就是一种典型的观察者模式,其实通过其用法中频繁出现的observer就能看出来。
在进入源码之前,先要交代一下Lifecycle中的两个概念:State和Event
顾名思义,State表示状态,Event表示事件,而他们之间的关系是完成某个事件达到某个状态,StateEvent都是枚举类型,分别有5中取值和7种取值(上面讲过)

 public enum State {
  
        DESTROYED,
   
        INITIALIZED,
   
        CREATED,
    
        STARTED,
    
        RESUMED;

        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }

 public enum Event {
      
        ON_CREATE,
     
        ON_START,
   
        ON_RESUME,
     
        ON_PAUSE,
    
        ON_STOP,
      
        ON_DESTROY,
      
        ON_ANY
    }

它们之间的关系如下图所示(图源享学课堂)



接下来就正式进入源码,以这行代码为入口:

getLifecycle().addObserver(new Presenter());

getLifecycle()返回的是LifecycleRegistry的实例,LifecycleRegistryLifecycle抽象类的实现类

//mLifecycleRegistry和getLifecycle()都在ComponentActivity中
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

public Lifecycle getLifecycle() {
    return mLifecycleRegistry;
}

我们看一下LifecycleRegistry的构造函数

public LifecycleRegistry(@NonNull LifecycleOwner provider) {
    mLifecycleOwner = new WeakReference<>(provider);
    mState = INITIALIZED;
}

这个provider就是activity,因为ComponentActivity实现了LifecycleOwner接口,可以看出LifecycleRegistryactivity的引用类型为弱引用,目的是防止内存泄漏,mState表示当前的状态,初始值为INITIALIZED

addObserver会调用到LifecycleRegistryaddObserver:

public void addObserver(@NonNull LifecycleObserver observer) {
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

    if (previous != null) {
        return;
    }
    LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        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();
        targetState = calculateTargetState(observer);
    }
    if (!isReentrance) {
        sync();
    }
    mAddingObserverCounter--;
}

一步步地来看(中间会跳到其他地方,希望各位记住代码是从什么地方跳出,回来从什么地方继续)

这里传入的参数observer就是监听activity生命周期的对象(PS:后面这个observer会被作为各个方法的参数,可能会有很多变量名,我一律称为observer);
State对象initialState用来表示observer的当前初始状态;
这里会先将传进来的observerinitialState封装成一个ObserverWithState对象,
我们再看一下ObserverWithState中做了什么?

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 = getStateAfter(event);
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }

ObserverWithStateLifecycleRegistry的一个静态内部类,在构造方法中,会将initialState赋值给成员变量mState,将observer封装进一个LifecycleEventObserver对象再赋值给成员变量mLifecycleObserver,我们再看一看LifecycleEventObserver这个类:

public interface LifecycleEventObserver extends LifecycleObserver {
    void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}

它是一个接口,定义了一个onStateChanged方法
而在ObserverWithState的构造方法中,由Lifecycling.lifecycleEventObserver(observer)实现:

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);
    }
    if (isFullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
    }

    if (isLifecycleEventObserver) {
        return (LifecycleEventObserver) object;
    }

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

这里慢慢来看,首先根据observer的是LifecycleObserver的实例来看,前三个if肯定不会命中,接下来获取observerClass对象调用getObserverConstructorType(klass)获取到一个int类型的type:

    private static int getObserverConstructorType(Class<?> klass) {
        Integer callbackCache = sCallbackCache.get(klass);
        if (callbackCache != null) {
            return callbackCache;
        }
        int type = resolveObserverCallbackType(klass);
        sCallbackCache.put(klass, type);
        return type;
    }

这种代码很容易理解,首先从缓存中拿,能拿到就直接返回,否则调用resolveObserverCallbackType(klass)获取,再放入缓存,最后返回,这里是第一次执行,缓存中肯定没有,进入resolveObserverCallbackType(klass)方法:

private static int resolveObserverCallbackType(Class<?> klass) {
        // anonymous class bug:35073837
        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;
        }

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

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

我们看到这里所有的返回包括了两种值REFLECTIVE_CALLBACKGENERATED_CALLBACK,从字面意思上感觉应该和反射和生成代码有关
首先是如果klass的类名为空,则返回REFLECTIVE_CALLBACK
否则会调用generatedConstructor(klass)返回一个Constructor实例constructor,这是一个构造器,它所对应的类应该是GeneratedAdapter的子类,我们先进这个方法看一下:

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

    public static String getAdapterName(String className) {
        return className.replace(".", "_") + "_LifecycleAdapter";
    }

它根据我们传入的Observer的类名来反射获取一个类名为类名__LifecycleAdapterClass对象,比如说我这里传入的是Presenter,那么它就是要获取一个Presenter_LifecycleAdapterClass对象,如果反射获取成功,就返回它的构造器,否则返回null
接下来就要细抠一下这个Presenter_LifecycleAdapter类是怎么来的了,可能会跳得有点远。
首先这个类名是根据我们传入的observer的类名动态生成的,不可能是我们自己写的,也不可能是框架里的,那么就只有可能是编译期生成的类,首先想到的就是注解处理器(APT),可是我找遍了工程依赖的Lifecycle源码都没看到注解处理器,在buildgenerated包下也没找到Presenter_LifecycleAdapter类,直到我机缘巧合之下看到了lifecycle-compiler,然后再在工程中引入lifecycle-compiler,终于看到了里面的LifecycleProcessor

@SupportedAnnotationTypes("androidx.lifecycle.OnLifecycleEvent")
class LifecycleProcessor : AbstractProcessor() {
    override fun process(
        annotations: MutableSet<out TypeElement>,
        roundEnv: RoundEnvironment
    ): Boolean {
        val input = collectAndVerifyInput(processingEnv, roundEnv)
        writeModels(transformToOutput(processingEnv, input), processingEnv)
        return true
    }

    override fun getSupportedSourceVersion(): SourceVersion {
        return SourceVersion.latest()
    }
}

它是通过JavaPoet生成代码,可以看到它支持的注解类型是androidx.lifecycle.OnLifecycleEvent类型,那么我们就不看它是怎么生成代码的了,直接看生成的代码更直观,引入lifecycle-compiler以后再编译,可以看到generated包下出现了Presenter_LifecycleAdapter类:

public class Presenter_LifecycleAdapter implements GeneratedAdapter {
    final Presenter mReceiver;

    Presenter_LifecycleAdapter(Presenter receiver) {
        this.mReceiver = receiver;
    }

    @Override
    public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny,
                            MethodCallsLogger logger) {
        boolean hasLogger = logger != null;
        if (onAny) {
            if (!hasLogger || logger.approveCall("onAny", 4)) {
                mReceiver.onAny(owner, event);
            }
            return;
        }
        if (event == Lifecycle.Event.ON_CREATE) {
            if (!hasLogger || logger.approveCall("onCreate", 1)) {
                mReceiver.onCreate();
            }
            return;
        }
        if (event == Lifecycle.Event.ON_START) {
            if (!hasLogger || logger.approveCall("onStart", 1)) {
                mReceiver.onStart();
            }
            return;
        }
        if (event == Lifecycle.Event.ON_RESUME) {
            if (!hasLogger || logger.approveCall("onResume", 1)) {
                mReceiver.onResume();
            }
            return;
        }
        if (event == Lifecycle.Event.ON_PAUSE) {
            if (!hasLogger || logger.approveCall("onPause", 1)) {
                mReceiver.onPause();
            }
            return;
        }
        if (event == Lifecycle.Event.ON_STOP) {
            if (!hasLogger || logger.approveCall("onStop", 1)) {
                mReceiver.onStop();
            }
            return;
        }
        if (event == Lifecycle.Event.ON_DESTROY) {
            if (!hasLogger || logger.approveCall("onDestroy", 1)) {
                mReceiver.onDestroy();
            }
            return;
        }
    }
}

Presenter_LifecycleAdapter实现了GeneratedAdapter接口,而GeneratedAdapter只有一个GeneratedAdapter方法:

public interface GeneratedAdapter {
    void callMethods(LifecycleOwner source, Lifecycle.Event event, boolean onAny,
            MethodCallsLogger logger);
}

Presenter_LifecycleAdapter有一个构造函数,构造函数中只有一个Presenter类型的参数receiver,会赋值给成员常量mReceiver,而在callMethods方法中根据传入的event来调用mReceiver的各个监听生命周期方法,所以这就得保证Presenter中的监听生命周期方法必须是public,否则就会报错。
那么此时上面的Lifecycling.generatedConstructor(klass)返回的构造器就是这个类的类对象的构造器了,那么再回到Lifecycling.resolveObserverCallbackType方法,此时我会分两步走,第一步讲解通过lifecycle的APT生成
Presenter_LifecycleAdapter时的处理方式,第二步讲解项目没有依赖lifecycle的APT的处理方式,先讲第一步:

通过ATP生成类执行观察者的生命周期方法

resolveObserverCallbackType方法中的constructor肯定不为null,首先会将constructor装入一个只存一个元素的List中,再和observer的Class类型缓存入一个HashMap变量sClassToAdapters中,再返回GENERATED_CALLBACK
紧接着回到lifecycleEventObserver方法,此时会命中第四个if

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

首先从缓存中根据传入对象的类型拿到存放构造器的List,如果List里面只有一个元素,那么直接拿出来和传入的observer一起调用createGeneratedAdapter方法得到一个GeneratedAdapter接口实例generatedAdapter

    private static GeneratedAdapter createGeneratedAdapter(
            Constructor<? extends GeneratedAdapter> constructor, Object object) {
        //noinspection TryWithIdenticalCatches
        try {
            return constructor.newInstance(object);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
   }

其实就是通过构造器创建一个Presenter_LifecycleAdapter实例,此时该实例里的成员mReceiver就是observer,这个Presenter_LifecycleAdapter实例就是generatedAdapter,然后再将generatedAdapter作为参数创建一个SingleGeneratedAdapterObserver对象并返回;
我们再看一下SingleGeneratedAdapterObserver

class SingleGeneratedAdapterObserver implements LifecycleEventObserver {

    private final GeneratedAdapter mGeneratedAdapter;

    SingleGeneratedAdapterObserver(GeneratedAdapter generatedAdapter) {
        mGeneratedAdapter = generatedAdapter;
    }

    @Override
    public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        mGeneratedAdapter.callMethods(source, event, false, null);
        mGeneratedAdapter.callMethods(source, event, true, null);
    }
}

实现了LifecycleEventObserver接口,重写的方法onStateChanged中调用了两次mGeneratedAdapter.callMethods();方法,后面再说,而这个mGeneratedAdapter就是构造函数传入的generatedAdapter,可以将这个SingleGeneratedAdapterObserver对象和observer对应起来。
到这里再回到LifecycleRegistry.ObserverWithState,成员变量mLifecycleObserver就是这个SingleGeneratedAdapterObserver实例
再回到LifecycleRegistry.addObserver方法,此时第二行代码终于执行完了,接着再将ObserverWithState实例statefulObserver缓存用mObserverMap起来,mObserverMapFastSafeIterableMap类型,它的每个结点都有前驱结点和后继结点,每个新加入的结点都放在最后,更多细节就不赘述了,紧接着便是同步observer的状态,首先会调用calculateTargetState(observer);获取目标状态:

private State calculateTargetState(LifecycleObserver observer) {
        Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);

        State siblingState = previous != null ? previous.getValue().mState : null;
        State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)
                : null;
        return min(min(mState, siblingState), parentState);
}

这里先获取到mObserverMap中的最后一个观察者也就是observer的前驱结点的当前状态siblingState
然后还有一个数组变量mParentStates,如果当前有其它观察者正在分发状态(同步状态),就会存放在这个mParentStates中,数组前面的观察者状态肯定大于后面的状态,拿到数组里的最后一个元素与被观察者的当前状态以及siblingState对比,返回最小值,就是observer当前需要同步的目标状态targetState,这样做的目的应该是如果添加新的观察者的时候,正好有生命周期正在发生,而同步操作还未完成,为了安全考虑只能先将新的观察者同步到最小状态。
observer的同步操作是在一个while循环中进行的,每分发一次状态以后都会重新获取一次targetState,再将observer的当前状态与targetState比较,看是否需要同步,最终所有的观察者都会进入同一状态。
再看一下observer分发状态的过程:

statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));

upEvent方法是根据observer当前的状态推出observer接下来的Event,规律我在前面的图中已经展示:

 private static Event upEvent(State state) {
        switch (state) {
            case INITIALIZED:
            case DESTROYED:
                return ON_CREATE;
            case CREATED:
                return ON_START;
            case STARTED:
                return ON_RESUME;
            case RESUMED:
                throw new IllegalArgumentException();
        }
        throw new IllegalArgumentException("Unexpected state value " + state);
}

调用到ObserverWithStatedispatchEvent方法:

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

可以看到,现根据event推导出接下来的state,调用mLifecycleObserver.onStateChanged(owner, event);以后再修改observer的当前状态;
根据上面的解读过程,observer所对应的mLifecycleObserverSingleGeneratedAdapterObserver的实例,而在该实例的onStateChanged方法中调用了两次mGeneratedAdaptercallMethods方法,一次onAny参数值为false,一次为true,这个mGeneratedAdapterPresenter_LifecycleAdapter的实例,onAny参数值为false时最终会根据event执行mReceiver也就是observer的对应生命周期方法,onAny参数值为false时则会执行onAny方法。
这就是将观察者添加到Lifecycle以后,观察者同步自己的状态再分发执行自己的对用生命周期的过程。
接下来再进入第二步,看是如何通过反射来分发执行观察者的对应生命周期方法的。

通过反射执行观察者生命周期方法

我们还是得先回到Lifecycling.resolveObserverCallbackType方法,如果没有引入Lifecycle的APT,那么就不会生成Presenter_LifecycleAdapter类,那么该方法中的constructor值也一定为null,接下来就会执行:

  boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);

从字面上来理解ClassesInfoCache.sInstance.应该是一个单例,hasLifecycleMethods(klass)返回一个boolean类型的值作用应该是判断klass是否有生命周期方法,点进去:

 boolean hasLifecycleMethods(Class klass) {
        Boolean hasLifecycleMethods = mHasLifecycleMethods.get(klass);
        if (hasLifecycleMethods != null) {
            return hasLifecycleMethods;
        }

        Method[] methods = getDeclaredMethods(klass);
        for (Method method : methods) {
            OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
            if (annotation != null) {
                createInfo(klass, methods);
                return true;
            }
        }
        mHasLifecycleMethods.put(klass, false);
        return false;
    }

这种形式的代码前面已经见到过一次了,先从缓存里拿,拿不到就调用相关方法获取,再存入缓存,这里是反射拿到klass的所有方法以后,再遍历获取方法上的注解,如果有OnLifecycleEvent注解则说明klass有生命周期方法,执行createInfo(klass, methods)以后返回true,再看一下createInfo(klass, methods)中做了什么:

private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
        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()) {
                verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
            }
        }

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

            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");
            }
            MethodReference methodReference = new MethodReference(callType, method);
            verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
        }
        CallbackInfo info = new CallbackInfo(handlerToEvent);
        mCallbackMap.put(klass, info);
        mHasLifecycleMethods.put(klass, hasLifecycleMethods);
        return info;
    }

这里首先创建了一个HashMap变量handlerToEvent,它是用来存储方法和生命周期的对应关系的,接下来对它的父类及接口的一些操作主要就是获取到其父类以及接口的handlerToEvent,再合并到自己的handlerToEvent
,先往下看,首先是判断如果传入的方法数组是为空就反射获取,接着遍历所有的方法,如果方法上面有OnLifecycleEvent注解则反射获取方法的参数个数和类型,根据个数和类型来确定方法的callType,这里对方法的参数个数以及类型要求很严格,规则如下:

  • 如果参数长度为0,callType= CALL_TYPE_NO_ARG

  • 如果参数长度大于0,那么第一个参数类型必须为LifecycleOwner,否则抛出异常;

  • 如果参数长度为1,则callType = CALL_TYPE_PROVIDER;

  • 如果参数长度为2,则callType = CALL_TYPE_PROVIDER,第二个参数必须为Lifecycle.Event类型,且OnLifecycleEvent注解的value值不能为Lifecycle.Event.ON_ANY,否则抛出异常;

  • 如果参数长度大于2,则直接抛出异常。

接着就会将callTypemethod封装到一个MethodReference对象中,调用verifyAndPutHandler方法:

    private void verifyAndPutHandler(Map<MethodReference, Lifecycle.Event> handlers,
            MethodReference newHandler, Lifecycle.Event newEvent, Class klass) {
        Lifecycle.Event event = handlers.get(newHandler);
        if (event != null && newEvent != event) {
            Method method = newHandler.mMethod;
            throw new IllegalArgumentException(
                    "Method " + method.getName() + " in " + klass.getName()
                            + " already declared with different @OnLifecycleEvent value: previous"
                            + " value " + event + ", new value " + newEvent);
        }
        if (event == null) {
            handlers.put(newHandler, newEvent);
        }
    }

这里主要是做一些容错处理,排除一些重复添加的情况,比如说父类中已经加入该方法了,在子类中有加入一次,这时就会抛出异常。确认没错以后就将这个MethodReference对象添加到handlerToEvent中,遍历完所有的方法以后就会将handlerToEvent封装进一个CallbackInfo对象中去,再将该对象缓存起来,一个klass对应一个CallbackInfo对象。
再回到Lifecycling.resolveObserverCallbackType方法,hasLifecycleMethodstrue则返回REFLECTIVE_CALLBACK,再回到lifecycleEventObserver方法,四个if都不会被命中,最后则返回一个ReflectiveGenericLifecycleObserver对象,看一下这个类的成员属性以及构造方法:

private final Object mWrapped;
    private final CallbackInfo mInfo;

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

它保存了observer以及observer对应的CallbackInfo对象。
这时LifecycleRegistry.ObserverWithState对象里面的mLifecycleObserver就是这个ReflectiveGenericLifecycleObserver对象,当observer同步状态的时候就会执行ReflectiveGenericLifecycleObserver对象的onStateChanged方法:

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

执行了CallbackInfoinvokeCallbacks方法,直接看整个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);
                }
            }
        }
    }

首先看它的构造函数,它将我们传入的handlerToEvent,转化了一下,之前是<MethodReference, Lifecycle.Event>的存储方式,转化成<Lifecycle.Event, List<MethodReference>>的存储方式;在invokeCallbacks中执行了两次invokeMethodsForEvent方法,首先是拿到生命周期所对应的所有MethodReference对象,调用其invokeCallback方法:

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

这里就是根据方法的mCallType来选择反射执行observer的的方法。

至此,添加观察者之后,观察者如何同步自己的状态以及如何调用观察者的生命周期方法已经全部看完了,
至于这两种方式从性能上来讲肯定是第一种更优,毕竟后者是通过反射执行的,不过第一种要求相对严苛,比如要求观察者生命周期方法必须是public的,需要引入额外的依赖,这是一种典型的以空间换时间。
接下来就看看被观察者生命周期改变时是如何分发给观察者的。

生命周期的分发

首先进入ComponentActivity,看一下它的onCreate生命周期:

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSavedStateRegistryController.performRestore(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
        if (mContentLayoutId != 0) {
            setContentView(mContentLayoutId);
        }
    }

有一行重要的代码ReportFragment.injectIfNeededIn(this),再进入ReportFragment类中看一下这个方法:

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

看到这里,如果之前看过其他开源框架如glide的源码,应该就能大致猜到是怎么一回事了,这里就是新建了一个没有界面的Fragment,宿主Activity生命周期变化时,Fragment的生命周期也会发生变化,再在Fragment的对应生命周期中将事件分发给观察者们,比如随便看一个onResume生命周期:

@Override
    public void onResume() {
        super.onResume();
        dispatchResume(mProcessListener);
        dispatch(Lifecycle.Event.ON_RESUME);
    }

主要看这个dispatch(Lifecycle.Event.ON_RESUME):

  private void dispatch(Lifecycle.Event event) {
        Activity activity = getActivity();
        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);
            }
        }
    }

最后会调用LifecycleRegistry..handleLifecycleEvent(event)方法:

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

它会根据event获取到需要进入的状态next,再将当前状态mState的值改为next在执行moveToState方法同步到该状态:

    private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        sync();
        mHandlingEvent = false;
    }

里面会执行sync方法:

 private void sync() {
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
                    + "garbage collected. It is too late to change lifecycle state.");
        }
        while (!isSynced()) {
            mNewEventOccurred = false;
            // no need to check eldest for nullability, because isSynced does it for us.
            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;
    }

这里首先会做一些容错处理,然后会通过while循环判断观察者状态是否已经同步,判断函数是isSynced

    private boolean isSynced() {
        if (mObserverMap.size() == 0) {
            return true;
        }
        State eldestObserverState = mObserverMap.eldest().getValue().mState;
        State newestObserverState = mObserverMap.newest().getValue().mState;
        return eldestObserverState == newestObserverState && mState == newestObserverState;
    }

mObserverMap中第一个观察者的状态,最后一个观察者的状态,以及mState进行比较,如果相等的话就说明当前状态已经同步,否则就会进入while循环,在循环中,首先如果mObserverMap中第一个观察者的状态大于当前状态mState,就会执行backwardPass将所有的观察者的状态往回推(状态回退),具体规则前面的图中有展示,先如果mObserverMap中最后一个观察者的状态小于于当前状态mState,就会执行forwardPass将所有的观察者的状态往前推(状态前进),为什么是这样呢,先看一下backwardPass做了什么:

 private void backwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
                mObserverMap.descendingIterator();
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                Event event = downEvent(observer.mState);
                pushParentState(getStateAfter(event));
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
 }

可以看到,这里通过迭代器将mObserverMap的观察者依次取出,再通过downEvent得到观察者当前状态回退的所需要执行的event,再分发该event来执行观察者的对应生命周期方法。不过这里的迭代器是从后往前取的,第一个观察者的状态是最后同步的,所以如果第一个观察者的状态同步了那么其他的观察者状态也就一定同步了,所以'sync'方法的while循环中会拿第一个观察者的状态和当前状态比较,而forwardPass也是如此:

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

这里的迭代器是从前往后取的,在依次拿到观察者状态前推多需要执行的event,再分发event来执行观察者对应的生命周期方法。
这就是Lifecycle中被观察者生命周期发生变化以后分发给观察者的过程,ReportFragment类是在lifecycle-runtime依赖文件下的,不过我这里是2.1.0的版本,我看了下2.2.0的版本又有了变化,injectIfNeededIn方法中在创建Fragment之前会先判断如果当前Android版本大于29,就会先执行这样一行代码:

 activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());

再看一下LifecycleCallbacks类:

 static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
        @Override
        public void onActivityCreated(@NonNull Activity activity,
                @Nullable Bundle bundle) {
        }

        @Override
        public void onActivityPostCreated(@NonNull Activity activity,
                @Nullable Bundle savedInstanceState) {
            dispatch(activity, Lifecycle.Event.ON_CREATE);
        }

        @Override
        public void onActivityStarted(@NonNull Activity activity) {
        }

        @Override
        public void onActivityPostStarted(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_START);
        }

        @Override
        public void onActivityResumed(@NonNull Activity activity) {
        }

        @Override
        public void onActivityPostResumed(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_RESUME);
        }

        @Override
        public void onActivityPrePaused(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_PAUSE);
        }

        @Override
        public void onActivityPaused(@NonNull Activity activity) {
        }

        @Override
        public void onActivityPreStopped(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_STOP);
        }

        @Override
        public void onActivityStopped(@NonNull Activity activity) {
        }

        @Override
        public void onActivitySaveInstanceState(@NonNull Activity activity,
                @NonNull Bundle bundle) {
        }

        @Override
        public void onActivityPreDestroyed(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_DESTROY);
        }

        @Override
        public void onActivityDestroyed(@NonNull Activity activity) {
        }
    }

其实就是向activity注册一个生命周期回调,也是一种观察者模式,当activity生命周期发生变化时会通知所有的callbackcallback会回调自己的对应生命周期方法,而这里的LifecycleCallbacks又会执行dispatch方法将事件分发给Lifecycle的所有观察者。而dispatch方法又发生了改变:

    private void dispatch(@NonNull Lifecycle.Event event) {
        if (Build.VERSION.SDK_INT < 29) {
            // Only dispatch events from ReportFragment on API levels prior
            // to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks
            // added in ReportFragment.injectIfNeededIn
            dispatch(getActivity(), event);
        }
 }

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

所以当Android版本低于29的时候,才会通过fragment来分发生命周期,高于29时就通过activity生命周期回调来分发了。

以上就是Lifecycle工作的基本流程和原理,如果有什么不正确的地方欢迎指正。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,362评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,330评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,247评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,560评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,580评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,569评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,929评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,587评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,840评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,596评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,678评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,366评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,945评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,929评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,165评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,271评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,403评论 2 342