为什么需要用Lifecycle?
在使用高德地图的SDK时,我们一般都会这样做:
public class MainActivity extends AppCompatActivity {
private TextureMapView mMapView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMapView = new TextureMapView(this);
}
@Override
protected void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
protected void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
}
因为组件必须感知Activity的生命周期,所以一般会直接将代码写到Activity的生命周期方法中。若是当需与Activity生命周期强关联的组件比较多时,Activity类里面就会变得非常臃肿,难以维护。
那么,有没有一种优雅的方式来感知Activity的生命周期呢?希望有一个观察者能够观察到Activity生命周期的变化,并且还不用直接引用Activity,将业务逻辑从Activity抽离出来。有,那就是使用Lifecycle。
简单使用
- 添加依赖
implementation 'androidx.lifecycle:lifecycle-runtime:2.3.1'
- 创建一个实现抽象观察者的具体观察者
public class MyLifecycleObserver implements LifecycleObserver {
@OnLifecycleEvent(value = Lifecycle.Event.ON_CREATE)
private void onCreate() {}
@OnLifecycleEvent(value = Lifecycle.Event.ON_START)
private void onStart() {}
@OnLifecycleEvent(value = Lifecycle.Event.ON_RESUME)
private void onResume() {}
}
- 将被观察者与观察者进行关联
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLifecycle().addObserver(new MyLifecycleObserver());
}
}
Lifecycle是如何感知生命周期的?
通过上面的分析可知,Lifecycle使用了观察者设计模式。抽象观察者是LifecycleObserver
,具体观察者就是我们实现的MyLifecycleObserver
。抽象被观察者是LifecycleOwner
,具体被观察者就是我们的Activity,实现LifecycleOwner
的是我们自己的Activity的父类ComponentActivity
。最后就是连接观察者和被观察者的桥梁Lifecycle
,它的实现类是LifecycleRegistry
。
-
ComponentActivity
做了什么?
在启动我们自己的Activity的onCreate
方法之前,先来看看它的父类ComponentActivity
执行了一些什么操作。
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
...
ReportFragment.injectIfNeededIn(this);
...
}
从方法名可以看出注入了一个Fragment,熟悉Glide的朋友肯定知道这个套路了。添加一个透明的Fragment,用它来感知宿主Activity的生命周期,然后进行转发。
// ReportFragment.java
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();
// Hopefully, we are the first to make a transaction.
manager.executePendingTransactions();
}
}
-
addObserver
做了什么?
分析完了父类Activity的onCreate
方法做的事情后,再来看看我们自己的onCreate
方法做的事。
getLifecycle().addObserver(new MyLifecycleObserver());
getLifecycle
方法获取的对象是一个Lifecycle
,它的实现类是LifecycleRegistry
。上面说过的ReportFragment
就会使用它来将生命周期的变化转发给观察者。
// ComponentActivity.java
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
继续跟进到LifecycleRegistry
的构造方法,它有一个比较重要的属性mState
,默认值 是INITIALIZED
。Lifecycle
中有两个枚举类,一个描述被观察者目前生命周期的状态,一个是用来发给观察者的事件,通知观察者目前被观察者所处的生命周期。如下图:
继续跟进addObserver
方法
// LifecycleRegistry.java
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
...
// 这里的mState一开始是等于INITIALIZED的
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// 注释1
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
// 注释2
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;
}
// mAddingObserverCounter初始化值为0,mHandlingEvent初始值为false,
// 所以isReentrance为false
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
// 注释3
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
// 注释4
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
final Event event = Event.upFrom(statefulObserver.mState);
if (event == null) {
throw new IllegalStateException("no event up from " + statefulObserver.mState);
}
statefulObserver.dispatchEvent(lifecycleOwner, event);
popParentState();
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer);
}
// 注释5
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
mAddingObserverCounter--;
}
先看注释1部分
ObserverWithState statefulObserver = new ObserverWithState(observer,initialState);
将我们的观察者和初始化状态包装成ObserverWithState
对象,在其构造方法内,又创建了一个LifecycleEventObserver
类型的观察者对象,它是一个接口,它继承自LifecycleObserver
,在这里返回的实现类是ReflectiveGenericLifecycleObserver
。
// LifecycleRegistry.java
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
接着看注释2部分
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
将我们的观察者作为key,包装对象ObserverWithState
作为value,将其保存到一个Map中,并且在Map中的value还被维护成了一个双向链表。
继续看注释3部分
// LifecycleRegistry.java
private State calculateTargetState(LifecycleObserver observer) {
Map.Entry previous = mObserverMap.ceil(observer);
State siblingState = previous != null ? previous.getValue().mState : null;
State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)
: null;
return min(min(mState, siblingState), parentState);
}
static State min(@NonNull State state1, @Nullable State state2) {
return state2 != null && state2.compareTo(state1) < 0 ? state2 : state1;
}
计算我们的观察者对象的State
。这里的previous为包含我们的观察者对象的Entry节点的前驱节点,它不为空且它的State
为INITIALIZED
。mParentStates
的size为空,所以在return语句中内层min
方法返回的是INITIALIZED
,而外层min
方法返回还是INITIALIZED
。
继续看注释4部分
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
...
}
我们的观察者对象的mState
以及由上面calculateTargetState
方法返回回来的targetState
相等,所以不会进入while循环。
继续看注释5部分
// LifecycleRegistry.java
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
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);
}
Map.Entry newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
private boolean isSynced() {
if (mObserverMap.size() == 0) {
return true;
}
State eldestObserverState = mObserverMap.eldest().getValue().mState;
State newestObserverState = mObserverMap.newest().getValue().mState;
return eldestObserverState == newestObserverState && mState == newestObserverState;
}
在标记处为注释3的地方的上一句分析了isReentrance
为false,所以进入到sync
方法。先看看进入while
循环的条件判断方法isSynced
。mObserverMap.eldest()
为双向链表的头节点,它的mState
为INITIALIZED
;mObserverMap.newest()
为双向链表的尾节点,也就是我们的观察地者对象,它的mState
也是为INITIALIZED
。而LifecycleRegistry
的mSate
初始值也是INITIALIZED
,所以整个方法返回值为true,while循环体不会执行。
到这里,我们的Activity的onCreate
方法分析完成。接下来就是执行前面提到的ReportFragment
的生命周期了。我们还是以onCreate
方法分例来分析。
ReportFragment生命周期事件转发
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// mProcessListener为空,
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}
private void dispatch(@NonNull Lifecycle.Event event) {
if (Build.VERSION.SDK_INT < 29) {
// Only dispatch events from ReportFragment on API levels prior
// to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks
// added in ReportFragment.injectIfNeededIn
dispatch(getActivity(), event);
}
}
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
...
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
在一个参数的dispatch
方法中,SDK小于29的才会通过ReportFragment
转发生命周期事件,那大于等于29的呢?是通过注册LifeActivityLifecycleCallbacks
来监听Activity的生命周期。可以在ReportFragment#injectIfNeededIn
方法查看。最终生命周期事件转发调用到了LifecycleRegistry#handleLifecycleEvent
方法。
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
moveToState(event.getTargetState());
}
在handleLifecycleEvent
方法内先获取当前event
对应的的state
,传过来的event
为Lifecycle.Event.ON_CREATE
,那么对应的state
为State.CREATED
。
@NonNull
public State getTargetState() {
switch (this) {
case ON_CREATE:
case ON_STOP:
return State.CREATED;
case ON_START:
case ON_PAUSE:
return State.STARTED;
case ON_RESUME:
return State.RESUMED;
case ON_DESTROY:
return State.DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException(this + " has no target state");
}
再回到moveToState
方法
private void moveToState(State next) {
// LifecycleRegistry中的mState初始值为INITIALIZED, 而next为CREATED
if (mState == next) {
return;
}
// 更新mState的值为CREATED
mState = next;
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
// 又回到了我们上面分析过的sync方法。只不过这次会进入这个方法内的while循环
sync();
mHandlingEvent = false;
}
再次回顾sync
方法
private void sync() {
...
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);
}
Map.Entry newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
mState
为CREATED
,而mObserverMap.eldest()
为双向链表的表表头,state
值为INITIALIZED
, 所以第一个if条件不会进入。newest
就是包含我们观察者的节点,此时newest
的mStage
还是INITIALIZED
,所以会进入forwardPass
方法。
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Map.Entry entry = ascendingIterator.next();
// 还记得在注释1提到的ObserverWithState吗?
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();
}
}
}
在注释1处,我们的观察者对象以及mState
被包装成了ObserverWithState
对象,继续查看其dispatchEvent
方法。
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = event.getTargetState();
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
这个mLifecycleObserver
是指哪个对象呢?还是在注释1处,在创建ObserverWithState
对象的构造方法内有对这个值进行赋值,它的类型就是ReflectiveGenericLifecycleObserver
。
// ReflectiveGenericLifecycleObserver.java
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
// ClassInfoCache.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);
}
private static void invokeMethodsForEvent(List 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);
}
}
最后通过反射,调用了我们的观察者实现类MyLifecycleObserver
带有OnLifecycleEvent
注解的方法。
到这里Activity的生命周期onCreate
转发就已经结束。同理,onStart
、onResume
等方法的事件分发差不多都一样。最后附上一张涉及到相关类的UML图。