Android Jetpack 之 Lifecycle - 2,2021 移动开发者未来的出路在哪里
}
</pre>
If you use <b>Java 7 Language</b>, Lifecycle events are observed using annotations.
Once Java 8 Language becomes mainstream on Android, annotations will be deprecated, so between
{@link DefaultLifecycleObserver} and annotations,
you must always prefer {@code DefaultLifecycleObserver}.
<pre>
class TestObserver implements LifecycleObserver {
{@literal @}OnLifecycleEvent(ON_STOP)
void onStopped() {}
}
</pre>
<p>
Observer methods can receive zero or one argument.
If used, the first argument must be of type {@link LifecycleOwner}.
Methods annotated with {@link Event#ON_ANY} can receive the second argument, which must be
of type {@link Event}.
<pre>
class TestObserver implements LifecycleObserver {
{@literal @}OnLifecycleEvent(ON_CREATE)
void onCreated(LifecycleOwner source) {}
{@literal @}OnLifecycleEvent(ON_ANY)
void onAny(LifecycleOwner source, Event event) {}
}
</pre>
These additional parameters are provided to allow you to conveniently observe multiple providers
and events without tracking them manually.
*/
public abstract class Lifecycle {
}
意思就是一旦 Java 8 成为 Android 的主流,注解将被弃用,所以介于 DefaultLifecycleObserver 和注解两者之间,更推荐使用 DefaultLifecycleObserver 。
使用方式如下
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
这个库里其实就一个 DefaultLifecycleObserver.java
接口类。之后我们需要 LifecycleObserver
的时候,一般实现 DefaultLifecycleObserver
接口即可(不用再去直接实现 LifecycleObserver 接口),使用方式变成了下面这样:
class NormalActivity : Activity(), LifecycleOwner {
private var lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
override fun getLifecycle(): Lifecycle {
return lifecycleRegistry
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_normal)
lifecycle.addObserver(object : DefaultLifecycleObserver {
//下面的方法视自身情况选择实现
override fun onCreate(owner: LifecycleOwner) {
}
override fun onStart(owner: LifecycleOwner) {
}
override fun onResume(owner: LifecycleOwner) {
}
override fun onPause(owner: LifecycleOwner) {
}
override fun onStop(owner: LifecycleOwner) {
}
override fun onDestroy(owner: LifecycleOwner) {
}
})
}
}
可以看到,这里我们直接在覆写我们需要的生命周期对应回调方法中写入我们的逻辑代码即可。更加简洁。
[](
)LifecycleObserver 之间的转换
我们在使用 LifecycleObserver
时,框架内部会将其转换为GenericLifecycleObserver
或其子类。 其转换行为在类 androidx.lifecycle.Lifecycling#getCallback
中。至于这个方法何时触发,我们后续会分析。
现在先看下这个转换过程
@NonNull
static GenericLifecycleObserver getCallback(Object object) {
// 如果是 FullLifecycleObserver, 转换为 FullLifecycleObserverAdapter
if (object instanceof FullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
}
// 如果是 GenericLifecycleObserver, 不转换
if (object instanceof GenericLifecycleObserver) {
return (GenericLifecycleObserver) object;
}
final Class<?> klass = object.getClass();
// 获取转换 type, GENERATED_CALLBACK 为使用代码生成,REFLECTIVE_CALLBACK 为使用反射调用
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);
}
这个方法的本质,其实就是根据传进来的一个LifecycleObserver
对象,构造出来一个 GenericLifecycleObserver
对象(目前有四个子类:FullLifecycleObserverAdapter
、SingleGeneratedAdapterObserver
、CompositeGeneratedAdaptersObserver
、ReflectiveGenericLifecycleObserver
),而最终构造出来的对象,就包含了我们创建的 LifecycleObserver
的所有信息,包括各种回调方法等。
当我们通过注解的方式来自定义LifecycleObserver
的时候,按照传统方式,必定要通过反射来对注解进行解析,这样就会对性能造成影响。那么如何优化呢?
通过缓存,来避免每次都通过反射获取构造器。
通过注解处理器,在编译时对那些被
@OnLifecycleEvent
注解标注的普通方法,进行预处理,生成以“类名_LifecycleAdapter”命名的类,将各种回调方法直接进行逻辑转换,避免反射,进而来提高性能。
我们先看下仅用反射的情况下 google 是如何优化的
不引入注解处理器时,Lifecycling.getCallback(observer)
返回的是ReflectiveGenericLifecycleObserver
package androidx.lifecycle;
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);
}
}
这里我们主要关注回调信息 CallbackInfo
的获取方式的代码:
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
因为反射的代价是比较大的,所以又通过 ClassesInfoCache.java
这个单例类,为 ReflectiveGenericLifecycleObserver
类要调用的各种方法的相关信息进行了缓存。
点进去看下它的 getInfo(...)
方法内部,是如何获取方法信息的。
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) {
// 先提取父类的 CallbackInfo
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);
}
}
// 再提取接口的 CallbackInfo
Class[] interfaces = klass.getInterfaces();
for (Class intrfc : interfaces) {
for (Map.Entry<MethodReference, Lifecycle.Event> entry : getInfo(
intrfc).mHandlerToEvent.entrySet()) {
// verifyAndPutHandler 的作用是实现了接口或者覆写了父类的方法,但是添加了不同的注解事件。
verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
}
}
// 最后处理类自身的注解
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
// 遍历方法,寻找被 OnLifecycleEvent 注解的方法
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;
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();
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");
}
}
if (params.length > 2) {
throw new IllegalArgumentException("cannot have more than 2 params");
}
MethodReference methodReference = new MethodReference(callType, method);
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
}
CallbackInfo info = new CallbackInfo(handlerToEvent);
// 放入缓存中
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
这里,就能看到对注解进行处理的代码了。
我们再看下另一种优化(使用注解处理器)
首先需要在项目模块中引入
annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.0.0"
复制代码
引入这个之后,会自动生成xxx_LifecycleAdapter
的文件,路径为
/app/build/generated/source/apt/debug/package_name/LifeObserveCustomName_LifecycleAdapter.java
我们先看下效果:
public class LifecyclePresenter implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreateInPresenter(@NotNull LifecycleOwner owner){
System.out.println("on create");
};
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestroyInPresenter(@NotNull LifecycleOwner owner){
System.out.println("on destory");
};
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
void onLifecycleChangedInPresenter(@NotNull LifecycleOwner owner,
@NotNull Lifecycle.Event event){
System.out.println("on any");
}
}
上面的代码在引入注解处理器后,编译项目时就会在 build 目录下自动生成LifecyclePresenter_LifecycleAdapter
public class LifecyclePresenter_LifecycleAdapter implements GeneratedAdapter {
final LifecyclePresenter mReceiver;
LifecyclePresenter_LifecycleAdapter(LifecyclePresenter receiver) {
this.mReceiver = receiver;
}
@Override
public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny,
MethodCallsLogger logger) {
boolean hasLogger = logger != null;
if (onAny) {
if (!hasLogger || logger.approveCall("onLifecycleChangedInPresenter", 4)) {
mReceiver.onLifecycleChangedInPresenter(owner,event);
}
return;
}
if (event == Lifecycle.Event.ON_CREATE) {
if (!hasLogger || logger.approveCall("onCreateInPresenter", 2)) {
mReceiver.onCreateInPresenter(owner);
}
return;
}
if (event == Lifecycle.Event.ON_DESTROY) {
if (!hasLogger || logger.approveCall("onDestroyInPresenter", 2)) {
mReceiver.onDestroyInPresenter(owner);
}
return;
}
}
}
这样通过该依赖库,在编译期把这些标注了的方法进行预处理,然后直接回调这些方法,避免反射,进行提高性能。
我们回头看下Lifecycling.getCallback(observer)
方法中是如何判断 是代码生成还是反射调用的代码
// 获取转换 type, GENERATED_CALLBACK 为使用代码生成,REFLECTIVE_CALLBACK 为使用反射调用
int type = getObserverConstructorType(klass);
// todo 详细过程暂不分析 下面简要分析下
前面已经分析过,引入注解处理器后,会生成xxx_LifecycleAdapter
类,因此如果我们找到这个生成类,则认为采用代码生成方式,否则采取反射调用。
我们看下关键方法
private static int getObserverConstructorType(Class<?> klass) {
if (sCallbackCache.containsKey(klass)) {
return sCallbackCache.get(klass);
}
int type = resolveObserverCallb
ackType(klass);
sCallbackCache.put(klass, type);
return type;
}
private static int resolveObserverCallbackType(Class<?> klass) {
// anonymous class bug:35073837
// 匿名内部类采用反射
if (klass.getCanonicalName() == null) {
return REFLECTIVE_CALLBACK;
}
// 寻找生成类
Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
if (constructor != null) {
// 找到生成类,则采用 GENERATED_CALLBACK
sClassToAdapters.put(klass, Collections
.<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
return GENERATED_CALLBACK;
}
// 是否有方法被 OnLifecycleEvent 注解
boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
if (hasLifecycleMethods) {
// 如果有方法被 OnLifecycleEvent 注解, 则采用反射
return REFLECTIVE_CALLBACK;
}
评论