其他分享
首页 > 其他分享> > Android Jetpack 之 Lifecycle - 2(2),flutter蓝牙打印

Android Jetpack 之 Lifecycle - 2(2),flutter蓝牙打印

作者:互联网

所以在分析 LifecycleRegistry之前我们先看下LifecycleObserver

生命周期观察者 (LifecycleObserver)

LifecycleObserver 基本介绍

标记接口 LifecycleObserver 表示生命周期观察者,是 lifecycle-aware 组件。

public interface LifecycleObserver {

}

这个接口用来声明它的实现类是生命周期观察者 ,我们要在这个类里接收到LifecycleOwner的生命周期变化事件,然后做自身逻辑。

但当我们看到LifecycleObserver这个接口时,第一感觉是比较奇怪:这个接口竟然是空的。那我们如何去接受生命周期变化的事件呢?(通常正常的是回调接口)

其实开头就介绍过用法了,google的做法是配合注解 OnLifecycleEvent 使用,LifecycleObserver 只是起一个声明和约束作用。其内部继承数如下图:

看到这么多类似的接口,我猜或许这是因为生命周期钩子比较多,如果全都放在接口里,那么实现者需要添加很多空实现方法,可阅读性降低。

比如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);

}

这个接口就将所有的生命周期函数声明了,如果我们实现这个接口,就得重写所有接口,然而我们不一定要用这么多接口。(其实你想用也用不了,这个接口不是public,我们不能实现)

我们知道用注解的话大多数是反射解析的,这就涉及到性能问题,当然使用apt可以在编译期解决这个问题。这点后文会详细分析。

如果我们不想用注解,又不想一下子实现所有的方法,可以吗? 答案是肯定的。java8的接口default方法。而且google也鼓励我们用这种方式,那就是DefaultLifecycleObserver

DefaultLifecycleObserver

注意:在androidx.lifecycle.Lifecycle类的顶部注释里有一段

/**

*/

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 对象(目前有四个子类:FullLifecycleObserverAdapterSingleGeneratedAdapterObserverCompositeGeneratedAdaptersObserverReflectiveGenericLifecycleObserver),而最终构造出来的对象,就包含了我们创建的 LifecycleObserver 的所有信息,包括各种回调方法等。

当我们通过注解的方式来自定义LifecycleObserver 的时候,按照传统方式,必定要通过反射来对注解进行解析,这样就会对性能造成影响。那么如何优化呢?

我们先看下仅用反射的情况下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);

}

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

}

标签:LifecycleOwner,Jetpack,void,Lifecycle,LifecycleObserver,owner,Android,flutter,Ev
来源: https://blog.csdn.net/m0_66144992/article/details/122729965