之前用过一些android架构组件,但也仅限于api调用,知其然也该知其所以然,所以尝试了解下其源码实现;
本文主要想简单探究下以下问题:
- Lifecycle 如何知晓 Activity 的生命周期变化;
- LifecycleObserver 的注解如何生效;
本文基于: macOS 10.13/AS 3.4/support-v7 28.0.0
使用方法简介
以前拆分业务逻辑到独立的 presenter
中时,需要重写 Activity
/Fragment
各生命周期,然后告知 presenter
, 写起来麻烦, 有没有比较简单的方式能把这些"脏活"给处理掉呢?
我们看看 Lifecycle
的用法:
// MainActiviy.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifecycle.addObserver(MainActObserver())
}
}
// MainActObserver.kt
class MainActObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
Logger.d("MainActObserver $this onCreate")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
Logger.d("MainActObserver onResume")
}
// 其他生命周期回调,此处省略
}
可以看到就简单一句 lifecycle.addObserver(MainActObserver())
就完成了 Activity
各生命周期的监听;
P.S. 由于
Android Studio
创建项目时默认导入了 support 的appcompat-v7
包,已经把Lifecycle
相关代码导入进来了, 因此我们可以直接使用,不需要额外添加依赖;
以下就从 lifecycle.addObserver(MainActObserver())
展开:
先认识下 Lifecycle
类
// package android.arch.lifecycle;
// Lifecycle.java
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();
// 生命周期事件
public enum Event {
ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DESTROY, ON_ANY
}
// 生命周期状态
public enum State {
// 以下均已 Activity 为例,介绍各状态值,具体请看源码注释
DESTROYED,
INITIALIZED, // 对象创建后但尚未收到 onCreate() 通知之前
CREATED,// onCreate()/onStop() 之后
STARTED, // onStart()/onPause() 之后
RESUMED; // onResume() 之后
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}
可以发现: Lifecycle
只是个抽象类,也没有对生命周期的变化做出响应的方法,只是简单定义了生命周期事件及状态, 因此应该有个实现类对生命周期事件作出处理;
顺便看下 MainActObserver
它实现了 LifecycleObserver
接口,而 LifecycleObserver
仅是一个标记接口:
/**
* Marks a class as a LifecycleObserver. It does not have any methods, instead, relies on {@link OnLifecycleEvent} annotated methods.
* 这是个标记性接口,没有任何方法
*/
public interface LifecycleObserver {
}
/**
* 通过上面 LifecycleObserver 的注释,可以发现,最终是通过本注解来实现生命周期感知的
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnLifecycleEvent {
Lifecycle.Event value();
}
通过代码注释我们也可大概猜到:各生命周期事件应该是通过遍历 LifecycleObserver
实现类,查找带有 OnLifecycleEvent
注解的方法,然后进行回调的;
言归正传,探究下 getLifecycle()
activity类图
// package android.support.v4.app;
// FragmentActivity.java
public class FragmentActivity extends SupportActivity {
public Lifecycle getLifecycle() {
return super.getLifecycle();
}
}
// package android.support.v4.app;
// SupportActivity.java
public class SupportActivity extends Activity implements LifecycleOwner, Component {
// LifecycleRegistry 是 Lifecycle 的实现类,所有逻辑由其来完成
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
public Lifecycle getLifecycle() {
return this.mLifecycleRegistry;
}
}
lifecycle
从上图可知, LifecycleRegistry
应能会接收并处理各生命周期事件/状态,并通过 sync()
同步到各observer;
生命周期状态的变化顺序
回看 Lifecycle
源码,发现生命周期状态(State
)的个数小于事件(Event
)的个数,因此应该有多个事件归属于同一个状态,并且状态之间的变化规律应该也定义在 LifecycleRegistry
中:
// package android.arch.lifecycle;
// LifecycleRegistry.java
public class LifecycleRegistry extends Lifecycle {
private State mState; // 当前状态
// 使用弱引用,避免影响Activity的GC
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
// 计算发生某个生命周期时间后应有的状态
static State getStateAfter(Event event) {
switch (event) {
case ON_CREATE:
case ON_STOP:
return CREATED;
case ON_START:
case ON_PAUSE:
return STARTED;
case ON_RESUME:
return RESUMED;
case ON_DESTROY:
return DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException("Unexpected event value " + event);
}
// 回退到前一状态时的事件
private static Event downEvent(State state) {
switch (state) {
case INITIALIZED:
throw new IllegalArgumentException();
case CREATED:
return ON_DESTROY;
case STARTED:
return ON_STOP;
case RESUMED:
return ON_PAUSE;
case DESTROYED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException("Unexpected state value " + state);
}
// 前进到下一状态时的事件
private static Event upEvent(State state) {
switch (state) {
case INITIALIZED:
case DESTROYED:
return ON_CREATE;
case CREATED:
return ON_START;
case STARTED:
return ON_RESUME;
case RESUMED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException("Unexpected state value " + state);
}
}
可得出下图(图片来自官网):
生命周期事件/状态的处理
// package android.arch.lifecycle;
// LifecycleRegistry.java
public class LifecycleRegistry extends Lifecycle {
/**
* 由于实际生命周期事件多于lifecycle定义的数量,可能有部分生命周期回调需要直接指定其当前的状态,
* 如: SupportActivity 的 onSaveInstanceState(Bundle) 事件, 就被直接标记为 CREATED 状态
*/
@MainThread
public void markState(@NonNull State state) {
moveToState(state);
}
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event); // 计算事件发生后的状态
moveToState(next); // 更新当前状态
}
// Activity 生命周期事件变化时都会走到这里, 最终通过 sync() 方法通知各 observer
private void moveToState(State next) {
if (mState == next) {
return;
}
mState = next; // 更新当前状态
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
return;
}
mHandlingEvent = true;
sync(); // 通知各 LifecycleObserver 更新状态
mHandlingEvent = false;
}
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.
// 如果当前状态比observerMap中最小的状态值还小,则回退状态
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
// 如果当前状态比observerMap中最大的状态值还大,则前移状态
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
}
无论 backwardPass(LifecycleOwner)
还是 forwardPass(LifecycleOwner)
最终都是调用 ObserverWithState
类的 dispatchEvent(LifecycleOwner, Event)
方法, 我们来看下这个类:
// LifecycleRegistry.java
public class LifecycleRegistry extends Lifecycle {
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// 我们定义的 LifecycleObserver 被包装成 ObserverWithState
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
// 缓存所有的observer,后续用于遍历回调通知
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
// 省略部分代码
}
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
// GenericLifecycleObserver 继承自 LifecycleObserver,此处又做了一次包装
mLifecycleObserver = Lifecycling.getCallback(observer);
mState = initialState;
}
// 当 LifecycleOwner 生命周期变化时,通过本方法来通知各 LifeObserver
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
}
到此,我们知道了 LifecycleRegistry
通知 LifecycleOwner
的大体流程,但我们仍然没看到我们的注解如何发生作用,如何收到生命周期事件,接下来我们就来看看
生命周期注解的使用
// package android.arch.lifecycle;
// Lifecycling.java
public class Lifecycling {
@NonNull
static GenericLifecycleObserver getCallback(Object object) {
if (object instanceof FullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
}
if (object instanceof GenericLifecycleObserver) {
return (GenericLifecycleObserver) object;
}
// 由于我没有使用 LifeCycleCompiler ,因此不会生成 MainActObserver_LifecycleAdapter 类, 此if判断不满足
// P.S. MainActObserver_LifecycleAdapter 位于: app/build/generated/source/kapt/debug/***
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);
}
// 最终是通过反射获取 LifecycleObserver 的方法
// 但反射比较耗性能, 因此可以猜想应该有做缓存优化
return new ReflectiveGenericLifecycleObserver(object);
}
}
// package android.arch.lifecycle;
// ReflectiveGenericLifecycleObserver.java
class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
// 可以猜想 ClassesInfoCache 是用于缓存 包含lifecycle生命周期事件方法的
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
// 当Activity生命周期发生变化时,通过 CallbackInfo 来触发 LifecycleObserver 各方法
// 因此重点就在 ClassesInfoCache 类生成的 CallbackInfo 中
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
// package android.arch.lifecycle;
// ClassesInfoCache.java
class ClassesInfoCache {
CallbackInfo getInfo(Class klass) {
// 由于运行时反射成本大, 因此先查缓存,若不存在,则反射提取各方法
CallbackInfo existing = mCallbackMap.get(klass);
if (existing != null) {
return existing;
}
existing = createInfo(klass, null);
return existing;
}
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
// 查看父类是否也有生命周期事件注解,若有,一并添加到缓存中
Class superclass = klass.getSuperclass();
Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
if (superclass != null) {
CallbackInfo superInfo = getInfo(superclass);
if (superInfo != null) {
handlerToEvent.putAll(superInfo.mHandlerToEvent);
}
}
Class[] interfaces = klass.getInterfaces();
for (Class intrfc : interfaces) {
for (Map.Entry<MethodReference, Lifecycle.Event> entry : getInfo(
intrfc).mHandlerToEvent.entrySet()) {
verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
}
}
// 遍历我们定义的 LifecycleObserver 实现类方法, 若带有 OnLifecycleEvent 注解,则缓存
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
for (Method method : methods) {
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation == null) {
continue;
}
hasLifecycleMethods = true;
Class<?>[] params = method.getParameterTypes();
int callType = CALL_TYPE_NO_ARG;
// 自定义的方法允许带有参数,并且第一个参数类型只能是 LifecycleOwner
if (params.length > 0) {
callType = CALL_TYPE_PROVIDER;
if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
throw new IllegalArgumentException(
"invalid parameter type. Must be one and instanceof LifecycleOwner");
}
}
Lifecycle.Event event = annotation.value();
// 若注解事件是 Lifecycle.Event.ON_ANY, 则还允许有第二个参数,但参数类型必须是 Lifecycle.Event
if (params.length > 1) {
callType = CALL_TYPE_PROVIDER_WITH_EVENT;
if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
throw new IllegalArgumentException(
"invalid parameter type. second arg must be an event");
}
if (event != Lifecycle.Event.ON_ANY) {
throw new IllegalArgumentException(
"Second arg is supported only for ON_ANY value");
}
}
// 参数个数不允许超过2个
if (params.length > 2) {
throw new IllegalArgumentException("cannot have more than 2 params");
}
// 若handlerToEvent中无该方法的缓存,则添加进去
MethodReference methodReference = new MethodReference(callType, method);
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
}
// 将搜索到的带注解事件方法列表缓存到CallbackInfo中,并返回
CallbackInfo info = new CallbackInfo(handlerToEvent);
// 把相关的 LifecycleObserver 类及相应注解方法都缓存到 mCallbackMap 中
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
static class CallbackInfo {
final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;
final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;
CallbackInfo(Map<MethodReference, Lifecycle.Event> handlerToEvent) {
mHandlerToEvent = handlerToEvent;
mEventToHandlers = new HashMap<>();
for (Map.Entry<MethodReference, Lifecycle.Event> entry : handlerToEvent.entrySet()) {
Lifecycle.Event event = entry.getValue();
List<MethodReference> methodReferences = mEventToHandlers.get(event);
if (methodReferences == null) {
methodReferences = new ArrayList<>();
mEventToHandlers.put(event, methodReferences);
}
methodReferences.add(entry.getKey());
}
}
@SuppressWarnings("ConstantConditions")
void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
// 调用一次对应 event 事件的注解方法,同一个event事件可能存在多个注解方法,需要遍历
invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
// 任意事件都会触发一次 ON_ANY 注解方法
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) {
// 遍历指定 event 事件对应的方法列表, 触发 MethodReference 的 invokeCallback(*) 方法
for (int i = handlers.size() - 1; i >= 0; i--) {
handlers.get(i).invokeCallback(source, event, mWrapped);
}
}
}
}
static class MethodReference {
final int mCallType;
final Method mMethod;
MethodReference(int callType, Method method) {
mCallType = callType;
mMethod = method;
mMethod.setAccessible(true);
}
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
// 关于方法参数个数问题,上面已经有说过
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);
}
}
}
}
至此我们就知晓了 LifecycleRegistry
处理生命周期变化的逻辑及如何回调通知被各注解标记的方法的, 但它是如何知道 Activity
生命周期的? 这个我们还没有看到,下面探究下;
LifecycleRegistry
如何获知 Activity
的生命周期变化
偶然看了眼 SupportActivity
类的导包列表,发现 android.arch.lifecycle
包下除了 ReportFragment
类外都有分析过, 我们来看看它的作用:
package android.support.v4.app;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.LifecycleRegistry;
import android.arch.lifecycle.ReportFragment;
import android.arch.lifecycle.Lifecycle.State;
@RestrictTo({Scope.LIBRARY_GROUP})
public class SupportActivity extends Activity implements LifecycleOwner, Component {
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
}
// package android.arch.lifecycle;
// ReportFragment.java
public class ReportFragment extends Fragment {
private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
/**
* 搜索当前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();
}
}
/**
* 通过fragment的生命周期来获知activity的生命周期
* 然后通过 dispatch(event) 来通知各 LifecycleObserver
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatch(Lifecycle.Event.ON_CREATE);
}
@Override
public void onStart() {
super.onStart();
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
dispatch(Lifecycle.Event.ON_RESUME);
}
@Override
public void onPause() {
super.onPause();
dispatch(Lifecycle.Event.ON_PAUSE);
}
@Override
public void onStop() {
super.onStop();
dispatch(Lifecycle.Event.ON_STOP);
}
@Override
public void onDestroy() {
super.onDestroy();
dispatch(Lifecycle.Event.ON_DESTROY);
}
private void dispatch(Lifecycle.Event event) {
Activity activity = getActivity();
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
// 此处就把activity的生命周期事件发送到 LifecycleRegistry 中了
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
}
至此,整体流程就通了,不过我还是有点疑问,知道的童鞋可以帮忙解惑下:
-
为何要通过注入
Fragment
的方式来获取Activity
的生命周期, 通过ActivityLifecycleCallbacks
也可以吧? -
为何
ReportFragment
是继承自已被Deprecated的android.app.Fragment
?整套lifecycle的实现是基于
SupportActivity
的,support-fragment
库已被导入,injectIfNeededIn(Activity)
参数类型不需非得是Activity
吧?
小结
-
ReportFragment
在SupportActivity
创建后被注入到Activity中,作为"中介",监听Activity
的生命周期变化,并把事件传递给LifecycleRegistry
; -
LifecycleRegistry
会弱引用其所在的SupportActivity
, 并管理各LifecycleObserver
; - 我们自定义的
LifecycleObserver
实现类, 默认会在运行时通过反射查找并缓存带有OnLifecycleEvent
注解的方法; - 若使用
lifeCycleCompiler
库(kapt("android.arch.lifecycle:compiler:1.1.1")
),则自定义的LifecycleObserver
类会在编译时生成*_LifecycleAdapter
类, 避免运行时反射; -
LifecycleObserver
实现类中的相关注解方法允许带有最多2个参数;
网友评论