Android Lifecycle源码解析

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android Lifecycle源码解析相关的知识,希望对你有一定的参考价值。

参考技术A

 Lifecycle是生命周期的意思。它是Jetpack中的一个 生命周期感知型组件 ,可执行操作来感知响应另一个组件(如 Activity 和 Fragment)的生命周期状态的变化。

 1.第一步添加依赖

 2.实现LifecycleObserver接口以及添加注解

 3.在Activity中或者Fragment中调用lifecycle.addObserver方法,把LifecycleObserver传入进去就可以

使用是不是很简单,在MytViewModelLifecycle里面就可以监听到Activity中或者Fragment生命周期了

 1.首先分析lifecycle怎么来的
  lifecycle调用的是ComponentActivity的getLifecycle方法,返回了一个mLifecycleRegistry

那么我们就从ComponentActivity入手会实现了它LifecycleOwner接口,并且初始化了LifecycleRegistry

  2.addObserver分析
  上面了解了lifecycle的实例,那么我们就从LifecycleRegistry入手,首先看addObserver方法,我们只管传入的参数哪里去了,也就是说我们只需要看ObserverWithState做了什么事.
  ObserverWithState会调用Lifecycling.lifecycleEventObserver方法,然后创建ReflectiveGenericLifecycleObserver对象,然后调用ClassesInfoCache.sInstance.getInfo,这个方法传入的是我们的MytViewModelLifecycle的对象,拿到他的class,然后通过反射拿到MytViewModelLifecycle方法和注解并且存入map.具体怎么反射这里就不细讲了! (在反射中一般都是通过map去存取提高性能)

 3.观察者(MytViewModelLifecycle)是如何知道被观察者(Activity)的生命周期的
   回到ComponentActivity中的onCreate方法,它会创建一个空白的ReportFragment,有了这个ReportFragment,当activity执行生命周期ReportFragment也会执行相应的生命周期. 我们以onStart为例,每个生命周期都会调用dispatch方法,最终都会调用**dispatch( Activity activity, Lifecycle.Event event)方法. 然后调用((LifecycleRegistry) lifecycle).handleLifecycleEvent(event)方法

  在handleLifecycleEvent分别会调用getStateAfter和moveToState方法这两个方法,getStateAfter的目的就是通过生命周期得到一个状态.方便大家理解大家可以看白色背景的那张图.通过不同的事件拿到相应的状态
 1.初始化状态->页面显示状态,这种情况属于activity的创建到显示 这属于前进状态
 2.页面显示状态->销毁状态:这种情况下属于activity回到不可见了 这属于倒退状态

  moveToState(next):这个方法的意思就是状态对齐.举个栗子吧:假如activity(被观察者)现在是onstart状态,这时候观察者MytViewModelLifecycle还是CREATE状态,这时候为了保证生命周期对齐,所以需要将next赋值给State,接着调用sync()进行同步

   backwardPass方法 如果满足条件的主要调用downEvent 这个方法主要通过状态拿到事件,例如现在是STARTED对应上面的图拿到ON_STOP事件,然后又通过getStateAfter(ON_STOP)方法去拿到CREATED状态,

   LifecycleEventObserver是一个接口 然后ReflectiveGenericLifecycleObserver实现了这个接口,所以最终调用了ReflectiveGenericLifecycleObserver的onStateChanged方法

   invokeCallbacks方法里面通过反射拿到执行相应方法,这里就不多阐述了!

   再回到sync()里面的forwardPass方法 如果满足条件的主要调用upEvent(observer.mState)拿到前进状态,例如现在是STARTED状态就可以到ON_RESUME事件通过ON_RESUME事件最终通过反射调用@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)的方法

总结一下:
1.ComponentActivity里面实现了LifecycleOwner接口 ,并且初始化LifecycleRegistry了,LifecycleRegistry是实现了LifecycleOwner接口
2.在ComponentActivity里面创建了一个透明的ReportFragment来感应activity的生命周期,在Fragment的生命周期方法里面分别执行对应的dispatch方法
2.addObserver方法创建了ReflectiveGenericLifecycleObserver并且存储了观察者的class信息,
3.在dispatch传入相应的事件之后,然后通过getStateAfter拿到相应的状态
4.通过状态枚举比大小,如果是倒退流程就调用backwardPass方法,backwardPass方法会通过downEvent拿到状态拿到事件,然后又通过事件拿到状态
5.,如果是前进流程就调用forwardPass方法,forwardPass方法会通过upEvent拿到状态拿到事件
6.最后在ReflectiveGenericLifecycleObserver.onStateChanged里面执行mInfo.invokeCallbacks执行相应的方法
7.之所以要设计状态 是要留给其他框架用的

Android AAC第一篇 Lifecycle的源码解析

