Lifecycle,将Activity或Fragment的生命周期与需要根据生命周期进行逻辑处理的类关联起来,减少该类与Activity或Fragment的耦合。
1.使用
/**
* Activity,被观察者
*/
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 添加观察者
getLifecycle().add(new Presenter());
}
}
/**
* Presenter,观察者
*/
public class Presenter implements LifecycleObserver {
private static final String TAG = "Presenter";
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
void onAny(LifecycleOwner owner, Lifecycle.Event event) {
Log.d(TAG, "onAny() called with: owner = [" + owner + "], event = [" + event + "]");
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreate() {
Log.d(TAG, "onCreate() called");
}
// 其他几个生命周期类似写法,不再列举
......
}
被观察者通过getLifecycle().add(new Presenter());
添加观察者;观察者则通过注解@OnLifecycleEvent
的形式观察其生命周期变化。
特别注意:onCreate
onStart
onResume
是先走Activity的相关方法然后是观察者的相关方法;onPause
onStop
onDestory
是先走观察者的相关方法然后是Activity的相关方法。
2. 涉及到的类
-
Lifecycle:持有Android生命周期的抽象类,提供了
addObserver
removeObserver
getCurrentState
方法,生命周期事件Event
和状态State
/**
* Defines an object that has an Android Lifecycle.
*/
public abstract class Lifecycle {
public abstract void addObserver(@NonNull LifecycleObserver observer);
public abstract void removeObserver(@NonNull LifecycleObserver observer);
public abstract State getCurrentState();
public enum Event {
ON_CREATE
... // 生命周期事件不再一一列举
}
public enum State {
INITIALIZED
... // 状态不再一一列举
}
}
-
LifecycleRegistry:
Lifecycle
的实现类,维护了一个观察者列表、处理了生命周期事件
public class LifecycleRegistry extends Lifecycle {
...
// 观察者列表
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>();
...
// 处理生命周期事件
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
...
}
...
}
-
LifecycelObserver:生命周期观察者标记标记接口,无任何方法;实现该接口的类才能被
addObserver
/**
* Marks a class as a LifecycleObserver.
*/
public interface LifecycleObserver {
}
-
LifecycleOwner:拥有Android生命周期的接口,实现该接口的类会持有
Lifecycle
/**
* A class that has an Android lifecycle.
*/
public interface LifecycleOwner {
Lifecycle getLifecycle();
}
类图
Lifecycle.png
3. 原理
原理简单的理解为三步:
1.注册观察者,将需要依赖Activity或Fragment的类注册为观察者,观察者需要实现Lifecycle接口;
2.Fragment和Activity关联Lifecycle,目的是在Frament或Activity触发生命周期时通知Lifecycle;
3.LifecycleRegistry(Lifecycle的实现类)通知观察者,通过反射的方法实现;
3.1 注册观察者
从添加观察者 getLifecycle().addObserver(new Presenter());
入手,了解注册观察者原理
首先会追溯到 LifecycleRegistry
public class LifecycleRegistry extends Lifecycle {
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
...
// 关键代码1 new ObserverWithState
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
...
}
// 静态内部类
static class ObserverWithState {
// 接--关键代码1
ObserverWithState(LifecycleObserver observer, State initialState) {
// 关键代码2 Lifecycling.lifecycleEventObserver
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
...
}
}
}
接着会追溯到 Lifecycling
public class Lifecycling {
// 接--关键代码2
static LifecycleEventObserver lifecycleEventObserver(Object object) {
...
// 关键代码3
return new ReflectiveGenericLifecycleObserver(object);
}
}
接着会追溯到 ReflectiveGenericLifecycleObserver
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
// 接--关键代码3
ReflectiveGenericLifecycleObserver(Object wrapped) {
...
// 关键代码4
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
}
最终追溯到 ClassesInfoCache
final class ClassesInfoCache {
// 接--关键代码4
CallbackInfo getInfo(Class<?> klass) {
...
// 关键代码5
existing = createInfo(klass, null);
return existing;
}
...
// 接--关键代码5
private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) {
...
// 通过反射获得类的方法
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
for (Method method : methods) {
// 找到使用注解 @OnLifecycleEvent 的方法
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
...
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
...
}
// 会创建一个回到的信息类,后续的反射就会从整个信息里取值
CallbackInfo info = new CallbackInfo(handlerToEvent);
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
...
static class CallbackInfo {
// 反射回调时,会从该集合里取值
final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;
CallbackInfo(Map<MethodReference, Lifecycle.Event> handlerToEvent) {
mHandlerToEvent = handlerToEvent;
mEventToHandlers = new HashMap<>();
for (Map.Entry<MethodReference, Lifecycle.Event> entry : handlerToEvent.entrySet()) {
Lifecycle.Event event = entry.getValue();
List<MethodReference> methodReferences = mEventToHandlers.get(event);
if (methodReferences == null) {
methodReferences = new ArrayList<>();
// 向集合里添加事件和对应的回调方法
mEventToHandlers.put(event, methodReferences);
}
methodReferences.add(entry.getKey());
}
}
}
}
注册观察者方法调用关系图
Observer Register3.2 将Fragment或Activity关联Lifecycle
Fragment或Activity持有Lifecycle的对象,在Frament或Activity触发生命周期时通知Lifecycle。Activity和Fragment的关联方式稍有不同。
Fragment的关联比较简单,注意是 androidx.fragment.app.Fragment;
3.2.1 Fragment关联Lifecycle
/**
* androidx.fragment.app.Fragment
*/
public class Fragment implements LifecycleOwner{
// 生命周期(Lifecycle)类
LifecycleRegistry mLifecycleRegistry;
...
@Override
@NonNull
public Lifecycle getLifecycle() {
// 实现 LifecycleOwner 的方法
return mLifecycleRegistry;
}
// 构造函数会初始化 生命周期(Lifecycle)
public Fragment() {
initLifecycle();
}
private void initLifecycle() {
mLifecycleRegistry = new LifecycleRegistry(this);
...
}
// ================= Fragment 生命周期 Create 事件 =================
void performCreate(Bundle savedInstanceState) {
...
// 调用 Fragment 的 onCreate 方法
onCreate(savedInstanceState);
...
// 调用生命周期(Lifecycle)方法通知 onCreate 事件
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
}
// ================= Fragment 生命周期 Start 事件 =================
void performStart() {
...
onStart();
...
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
...
}
// ================= Fragment 生命周期 Resume 事件 =================
void performResume() {
...
onResume();
...
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
...
}
// ================= Fragment 生命周期 Pause 事件;注意这里的调用顺序变了 =================
void performPause() {
...
// 调用生命周期(Lifecycle)方法通知 onPause 事件
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
...
// 先调用了 mLifecycleRegistry ,后调用 onPause()
// 调用 Fragment 的 onResume 方法
onPause();
...
}
// ================= Fragment 生命周期 Stop 事件;注意这里的调用顺序变了 =================
void performStop() {
...
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
...
onStop();
...
}
// ================= Fragment 生命周期 Destroy 事件;注意这里的调用顺序变了 =================
void performDestroy() {
...
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
...
onDestroy();
...
}
}
至此,Fragment的生命周期通过Lifecycle的实现类LifecycleRegistry与Lifecycle关联起来,接下来看一下Activity是如何与Lifecycle关联起来。
3.2.2 Activity关联Lifecycle
Activity并不是直接关联Lifecyle,而是通过一个 ReportFragment
作为中介实现关联回调的。首先看一下Activity的继承关系
从Fragment的分析可以了解到持有生命周期的类(Fragment/Activity)主要是通过 LifecycleRegistry 来通知观察者。
Activity继承比较复杂,如何正确寻找处理Lifecycle的Activity(心路历程...可跳过)
错误线路:首先找到与之相关的类 androidx.fragment.app.FragmentActivity
,他有一个成员变量 mFragmentLifecycleRegistry
,根据Fragment的逻辑去查看 FragmentActivity
的生命周期方法,确实发现有调用 mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event);
方法,但是这个并不是我们要找的。我们知道在添加观察者时需要调用 getLifecycle()
方法,而 FragmentActivity
并没有实现 LifecycleOwner
接口;FragmentActivity
的成员变量 mFragmentLifecycleRegistry
时间是为其内部类 HostCallbacks
服务的。因此这是错误的,我在Debug的时候深深的踩了这个坑......
正确路线:在添加观察者时要调用getLifecycle()
方法,从类图中可以看到 androidx.activity.ComponentActivity
和 androidx.core.app.ComponentActivity
都实现了 LifecycleOwner
接口的getLifecycle()
方法,那么到底是调用哪一个呢?根据继承关系可以得出实际上是会调用 androidx.activity.ComponentActivity
中的方法,根据编译器 ctrl+b
也会引导到这里。
根据正确路线找到了正确的类 androidx.activity.ComponentActivity
(以下简称ComponentActivity),看一下ComponentActivity的生命周期方法,惊奇的发现并没有调用 mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event);
方法,和Fragment不一样(这也是我一直陷入错误路线的原因)。接下来查看一下 ComponentActivity
的 onCreate 方法
查看 ComponentActivity
源码
public class ComponentActivity extends androidx.core.app.ComponentActivity implements LifecycleOwner{
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
...
// 通过一个没有UI的ReportFragment绑定到Activity上来实现触发
ReportFragment.injectIfNeededIn(this);
...
}
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
查看 ReportFragment
源码,可以看到其中有:获取其绑定的Activity的 Lifecycle
并调用 handleLifecycleEvent
方法的代码。以下代码截取的是Api 29 以下的,Api29及以上大同小异
public class ReportFragment{
// 绑定 Activity
public static void injectIfNeededIn(Activity activity) {
...
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
// 以 Create 为例,其他生命周期时间雷同
@Override
public void onActivityCreated(Bundle savedInstanceState) {
...
// 分发事件
dispatch(Lifecycle.Event.ON_CREATE);
}
private void dispatch(@NonNull Lifecycle.Event event) {
...
// 获取其绑定的Activity
dispatch(getActivity(), event);
}
// 最终回调到该方法
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
if (activity instanceof LifecycleRegistryOwner) {
// 调用绑定的Activity的生命周期(Lifecycle)方法通知相关事件
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
// 调用生命周期(Lifecycle)方法通知相关事件
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
}
不要忘记生命周期调用顺序的区别,再放一次图
日志Activity是如何控制以上流程的?查看Activity源码
public class Activity{
// ============================ Create 事件 ============================
final void performCreateCommon() {
...
mFragments.dispatchActivityCreated();
...
}
final void performCreate(Bundle icicle) {
...
// Activity 的onCreate
onCreate(icicle);
...
// Fragment 分发Create
performCreateCommon();
}
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
...
onCreate(icicle, persistentState);
...
performCreateCommon();
}
// ============================ Start 事件 ============================
final void performStart() {
...
// Activity 的 onStart
mInstrumentation.callActivityOnStart(this);
...
// Fragment 分发 Start
mFragments.dispatchStart();
...
}
// ============================ Resume 事件 ============================
final void performResume() {
...
// Activity 的 onStart
mInstrumentation.callActivityOnResume(this);
...
// Fragment 分发 Resume
mFragments.dispatchResume();
...
}
// ============================ Pause 事件 ============================
final void performPause() {
...
// Fragment 分发 Pause
mFragments.dispatchPause();
...
// Activity 的 onPause
onPause();
...
}
// ============================ Stop 事件 ============================
final void performStop(boolean preserveWindow) {
...
// Fragment 分发 Stop
mFragments.dispatchStop();
...
// Activity 的 onStop
mInstrumentation.callActivityOnStop(this);
...
}
// ============================ Destroy 事件 ============================
final void performDestroy() {
...
// Fragment 分发 Stop
mFragments.dispatchDestroy();
// Activity 的 onDestroy
onDestroy();
...
}
}
3.3 LifecycleRegistry通知观察者
通过以上分析得出,最终都会回调到 LifecycleRegistry.handleLifecycleEvent(event)
,看一下该方法做了什么操作
public class LifecycleRegistry extends Lifecycle {
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
...
moveToState(event.getTargetState());
}
private void moveToState(State next) {
...
sync();
...
}
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
...
while (!isSynced()) {
...
// 调用 backwardPass 或 forwardPass
backwardPass(lifecycleOwner);
...
forwardPass(lifecycleOwner);
}
...
}
// 以 forwardPass 为例
private void forwardPass(LifecycleOwner lifecycleOwner) {
// 这里就开始遍历观察者列表 mObserverMap
Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator = mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
// 这里拿到注册的观察者对象
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred && mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
final Event event = Event.upFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event up from " + observer.mState);
}
// 调用观察者的事件分发
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
// 带状态的观察者
static class ObserverWithState {
LifecycleEventObserver mLifecycleObserver;
void dispatchEvent(LifecycleOwner owner, Event event) {
...
// 通知观察者发生变化
mLifecycleObserver.onStateChanged(owner, event);
...
}
}
}
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
...
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
...
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
// 回调
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
final class ClassesInfoCache {
...
// 回调
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);
}
}
}
static final class MethodReference {
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
...
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;
}
...
}
}
4.总结
方法调用关系图
Lifecycle Callback
网友评论