Android AAC第一篇 Lifecycle的源码解析
Posted 宿罪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
触发点。通过对FullLifecycleObserver
和FullLifecycleObserverAdapter
分析我们得出,如果我们添加的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转化类是通过反射还是注解生成的类。回到调用getObserverConstructorType
的getCallback
方法
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 AAC第一篇 Lifecycle的源码解析的主要内容,如果未能解决你的问题,请参考以下文章