前言

AAC是Android Architecture Components的缩写,翻译过来就是Android架构组件的意思,是Google IO 2017大会期间发布的一组架构组件,它可以用来帮助开发搭建更加简单便捷的APP架构。AAC里面涉及到了LiveData,ViewModel,其中LiveData的工作需要依赖于Lifecycle,所以本篇文章将介绍Lifecycle的工作原理,并从源码的角度去解析它。在进行源码解读前我们需要先知道Lifecycle的使用方法,下面先看一个简单的simple。

这里我们新建Activity继承androidx里面的AppCompatActivity,它已经实现了LifecycleOwner接口,我们可以通过它的getLifecycle方法拿到这个lifecycle对象添加observer,如果是自己实现的Activity,那么可以在自定义的Activity中新建一个LifecycleRegistry并在响应的生命周期中调用它的handleLifecycleEvent方法监听生命周期的改变。

class LifecycleTestActivity : AppCompatActivity() 

    val TAG = javaClass.simpleName

    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_lifecycle_test)
        lifecycle.addObserver(MyLifeCycleObserver())
    

MyLifeCycleObserver .java

class MyLifeCycleObserver : LifecycleObserver 
    
    val TAG = javaClass.simpleName

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate()
        Log.i(TAG, "onCreate-----");
    

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStart()
        Log.i(TAG, "onStart-----");
    

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume()
        Log.i(TAG, "onResume-----");
    

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause()
        Log.i(TAG, "onPause-----");
    

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onStop()
        Log.i(TAG, "onStop-----");
    

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy()
        Log.i(TAG, "onDestroy-----");
    

这样我们就可以监听到Activity的生命周期回调了。

源码解析

Lifecycle是androidx或者support包中新加入的功能特性,用来管理Activity的生命周期。本文以androidx包为例,进行源码解析。

在androidx包我们根据AppCompatActivity的继承关系可以发现它是ComponentActivity.java的子类,我们先看一下ComponentActivity.java的类结构

public class ComponentActivity extends Activity
        implements LifecycleOwner, KeyEventDispatcher.Component

发现其实现了LifecycleOwner接口,我们看一下LifecycleOwner接口的定义

public interface LifecycleOwner 
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();

它定义了一个getLifecycle()方法,我们看看在ComponentActivity中这个接口方法的实现

@Override
public Lifecycle getLifecycle() 
    return mLifecycleRegistry;

发现这个方法返回的是一个Lifecycle对象,Lifecycle是一个抽象类,里面定义了三个抽象方法,和Event,State两个枚举类,我们看一下它的源码(限于篇幅,已裁剪掉了大段注释)

public abstract class Lifecycle 

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

    @SuppressWarnings("WeakerAccess")
    public enum Event 
        ON_CREATE,
        ON_START,
        ON_RESUME,
        ON_PAUSE,
        ON_STOP,
        ON_DESTROY,
        ON_ANY
    

    /**
     * Lifecycle states. You can consider the states as the nodes in a graph and
     * @link Events as the edges between these nodes.
     */
    @SuppressWarnings("WeakerAccess")
    public enum State        
        DESTROYED,        
        INITIALIZED,       
        CREATED,        
        STARTED,        
        RESUMED;     
        public boolean isAtLeast(@NonNull State state) 
            return compareTo(state) >= 0;
        
    

getLifecycle方法中,它返回的mLifecycleRegistry是一个LifecycleRegistry类的实例,我们看看它是怎么实现Lifecycle接口的,首先看看它的addObserver方法的源码

@Override
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) 
        // 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--;

在第二段代码中根据我们传入的observer创建了一个ObserverWithState类对象,我们看看ObserverWithState类对象

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;
    

注意看它的构造方法,它将我们传入的observer转化为了GenericLifecycleObserver类对象,而我们传入的对象仅是实现了一个空接口LifecycleObserver的实例,那么它是怎么转化的呢,我们看看Lifecycling.getCallback(observer);

@NonNull
static GenericLifecycleObserver getCallback(Object object) 
	// 如果是FullLifecycleObserver实例,那么创建一个FullLifecycleObserverAdapter对象
	// FullLifecycleObserverAdapter实现了GenericLifecycleObserver接口	
	// ①. 
    if (object instanceof FullLifecycleObserver) 
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
    
	// 如果是GenericLifecycleObserver对象,则不用转化了直接返回
	// ②.
    if (object instanceof GenericLifecycleObserver) 
        return (GenericLifecycleObserver) 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);

这个方法比较复杂,我们首先看下1处的FullLifecycleObserver接口

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

发现它定义了一组和Activity生命周期相对应的方法,我们在看看FullLifecycleObserverAdapter

