前言
Lifecycles管理 Activity 和 Fragment 生命周期,可以有效地避免内存泄漏和解决android生命周期的常见难题。
· Lifecycle 是一个表示android生命周期及状态的对象。
· LifecycleOwner 用于连接生命周期的对象。
· LifecycleObserver 用于观察LifecycleOwner。
如何管理
- getLifecycle().addObserver(presenter);
public class LifecycleRegistry extends Lifecycle {
//···省略
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
}
}
getLifecycle()返回一个Lifecycle的子类LifecycleRegistry,再调用它的方法addObserver(),生成一个ObserverWithState ,再放入到FastSafeIterableMap里,用于保存观察者并可以再遍历期间处理删除添加操作。
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
//截取关键代码
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
}
AppCompatActivity继承自ComponentActivity ,实现了LifecycleOwner接口,同时持有LifecycleRegistry对象,这个对象可以将其理解为观察者模式的Observable,LifecycleRegistry保存了多个LifecycleObserver,生命周期改变时通知LifecycleObserver进行相应的方法调用。
3.添加一个Fragment来监听activity的生命周期
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
//如何管理生命周期,类似Glide,添加一个Fragment
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
}
4.添加完成Fragment之后,如何真正的感知?
public class ReportFragment extends Fragment {
@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);
}
·················省略
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);
}
}
}
}
可以看出ReportFragment的生命周期函数,都调用了dispatch()方法。
而dispatch()则会判断Activity是否实现了LifecycleOwner接口,如果实现了就调用LifecycleRegistry的handleLifecycleEvent方法,发现没有,最后把感知的处理丢给了LifecycleRegistry来处理,去通知各个LifecycleObserver从而调用对应的Lifecycle.Event。
5.看看handleLifecycleEven()到底做了啥
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
private void sync() {
backwardPass(lifecycleOwner);
forwardPass(lifecycleOwner);
}
就是事件发生时,推导activity的下一状态,可以向前推或者向后推。
关联时关联上了,哪里体现了LifecycleObserver的管理
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
//最终会调到ReflectiveGenericLifecycleObserver
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
第一步生成了ObserverWithState ,这里就是对它来使用。
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
//重点看看这个minfo怎么生成的
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
接着往下看
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
······省略
//获取方法列表
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
for (Method method : methods) {
//获取注解
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation == null) {
continue;
}
hasLifecycleMethods = true;
Class<?>[] params = method.getParameterTypes();
·····省略
}
不难看出,这里通过反射获取到LifecycleObserver 声明的方法,注解,来处理。
网友评论