Jetpack之Lifecycle
Lifecycle是谷歌推出用来帮助开发者管理Activity和Fragment等的生命周期的,避免开发者在各个生命周期中写大量重复性类似的代码逻辑,同时使得我们的监听者与Activity或Fragment解耦。
1.简述
Lifecycle整套逻辑与观察者模式类似,由LifecycleOwner触发事件,即它是事件源,而我们自己写的观察者则接收这些事件并处理。为了规范使用,我们的观察者必然遵循一定的规则(接口)。
2.使用
在Lifecycle中,需要我们创建Observer(实现LifecycleObserver接口,该接口是个空接口,可以理解为一种标记),用于监听声明周期状态,同时使用注解的方式,来指明各个生命周期触发时对应的调用方法。例如
public class ActivityLifecycleObserver implements LifecycleObserver {
private static final String TAG = "ActivityObserver";
// 当activity调用了onResume方法时,会回调到这个方法
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onHostResume(){
Log.e(TAG, "host invoke resume, thread: " + Thread.currentThread().getName());
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onHostDestroy(){
Log.e(TAG, "host invoke destroy");
}
}
注意到我们的回调方法中打印的日志,结果如下:
E/ActivityObserver: host invoke resume, thread: main
也就是说生命周期观察者是运行在主线程中的,因此我们要避免在方法内部做耗时操作处理。
2.1 简单使用
在新版本中AppCompatActivity的父类ComponentActivity已经实现了LifecycleOwner接口,因此我们只需要在其中注册我们的Observer即可。
public class MainActivity extends AppCompatActivity {
private ActivityLifecycleObserver mObserver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 注册观察者
mObserver = new ActivityLifecycleObserver();
getLifecycle().addObserver(mObserver);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
这样我们的Observer就可以监听到Activity的生命周期的变化了。可以发现我们不需要在onResume或者onDestroy方法中写任何逻辑,就可以完成监听操作了,这样避免了传统方式会在这些生命周期方法中存在大量重复性的逻辑。
2.2 自定义LifecycleOwner
我们创建一个自己的Observable并实现LifecycleOwner,在内部我们维护一套类似Activity生命周期的方法,如下
public class Observable implements LifecycleOwner {
private LifecycleRegistry mLifecycleRegistry;
public Observable() {
mLifecycleRegistry = new LifecycleRegistry(this);//1
getLifecycle().addObserver(new ActivityLifecycleObserver());//2
}
public void onCreate(){
mLifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);//3
}
public void onResume(){
mLifecycleRegistry.setCurrentState(Lifecycle.State.RESUMED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
在1处创建LifecycleRegistry,用于协助我们Observable来发送事件,并在getLifecycle方法中返回它。在2处添加我们之前定义的Observer(注意:我们应该在使用这个新的LifecycleOwner实例时把旧的实例中添加的观察者移除,避免出现多个被观察者同时持有一个观察者的情况,具体可以通过getLifecycle().removeObserver(mObserver)来移除),在3处发送事件,这样就模拟了类似Activity的操作了。
2.3 Lifecycle有什么优势呢
在上面分析中,知道在activity的生命周期中,我们不需要再进行写一些列重复性的代码,下面具体对比一下两种不同方式的效果。(示例来源于谷歌官方文档)
具体以定位功能为例,在传统方式中,我们在activity中的大致逻辑如下:
class MyActivity extends AppCompatActivity {
private MyLocationListener myLocationListener;
public void onCreate(...) {
myLocationListener = new MyLocationListener(this, location -> {
// update UI
});
}
@Override
public void onStart() {
super.onStart();
Util.checkUserStatus(result -> {
// what if this callback is invoked AFTER activity is stopped?
if (result) {
myLocationListener.start();
}
});
}
@Override
public void onStop() {
super.onStop();
myLocationListener.stop();
}
}
“虽然此示例看起来没问题,但在真实的应用中,最终会有太多管理界面和其他组件的调用,以响应生命周期的当前状态。管理多个组件会在生命周期方法(如 onStart() 和 onStop())中放置大量的代码,这使得它们难以维护。
此外,无法保证组件会在 Activity 或 Fragment 停止之前启动。在我们需要执行长时间运行的操作(如 onStart() 中的某种配置检查)时尤其如此。这可能会导致出现一种竞争条件,在这种条件下,onStop() 方法会在 onStart() 之前结束,这使得组件留存的时间比所需的时间要长。” 这时谷歌中文官方原话。
而如果我们使用Lifecycle呢,“我们可以让 MyLocationListener 类实现 LifecycleObserver,然后在 onCreate() 方法中使用 Activity 的 Lifecycle 对其进行初始化。这样,MyLocationListener 类便可以“自给自足”,这意味着,对生命周期状态的变化做出响应的逻辑会在 MyLocationListener(而不是在 Activity)中进行声明。让各个组件存储自己的逻辑,可使 Activity 和 Fragment 逻辑更易于管理。”
同时,如果LifecycleOwner的生命周期并没有处于活动状态,那么应该避免继续回调操作,“例如,如果回调在 Activity 状态保存后运行 Fragment 事务,就会引发崩溃,因此我们绝不能调用该回调。” 所以,Lifecycle给观察者提供了查询LifecycleOwner的状态信息,这样观察者与被观察者之间的耦合降到最低。基本逻辑类似如下:
class MyLocationListener implements LifecycleObserver {
private boolean enabled = false;
public MyLocationListener(Context context, Lifecycle lifecycle, Callback callback) {
...
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
void start() {
if (enabled) {
// connect
}
}
public void enable() {
enabled = true;
if (lifecycle.getCurrentState().isAtLeast(STARTED)) {
// connect if not connected
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void stop() {
// disconnect if connected
}
}
这里举例暂且说到这里,其实这里看出来,使用Lifecycle之后效果也有一定麻烦。而且还存在一部分类似的模板逻辑可以继续抽象出来,例如在LifecycleOwner的生命周期处于非活动状态时,可以停止数据加载过程(在这里是定位查询的功能)。实际上jetpack中这些交给了LiveData和ViewModel,毕竟这与本文主题相悖,在最后总结时来看看谷歌推荐的最佳用法。
3.原理分析
通过前面的观察者模式的UML图,我们知道观察者模式中被观察者与观察者是一种聚合的关系。那么在Observable中必然维护了一个Observer的引用列表,事件触发时,遍历列表并调用相关方法。下面带着这个结论,阅读源码。
3.1 注册
首先找到分析入口,注册观察者:
getLifecycle().addObserver(mObserver);
方法回调到Lifecycle接口中,从前文我们知道实际上调用该逻辑的是LifecycleRegistry。
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
LifecycleRegistry.java
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);//1
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);//2
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--;
}
在注释1处创建了一个ObserverWithState对象,并传入了LifecycleObserver对象,在注释2处调用了mObserverMap.putIfAbsent方法,mObserverMap是一个以LifecycleObserver为key、FastSafeIterableMap类型的数据结构,内部维护了一个HashMap。我们暂且不去深入了解其内部实现,继续主路线分析。
在putIfAbsent方法中逻辑如下,从方法名和逻辑都可以看出,如果元素不存在在集合中,则会调用put操作。
@Override
public V putIfAbsent(@NonNull K key, @NonNull V v) {
Entry<K, V> current = get(key);
if (current != null) {
return current.mValue;
}
mHashMap.put(key, put(key, v));
return null;
}
至此,一条引用链:Activity(或其他LifecycleOwner)--->LifecycleRegistry ----> FastSafeIterableMap(存储ObserverWithState集合)---->LifecycleObserver。从整个逻辑来看,LifecycleRegistry实现了Lifecycle接口,而我们Activity实现了LifecycleOwner接口,并在内部创建了LifecycleRegistry对象,如下ComponentActivity代码注释1处。
ComponentActivity.java
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
...
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);//1
private final SavedStateRegistryController mSavedStateRegistryController =
SavedStateRegistryController.create(this);
...
}
这也就很好理解,为什么Activity等实现了接口名称为LifecycleOwner了,其内部持有了Lifecycle实现类LifecycleRegistry对象。LifecycleRegistry内部维护了一个存储着LifecycleObserver的集合,通过它实现了观察者和被观察者之间的聚合关系。因此上面的观察者模式的UML图,可以大致转换为下面的UML类图。
3.2 事件发送
上面观察者与被观察者已经建立了聚合关系,接下来就是被观察者发送事件并通知观察者处理了。
前面由代码分析,在activity的生命周期中没有调用相关的LifecycleRegistry的setCurrentState方法,而我们在自定义的LifecycleOwner调用了这些方法,LifecycleOberver接收到了事件。因此我们直接进入LifecycleOwner的实现者ComponentActivity。
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);//1
private final SavedStateRegistryController mSavedStateRegistryController =
SavedStateRegistryController.create(this);
...
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
ReportFragment.injectIfNeededIn(this);//2
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
...
@CallSuper
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
Lifecycle lifecycle = getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).setCurrentState(Lifecycle.State.CREATED);//3
}
super.onSaveInstanceState(outState);
mSavedStateRegistryController.performSave(outState);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;//4
}
}
在注释1处创建了LifecycleRegistry即Lifecycle的实现类,并在注释4处LifecycleOwner的getLifecycle方法中返回了上述对象。我们只在注释3看到调用了我们之前的setCurrentState方法,而其他地方没有调用过。其实关键的逻辑在注释2处,如下
ReportFragment.java
...
public static void injectIfNeededIn(Activity activity) {
// ProcessLifecycleOwner should always correctly work and some activities may not extend
// FragmentActivity from support lib, so we use framework fragments for activities
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
// Hopefully, we are the first to make a transaction.
manager.executePendingTransactions();
}
}
...
上述逻辑中通过activity拿到FragmentManager,并通过add方法添加了创建的ReportFragment对象,因为activity的生命周期和fragment生命周期之间有一定的关系,所以生命周期的变动都交给了ReportFragment来协助完成。这种依赖无页面的Fragment来实现生命周期监听的方式,在Glide、旧版RxPermissions也是通过这种方式实现的。
public class ReportFragment extends Fragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}
@Override
public void onStart() {
super.onStart();
dispatchStart(mProcessListener);
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
dispatchResume(mProcessListener);
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);
// just want to be sure that we won't leak reference to an activity
mProcessListener = null;
}
private void dispatch(Lifecycle.Event event) {
Activity activity = getActivity();
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
}
上述所有方法都调用了dispatch方法,在dispatch方法中判断activity所实现的接口类型,通过源码查看可以知道,LifecycleRegistryOwner接口中也有一个getLifecycle方法,而返回类型是LifecycleRegistry。通过前面代码,在LifecycleOwner中,activity中使用的也是LifecycleRegistry,因此最终上面dispatch方法最终都是调用到了LifecycleRegistry中的handleLifecycleEvent方法。
LifecycleRegistry.java
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);//1
moveToState(next);
}
private void moveToState(State next) {
if (mState == next) {
return;
}
mState = next;
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
+ "garbage collected. It is too late to change lifecycle state.");
}
while (!isSynced()) {
mNewEventOccurred = false;
// no need to check eldest for nullability, because isSynced does it for us.
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
在1处调用了getStateAfter方法,即根据当前的Event类型,返回不同的CREATED等State类型,它是一种枚举类型,表示的是状态;而Event也是一种枚举,表示的一种事件类型,即我们常见的onCreate事件等。可以看到当我们调用了onCreate或onStop事件方法,将会进入CREATED状态...
LifecycleRegistry.java
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);
}
这两个枚举State和Event之间的关系如下图(图片来源于google官方文档)
在State与Event关系中,谷歌官方文档指出Lifecycle中ON_STOP事件触发与实际Activity中onStop方法的调用存在不一致的情况,主要原因是为了避免 onSaveInstanceState()方法与onStop()方法之间修改页面可能会导致的异常:
调用了onSaveInstanceState()方法之后,未必会调用onStop方法,但这个时候不应该修改页面了,否则有可能出现数据不一致或者报错异常,但这时State仍然处于STARTED状态,因此为了避免出现这个问题,“自 1.0.0-rc1 版本起,当调用 onSaveInstanceState() 时,会将 Lifecycle 对象标记为 CREATED 并分派 ON_STOP,而不等待调用 onStop() 方法”。
比如我们做个测试,利用按钮手动触发onSaveInstanceState方法,观察日志情况,activity逻辑如下:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private ActivityLifecycleObserver mObserver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 注册观察者
mObserver = new ActivityLifecycleObserver();
getLifecycle().addObserver(mObserver);
}
@Override
protected void onStop() {
super.onStop();
Lifecycle.State currentState = getLifecycle().getCurrentState();
Log.e(TAG,"onStop, current state is "+currentState);
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
Lifecycle.State currentState = getLifecycle().getCurrentState();
Log.e(TAG,"onSaveInstanceState, current state is "+currentState);
}
public void invokeSave(View view) { //对应btn的onClick
// 手动触发onSaveInstanceState
onSaveInstanceState(new Bundle());
}
}
按下按钮,输出日志如下:
E/MainActivity: onSaveInstanceState, current state is CREATED
再退出整个activity,输出日志如下:
E/MainActivity: onStop, current state is CREATED
E/MainActivity: onSaveInstanceState, current state is CREATED
也就是说按下按钮时,并没有触发onStop方法,但状态已经转变为了CREATED状态,这与activity中流程不太一致。
最终调用backwardPass或forwardPass方法。这里以backwardPass方法为例,最终看到调用到了ObserverWithState的dispatchEvent方法
LifecycleRegistry.java
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
Event event = downEvent(observer.mState);
pushParentState(getStateAfter(event));
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
而ObserverWithState就是在注册时创建并被put到集合中的对象。
LifecycleRegistry.java
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);//2
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);//1
mState = newState;
}
}
在1处调用到了LifecycleEventObserver的onStateChanged方法。前面我们自定义创建是LifecycleObserver,而LifecycleEventObserver是什么?在注释2处是它的创建点,而我们之前创建ObserverWithState时传入了LifecycleObserver对象,核心进入到注释2处。
Lifecycling.java
@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object object) {
boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
if (isLifecycleEventObserver && isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
(LifecycleEventObserver) object);
}
if (isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
}
if (isLifecycleEventObserver) {
return (LifecycleEventObserver) 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创建是通过注解方式完成的,所以内部逻辑实际上调用了最后的ReflectiveGenericLifecycleObserver创建过程,因此最终进入了ReflectiveGenericLifecycleObserver中。
ReflectiveGenericLifecycleObserver.java
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());//1
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
在注释1处内部调用了getInfo方法来创建CallbackInfo。
ClassesInfoCache.java
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);
}
}
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
for (Method method : methods) {
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);//1
if (annotation == null) {
continue;
}
hasLifecycleMethods = true;
Class<?>[] params = method.getParameterTypes();
int callType = CALL_TYPE_NO_ARG;
//2
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);//3
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);//4
}
CallbackInfo info = new CallbackInfo(handlerToEvent);
mCallbackMap.put(klass, info);//5
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
在注释1处看到了我们之前的OnLifecycleEvent注解,在内部通过反射获取到所定义的所有方法,并找到所有被OnLifecycleEvent注解的方法。在注释2处,可以发现我们定义的LifecycleObserver类中生命周期的方法最多可以有两个参数,在不同状态下有不同的要求。在注释3处创建了MethodReference类型,并在注释4处把前面的methodReferce存入handlerToEvent(Map数据结构类型),在注释5处通过put方法把ClassInfo存入mCallbackMap中,该mCallbackMap是一个HashMap。
最后回到ReflectiveGenericLifecycleObserver的onStateChanged方法,如下注释1中,并调用invokeCallbacks方法。
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
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);//1
}
}
ClassesInfoCache.java
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);
}
可以看出来,调用了invokeMethodsForEvent方法,如下,调用handlers拿到MethodReference类,并调用invokeCallback方法
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);
}
}
}
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
//noinspection TryWithIdenticalCatches
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);
}
}
最终完成了方法的调用,即观察者响应触发事件。
总结
1.所有实现了LifecycleObserver接口的类,被注解修饰的方法会被注册时收集起来,最后事件触发时通过反射调用。最终我总结整体UML类图如下:
2.谷歌官方文档给出了Lifecycle使用的最佳方法,下面摘自原文。
1)使界面控制器(Activity 和 Fragment)尽可能保持精简。它们不应试图获取自己的数据,而应使用 ViewModel 执行此操作,并观察 LiveData 对象以将更改体现到视图中。
2)设法编写数据驱动型界面,对于此类界面,界面控制器的责任是随着数据更改而更新视图,或者将用户操作通知给 ViewModel。
3)将数据逻辑放在 ViewModel 类中。 ViewModel 应充当界面控制器与应用其余部分之间的连接器。不过要注意,ViewModel 不负责获取数据(例如,从网络获取)。
ViewModel 应调用相应的组件来获取数据,然后将结果提供给界面控制器。
4)使用 Data Binding 在视图与界面控制器之间维持干净的接口。这样一来,您可以使视图更具声明性,并尽量减少需要在 Activity 和 Fragment 中编写的更新代码。如果您更愿意使用 Java 编程语言执行此操作,请使用诸如 Butter Knife 之类的库,以避免样板代码并实现更好的抽象化。
5)如果界面很复杂,不妨考虑创建 presenter 类来处理界面的修改。这可能是一项艰巨的任务,但这样做可使界面组件更易于测试。
6)避免在 ViewModel 中引用 View 或 Activity 上下文。 如果 ViewModel 存在的时间比 Activity 更长(在配置更改的情况下),Activity 将泄露并且不会由垃圾回收器妥善处置。
7)使用 Kotlin 协程管理长时间运行的任务和其他可以异步运行的操作。
整体的UML结构图
上面内容涉及到LiveData和ViewModel等其他知识,以及MVVM,需要我们深入继续学习它们。
参考:
官方文档:https://developer.android.google.cn/topic/libraries/architecture/lifecycle#java