Lifecycle 组件指的是 android.arch.lifecycle 包下提供的各种类与接口,可以让开发者构建能感知其他组件(主要指Activity 、Fragment)生命周期(lifecycle-aware)的类。
使用
引用依赖
def lifecycle_version = "2.1.0"
compile "android.arch.lifecycle:runtime:$lifecycle_version"
annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version"
使用步骤
1.新建类实现LifecycleObserver接口,通过注解关联生命周期方法。
public class ActivityLifeObserver implements BasePresenter,LifecycleObserver {
private final static String TAG = "ActivityLifeObserver";
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
@Override
public void onCreate() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
@Override
public void onStart() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
@Override
public void onResume() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
@Override
public void onPause() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
@Override
public void onStop() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
@Override
public void onDestroy() {
}
}
BasePresenter是回调方法可以随意,OnLifecycleEvent的参数是枚举类Lifecycle.Event,对应生命周期方法。
2.Activity实现LifecycleOwner接口,声明全局变量LifecycleRegistry,并重写getLifecycle方法返回。通过LifecycleRegistry注册监听。详细代码如下:
public class MainActivity extends AppCompatActivity implements LifecycleOwner {
private LifecycleRegistry mRegistry;
private LifecycleObserver mLifecycleObserver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (mRegistry == null){
mRegistry = new LifecycleRegistry(this);
}
//绑定
mRegistry.addObserver(mLifecycleObserver = new ActivityLifeObserver());
}
@NonNull
@Override
public Lifecycle getLifecycle() {
//getLifecycle在oncreate前,因此需要判断
if (null == mRegistry){
mRegistry = new LifecycleRegistry(this);
}
return mRegistry;
}
@Override
protected void onDestroy() {
super.onDestroy();
if (null != mRegistry){
//解绑
mRegistry.removeObserver(mLifecycleObserver);
}
}
}
此时运行就可以监听声明周期了,效果如下:
D/ActivityLifeObserver: onCreate
D/ActivityLifeObserver: onStart:
D/ActivityLifeObserver: onResume:
D/ActivityLifeObserver: onPause:
D/ActivityLifeObserver: onStop:
D/ActivityLifeObserver: onDestroy:
原理
Lifecycle是如何感知生命周期的?
Lifecycle是如何完成注解与生命周期方法绑定的?
带着这两个问题我们来看一下Lifecycle源码。
首先我们来看一下Lifecycle是如何感知生命周期的?
从MainActivity来看一共做了三件事
1.初始化LifecycleRegistry
2.绑定LifecycleObserver
3.通过getLifecycle返回LifecycleRegistry
第一二步是基础的数据绑定操作,那么涉及生命周期感知的应该就是第三步了。点击getLifecycle方法跳出引用的地方,我们发现有个类叫ReportFragment
。有过glide分析经验的同志应该记得Glide就是向Activity添加无界面的Fragment从而感知生命周期,那么Lifecycle是否如此,我们来看一下ReportFragment源码:
@SuppressWarnings("UnknownNullness") // TODO https://issuetracker.google.com/issues/112197238
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
public class ReportFragment extends Fragment {
private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
...
@Override
public void onResume() {
super.onResume();
dispatchResume(mProcessListener);
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);
}
}
}
}
我们发现ReportFragment
的确是用来感知生命周期的,在对应的生命周期方法中调用dispatch将生命周期状态分发下去。最后事件走到LifecycleRegistry的handleLifecycleEvent方法里面。我们看一下ReportFragment是在哪里被添加的:
//向activity添加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();
}
}
injectIfNeededIn是ReportFragment添加进Activity的方法,调用的地方在ComponentActivity中,而ComponentActivity是AppCompatActivity的父类:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
所以在activity刚刚被创建的时候,ReportFragment就已经同步添加了。这时候第一个问题就可以回答了:Lifecycle是通过向Activity添加ReportFragment从而达到感知生命周期的作用。
下面我们来看第二个问题,上面我们看到ReportFragment生命周期方法走到LifecycleRegistry的handleLifecycleEvent方法里面,下面我们来看下该方法:
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
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;
}
handleLifecycleEvent会依据Event找到下一个状态,并将同步至该状态,核心方法是 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;
}
sync方法对比此状态与map最后一个状态,如果小于则回退,对比最新的状态,如果大于则前进状态,则前进,以下是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();
}
}
}
代码核心为ObserverWithState ,调用其dispatchEvent完成状态分发,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;
}
}
可以看到ObserverWithState 将LifecycleObserver封装为LifecycleEventObserver ,然后调用onStateChanged了,下面我们看下封装的代码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);
}
lifecycleEventObserver有4层判定:
1、FullLifecycleObserver的子类,返回FullLifecycleObserverAdapter,FullLifecycleObserver是官方实现,默认有生命周期方法。不用注解。
2、LifecycleEventObserver子类,返回LifecycleEventObserver子类本身,改类提供了onStateChanged回调方法,用于检测生命周期变换。
3、如果APT生成了对应的类,则返回CompositeGeneratedAdaptersObserver,其内部也是调用反射执行对应的注解方法。
4、如都不满足则返回ReflectiveGenericLifecycleObserver,内部onStateChanged调用CallbackInfo的invokeCallbacks方法。
我们来看下invokeCallbacks方法:
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);
}
}
}
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
//noinspection TryWithIdenticalCatches
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);
}
}
一路追寻,发现最终是通过反射来完成方法的执行的。那么Method是如下关联的呢?我们发现在前面的lifecycleEventObserver方法中有个代码语句:
int type = getObserverConstructorType(klass);
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;
}
该代码块是判断是否是APT还是默认的反射方式,其中resolveObserverCallbackType做了一些操作:
...
ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
...
hasLifecycleMethods方法:
...
Method[] methods = getDeclaredMethods(klass);
for (Method method : methods) {
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation != null) {
// Optimization for reflection, we know that this method is called
// when there is no generated adapter. But there are methods with @OnLifecycleEvent
// so we know that will use ReflectiveGenericLifecycleObserver,
// so we createInfo in advance.
// CreateInfo always initialize mHasLifecycleMethods for a class, so we don't do it
// here.
createInfo(klass, methods);
return true;
}
}
...
hasLifecycleMethods获取被OnLifecycleEvent 注解的方法,然后一一创建CallbackInfo对象:
for (Method method : methods) {
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
....
Class<?>[] params = method.getParameterTypes();
int callType = CALL_TYPE_NO_ARG;
Lifecycle.Event event = annotation.value();
....
MethodReference methodReference = new MethodReference(callType, method);
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
}
CallbackInfo info = new CallbackInfo(handlerToEvent);
到这里我们就可以知道,原来onStateChanged执行的CallbackInfo对象实际上就是封装了OnLifecycleEvent 注解方法的对象。所以当状态变更时,对应的方法也会调用。
总结:
Lifecycle是如何感知生命周期的?
Lifecycle向Activity添加ReportFragment,然后通过ReportFragment感知生命周期。
Lifecycle是如何完成注解与生命周期方法绑定的?
生命周期分发时,最终会执行ObserverWithState的dispatchEvent方法,dispatchEvent方法会调用LifecycleEventObserver的onStateChanged方法。
ObserverWithState通过Lifecycling获取不同类型的LifecycleEventObserver,获取过程中会遍历被OnLifecycleEvent 注解修饰的方法,并保存。
当onStateChanged执行时,通过反射执行对应状态的方法,从而完成注解与生命周期方法的绑定。
如果配置了APT依赖,APT分支在于默认反射分支前。