Android架构组件之Lifecycle源码解析

Posted

tags:

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

参考技术A Lifecycle-Aware是Google官方的生命周期感知组件。同时,在Google推出的android Jetpack组件中,也将Lifecycle-Aware放在了Architecture类别之中。我们可以利用 android.arch.lifecycle 包提供的类来控制数据、监听器等的 lifecycle。同时,LiveData和ViewModel的lifecycle也依赖于Lifecycle框架,所以我们有必要去了解一下Lifecycle。

/app/build/intermediates/manifests/full/debug/AndroidManifest.xml,是我们应用在构建完成之后完整生成的AndroidManifest.xml文件。其中,我们可以找到Lifecycle-Aware组件在AndroidManifest的定义。

ProcessLifecycleOwnerInitializer是ContentProvider的子类,利用其onCreate()生命周期方法,处理Lifecycle组件初始化。因此,这是一种隐式初始化的方式。

继续关注ProcessLifecycleOwnerInitializer的onCreate()方法,其调用了LifecycleDispatcher的init()方法进行相应初始化。

init()方法其实就是在Application中注册了一个ActivityLifecycleCallbacks监听(即DispatcherActivityCallback),用来监听每个Activity的生命周期变化。
我们再看下DispatcherActivityCallback的onActivityCreated()回调方法,如果Activity是FragmentActivity,则注册一个FragmentLifecycleCallbacks(即FragmentCallback)用来监听Activity中Fragment的生命周期。

我们看到FragmentCallback的onFragmentCreated()回调方法中,当Fragment如果实现了LifecycleRegistryOwner,就会为其添加一个DestructionReportFragment,用来监听Fragment的生命周期。
之后,会在Activity中添加一个ReportFragment,用来监听Activity生命周期。

如此,利用一个附着在Activity上无UI的Fragment,通过相应的生命周期回调方法,实质上是对Activity生命周期的监听。
至此,我们知道了Lifecycle组件通过ActivityLifecycleCallbacks、FragmentLifecycleCallbacks及 无UI的Fragment来感知Activity/Fragment的生命周期变化并产生相应的事件。

在上面的分析中,我们只是重点关注了Lifecycle如何感知生命周期,也就是如何监听Activity/Fragment的生命周期。在相应的回调方法当中,其实都包含了很多生命周期事件分发相关的逻辑。通过相关的源码分析,我们可以发现最终都会调用到Activity/Fragment的getLifecycle()方法获取Lifecycle对象,之后再调用Lifecycle对象的handleLifecycleEvent()方法进行事件分发。26.1.0及更高版本Support支持库中的Activity和Fragment已经实现了LifecycleOwner接口。

有上述源码可以,其实getLifecycle() 方法最终返回的都是LifecycleRegistry对象,事件分发最后也都是调用LifecycleRegistry的handleLifecycleEvent()方法。

这些只是分发的逻辑,那么在事件分发之前,肯定要有事件的注册,这就得看一下addObserver()方法。

至此,我们可以知道,当lifecycle发生变化时,handleLifecycleEvent
会通过 getStateAfter()方法获取当前应处的状态并修改mState值,紧接着遍历所有 ObserverWithState并调用他们的sync方法来同步且通知LifecycleObserver状态发生变化。

Lifecycle生命周期事件感知由LifecycleDispatcher(ActivityLifecycleCallbacks, FragmentLifecycleCallbacks, Fragment)完成,并通过 LifecycleRegistry传递给 LifecycleObserver。

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 AAC第一篇 Lifecycle的源码解析

Android AAC第一篇 Lifecycle的源码解析

Android Lifecycle源码解析

Android官方架构组件介绍之LifeCycle

Android Jetpack 组建介绍——Lifecycler

Android Jetpack架构组件——Lifecycle原理篇