【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 Event}s 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
                    .<? 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.invokeCallbacks(source, event, mWrapped);
    }
}

可以看到它们三种observer都实现了GenericLifecycleObserver接口,并在onStateChanged方法中分发响应了响应的生命周期回调事件,所以最终我们锁定到GenericLifecycleObserver.java,回到LifecycleRegistry的addObserver方法

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

我们看到这里调用了statefulObserver的dispatchEvent方法,包括下面的sync方法中也调用了dispatchEvent方法,我们看看statefulObserverdispatchEvent的方法实现

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

这里调用了通过生成器生成的GenericLifecycleObserver还是反射得到的GenericLifecycleObserveronStateChanged的方法,而通过上面的分析我们知道GenericLifecycleObserveronStateChanged里面分发的observer的事件方法,这个是在addObserver的走的逻辑。那么我们的Activity在其他生命周期回调的时候是怎么通知我们的observer事件改变的呢。

这时我们回到ComponentActivity,发现其在onCreate()方法中创建了一个空的fragment来监听生命周期的方法

protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ReportFragment.injectIfNeededIn(this);
}

我们看看injectIfNeededIn方法

public static void injectIfNeededIn(Activity activity) {
    // ProcessLifecycleOwner should always correctly work and some activities may not extend
    // FragmentActivity from support lib, so we use framework fragments for activities
    android.app.FragmentManager manager = activity.getFragmentManager();
    if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
        manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
        // Hopefully, we are the first to make a transaction.
        manager.executePendingTransactions();
    }
}

发现在方法中创建了一个ReportFragment并添加到了我们的Activity,我们看下ReportFragment.java的源码的几个生命周期相关的方法

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

发现其在相应的生命周期中调用了dispatch方法

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

最终又调用了lifecycle实现类LifecycleRegistryhandleLifecycleEvent方法

public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    State next = getStateAfter(event);
    moveToState(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) {
        Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
                + "new events from it.");
        return;
    }
    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;
}

sync方法里面又调用了backwardPassforwardPass方法,在这两个方法中最终都回调了ObserverWithStatedispatchEvent方法,在这个方法中调用了onStateChanged方法触发了我们调用addObserver添加的observer相应的生命周期方法。

到这里Lifecycle的工作原理就已经解析完了,有兴趣的读者可以去查阅一下androidx或者support包中的Fragment是Lifecycle源码实现,下面Lifecycle工作原理的类图和时序图来结束本篇文章。

类图:
【Android AAC】第一篇 Lifecycle的源码解析_第1张图片
时序图:
【Android AAC】第一篇 Lifecycle的源码解析_第2张图片

你可能感兴趣的:(Android源码解析,Android进阶)