class FullLifecycleObserverAdapter implements GenericLifecycleObserver 

    private final FullLifecycleObserver mObserver;

    FullLifecycleObserverAdapter(FullLifecycleObserver observer) 
        mObserver = observer;
    

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

可以发现它应用了适配器模式,实现了GenericLifecycleObserver接口,在接口方法onStateChanged实现中回调了相应的方法,将。这FullLifecycleObserver接口适配成了GenericLifecycleObserver。这里我们先记住GenericLifecycleObserver接口,它比较重要,后面我们会知道GenericLifecycleObserver接口的onStateChanged触发点。通过对FullLifecycleObserverFullLifecycleObserverAdapter分析我们得出,如果我们添加的observer是FullLifecycleObserver的实例,那么它最终也会转换为GenericLifecycleObserver,可惜FullLifecycleObserver的访问权限是默认的不是public的。

我们再看上面的②处,如果我们传入的observer是GenericLifecycleObserver实例,那么它直接返回。再看上面的③处的getObserverConstructorType方法

private static int getObserverConstructorType(Class<?> klass) 
        if (sCallbackCache.containsKey(klass)) 
            return sCallbackCache.get(klass);
        
        int type = resolveObserverCallbackType(klass);
        sCallbackCache.put(klass, type);
        return type;
    

它做了缓存,然后调用了resolveObserverCallbackType方法

private static int resolveObserverCallbackType(Class<?> klass) 
        // anonymous class bug:35073837
        // 判断是不是匿名内部类,为null代表是匿名内部类
        if (klass.getCanonicalName() == null) 
            return REFLECTIVE_CALLBACK;
        
		// 反射获取构造器,内部根据传入的class和约定的_LifecycleAdapter命名后缀反射加载相应注解生成器生成的构造器
        Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
        if (constructor != null) 
            sClassToAdapters.put(klass, Collections
                    .<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
            // 有相应的构造器,返回生成类型
            return GENERATED_CALLBACK;
        
		// 反射获取observer类的方法,判断它是否包含OnLifecycleEvent.class注解,如果包含,则返回反射类型
        boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
        if (hasLifecycleMethods) 
            return REFLECTIVE_CALLBACK;
        

        Class<?> superclass = klass.getSuperclass();
        List<Constructor<? extends GeneratedAdapter>> adapterConstructors = null;
        // 判断observer的superclass是否是LifecycleObserver的子类
        if (isLifecycleParent(superclass)) 
        	// 判断父类型是否符合反射类型
            if (getObserverConstructorType(superclass) == REFLECTIVE_CALLBACK) 
                return REFLECTIVE_CALLBACK;
            
            adapterConstructors = new ArrayList<>(sClassToAdapters.get(superclass));
        
		// 判断observer实现的接口是否符合反射类型
        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;
    

通过上面的注释我们发现getObserverConstructorType方法是生成observer转化类是通过反射还是注解生成的类。回到调用getObserverConstructorTypegetCallback方法

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

通过getObserverConstructorType方法得到通过反射还是生成得到代理的observer的类,如果是生成类型则会更加构造器的数量生成SingleGeneratedAdapterObserver或是CompositeGeneratedAdaptersObserver,如果是反射方式则会生成ReflectiveGenericLifecycleObserver,我们分别看下这三个类的源码

SingleGeneratedAdapterObserver.java

public class SingleGeneratedAdapterObserver implements GenericLifecycleObserver 

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

CompositeGeneratedAdaptersObserver.java

@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class CompositeGeneratedAdaptersObserver implements GenericLifecycleObserver 

    private final GeneratedAdapter[] mGeneratedAdapters;

    CompositeGeneratedAdaptersObserver(GeneratedAdapter[] generatedAdapters) 
        mGeneratedAdapters = generatedAdapters;
    

    @Override
    public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) 
        MethodCallsLogger logger = new MethodCallsLogger();
        for (GeneratedAdapter mGenerated: mGeneratedAdapters) 
            mGenerated.callMethods(source, event, false, logger);
        
        for (GeneratedAdapter mGenerated: mGeneratedAdapters) 
            mGenerated.callMethods(source, event, true, logger);
        
    

ReflectiveGenericLifecycleObserver .java

class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver 
    private final Object mWrapped;
    private final CallbackInfo mInfo;

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

    @Override
    public void onStateChanged(LifecycleOwner source, Event event) 
        mInfo.以上是关于Android Lifecycle源码解析的主要内容,如果未能解决你的问题,请参考以下文章

Android jetpack架构组件Lifecycle实战与源码解析

Android AAC第一篇 Lifecycle的源码解析

Android AAC第一篇 Lifecycle的源码解析

Jetpack-Lifecycle源码解析

Lifecycle源码解析

3. Jetpack源码解析---用Lifecycles管理生命周期