android andegine源码,Android Architecture Component之Lifecycle-Aware Components源码分析

首先看下被观察者LifecycleRegistry,我们看下他的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--;

}

我们的被观察着传入进来之后,首先被封装成ObserverWithState,意思是带状态的Observer,初始化的是INITIALIZED或者DESTROYED,然后放入我们的mObserverMap,管理起来。我们看下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;

}

}

里面有两个变量,mState存放的是这个observer的状态,传入进来的observer通过Lifecycling.getCallback(observer)返回了一个GenericLifecycleObserver对象,我们先看下getCallback方法做了什么

@NonNull

static GenericLifecycleObserver getCallback(Object object) {

if (object instanceof FullLifecycleObserver) {

return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);

}

if (object instanceof GenericLifecycleObserver) {

return (GenericLifecycleObserver) object;

}

final Class> klass = object.getClass();

int type = getObserverConstructorType(klass);

if (type == GENERATED_CALLBACK) {

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

}

当调用 getCallback 时,Lifecycling 会根据传入的 Object(LifecycleObserver)调用 getGeneratedAdapterConstructor。接着看源码

@Nullable

private static Constructor extends GenericLifecycleObserver> getGeneratedAdapterConstructor(

Class> klass) {

final String fullPackage = klass.getPackage().getName();

String name = klass.getCanonicalName();

// anonymous class bug:35073837

if (name == null) {

return null;

}

final String adapterName = getAdapterName(fullPackage.isEmpty() ? name :

name.substring(fullPackage.length() + 1));

try {

@SuppressWarnings("unchecked")

final Class extends GenericLifecycleObserver> aClass =

(Class extends GenericLifecycleObserver>) Class.forName(

fullPackage.isEmpty() ? adapterName : fullPackage + "." + adapterName);

return aClass.getDeclaredConstructor(klass);

} catch (ClassNotFoundException e) {

final Class> superclass = klass.getSuperclass();

if (superclass != null) {

// 找不到 LifecycleAdapter 时获取父类的 LifecycleAdapter

return getGeneratedAdapterConstructor(superclass);

}

} catch (NoSuchMethodException e) {

// this should not happen

throw new RuntimeException(e);

}

return null;

}

static String getAdapterName(String className) {

return className.replace(".", "_") + "_LifecycleAdapter";

}

不难看出,getGeneratedAdapterConstructor 主要是获取 annotationProcessor 生成的 xxx_LifecycleAdapter(eg:我们定义了MyLifecycle,就会自动生成MyLifecycle_LifecycleAdapter,存放在build/generated/source/apt文件夹下,感兴趣的同学请看怎么编译器生成注解的文章)的构造函数,并通过反射实例化返回到 getCallback 中。

需注意的是,如果找不到 LifecycleAdapter 且 object(LifecycleObserver) 存在父类时会试图获取父类的LifecycleAdapter(估计是为了应对混淆时只混淆了子类的情况)。

LifecycleAdapter的主要作用就是把我们写的MyLifecycle转化为我们的GenericLifecycleObserver。

apt(编译期)自动生成的MyLifecycle_LifecycleAdapter源码如下:

public class MyLifecycle_LifecycleAdapter implements GeneratedAdapter {

final MyLifecycle mReceiver;

MyLifecycle_LifecycleAdapter(MyLifecycle 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("onAny", 4)) {

mReceiver.onAny(owner,event);

}

return;

}

if (event == Lifecycle.Event.ON_CREATE) {

if (!hasLogger || logger.approveCall("onCreate", 1)) {

mReceiver.onCreate();

}

return;

}

if (event == Lifecycle.Event.ON_DESTROY) {

if (!hasLogger || logger.approveCall("onDestroy", 1)) {

mReceiver.onDestroy();

}

return;

}

}

}

通过callMethods根据不同得到event执行不同的方法回调,调用我们自己定义的MyLifecycle的各个方法。

回到getCallback方法,首先我们获取MyLifecycle_LifecycleAdapter构造方法方法,然后反射生产GeneratedAdapter对象.

如果只有一个构造的话返回SingleGeneratedAdapterObserver,多个的话返回CompositeGeneratedAdaptersObserver都失败的话返回ReflectiveGenericLifecycleObserver,估计是为了应对代码混淆的情况。这里我们只有一个这样的构造方法,所以

我们看下SingleGeneratedAdapterObserver的源码

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

}

}

GeneratedAdapter就是MyLifecycle_LifecycleAdapter,我们在SingleGeneratedAdapterObserver的源码中看到有个onStateChanged方法,在调用onStateChanged的时候会调用GeneratedAdapter的callMethods,从而会调用MyLifecycle的方法。那么onStateChanged是谁调用的?

我们回到ObserverWithState,发现了它的dispatchEvent方法里面有个onStateChanged,而这个mLifecycleObserver就是我们上面讲的SingleGeneratedAdapterObserver,它是通过我们上面讲的Lifecycling.getCallback(observer)生成的。

void dispatchEvent(LifecycleOwner owner, Event event) {

State newState = getStateAfter(event);

mState = min(mState, newState);

mLifecycleObserver.onStateChanged(owner, event);

mState = newState;

}

后面会讲到怎么通知所有的观察者处理事件,我们先总结下添加及调用的过程。

334d674cf65b

image

acitivty中调用LifecycleRegistry的ddObserver(LifecycleObserver observer)

LifecycleObserver 被封装成了ObserverWithState并存入我们集合中

ObserverWithState 在构造的时候,调用了Lifecycling.getCallback(observer)

getCallback(observer)调用了createGeneratedAdapter()

createGeneratedAdapter通过反射生了MyLifecycle_LifecycleAdapter对象

MyLifecycle_LifecycleAdapter是在编译器有apt帮我们生成的

最后返回一个SingleGeneratedAdapterObserver对象

在ObserverWithState的dispatchEvent()方法调用了SingleGeneratedAdapterObserver对象的onStateChanged方法,

它又调用了MyLifecycle_LifecycleAdapter的callMethods,然后再调用了我们自定义的MyLifecycle方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值