Android架构组件中的注解

架构组件中的注解

在架构组件中,由于注册了声明周期,所以可以在任何地方利用注解使用声明周期,而不用去添加调用方法啦!这个用途非常广!,Flutter也用到了这个办法管理FlutterView的声明周期

1
2
3
static class BoundLocationListener implements LifecycleObserver

lifecycleOwner.getLifecycle().addObserver(this);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void addLocationListener() {
// Note: Use the Fused Location Provider from Google Play Services instead.
// https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi

mLocationManager =
(LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mListener);
Log.d("BoundLocationMgr", "Listener added");

// Force an update with the last location, if available.
Location lastLocation = mLocationManager.getLastKnownLocation(
LocationManager.GPS_PROVIDER);
if (lastLocation != null) {
mListener.onLocationChanged(lastLocation);
}
}

那么看一下此的实现

首先在上一个流程当中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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<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);
}

在这里判断Observer类型的时候,如果不是以上任何类型的Observer的话,那么就是默认的ReflectiveGenericLifecycleObserver()
那么在在这个类的构造方法

1
2
3
4
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}

从ClassesInfoCache里面拿了一个info

1
2
3
4
5
6
7
8
CallbackInfo getInfo(Class klass) {
CallbackInfo existing = mCallbackMap.get(klass);
if (existing != null) {
return existing;
}
existing = createInfo(klass, null);
return existing;
}

那么在反射建立的方法中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

Class superclass = klass.getSuperclass();
Map<MethodReference, Lifecycle.EventhandlerToEvent = new HashMap<>();
if (superclass != null) {
CallbackInfo superInfo getInfo(superclass);
if (superInfo != null) {
handlerToEvent.putAll(superInfo.mHandlToEvent);
}

Class[] interfaces = klass.getInterfaces();
for (Class intrfc : interfaces) {
for (Map.Entry<MethodReferenceLifecycle.Event> entry : getInfo(
intrfc).mHandlerToEvent.entrySet(){
verifyAndPutHandler(handlerToEvententry.getKey(), entry.getValue()klass);
}

Method[] methods = declaredMethods != null declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
for (Method method : methods) {
OnLifecycleEvent annotation method.getAnnotation(OnLifecycleEvent.clas;
if (annotation == null) {
continue;
}
hasLifecycleMethods = true;
Class<?>[] params method.getParameterTypes();
int callType = CALL_TYPE_NO_ARG;
if (params.length > 0) {
callType = CALL_TYPE_PROVIDER;
i(!params[0].isAssignableFrom(Lifecyclener.class)) {
throw new IllegalArgumentException(
"invalid parameter typeMust be one and instanceoLifecycleOwner");
}
}
Lifecycle.Event event = annotation.value()
if (params.length > 1) {
callType CALL_TYPE_PROVIDER_WITH_EVENT;
i(!params[1].isAssignableFrom(Lifecyclevent.class)) {
throw new IllegalArgumentException(
"invalid parameter typesecond arg must be aevent");
}
if (event != Lifecycle.Event.ON_ANY) {
throw new IllegalArgumentException(
"Second arg is supporteonly for ON_ANY value");
}
}
if (params.length > 2) {
throw neIllegalArgumentException("cannot havmore than 2 params");
}
MethodReference methodReference = neMethodReference(callType, method);
verifyAndPutHandler(handlerToEventmethodReference, event, klass);
}
CallbackInfo info = neCallbackInfo(handlerToEvent);
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klasshasLifecycleMethods);
return info;

那么从中可以看到,作为Observer的注解的方法是不可以有参数的,如果参数为1个,必须是(LifecycleOwner类型)如果行参有两个那么必须是(Lifecycle.Event.class)类型),若为两个以上是不行的
并且在
MethodReference中

1
2
3
4
5
MethodReference(int callType, Method method) {
mCallType = callType;
mMethod = method;
mMethod.setAccessible(true);
}

并且在取消了编译时方法检查

由此我们可知,官方偷偷的留了一手,其实这个注解还有两个隐藏使用方法

首先在Event中可以看到

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public enum Event {

ON_CREATE,

ON_START,

ON_RESUME,

ON_PAUSE,

ON_STOP,

ON_DESTROY,

ON_ANY
}

那么我的注解如果写成

1
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)

会回调所有的方法

从注解代码中可以看到必须是两个参数才会将flog设置为ANY

官方的骚操作

1
2
3
4
5
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);
}

拿到所有evet持有的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@SuppressWarnings("ConstantConditions")
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);
}
}
}

1
2
3
4
5
6
7
8
9
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;

google官方的骚操作

那么这个注解隐藏的两个接口就是

1
2
3
4
5
6
7
8
9
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)

method(LifecycleOwner owner,Lifecycle.Event event)

//或者是

@OnLifecycleEvent(Lifecycle.Event.ONC_REATE)

method(LifecycleOwner owner)


2018.8.7更新

Flutter中用到了这个办法来执行FlutterView的声明周期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
lifecycle.addObserver(new LifecycleObserver() {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
final FlutterRunArguments arguments = new FlutterRunArguments();
arguments.bundlePath = FlutterMain.findAppBundlePath(activity.getApplicationContext());
arguments.entrypoint = "main";
flutterView.runFromBundle(arguments);
GeneratedPluginRegistrant.registerWith(flutterView.getPluginRegistry());
}

@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
flutterView.onStart();
}

@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
flutterView.onPostResume();
}

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
flutterView.onPause();
}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
flutterView.onStop();
}

@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
flutterView.destroy();
}
});

谢谢您的鼓励~