1、前言
Lifecycle作用:
监听观察Activity、Fragment生命周期,当我们需要在生命周期中做相应的业务,不需要再把代码写到Activity中,起到解耦的作用。
Lifecycle用到了典型的观察者设计模式,在Lifecycle中包含了两个元素LifecycleObserver、LifecycleOwner。分别是观察者和被观察者。而我们的Activity当实现了LifecycleOwner接口之后,就充当了被观察者的身份。在添加关联指定的观察者LifecycleObserver,就能观察Activity的生命周期的变化。
2、简单的使用
Lifecycle有好几种用法,我们来介绍一下比较简单的,也是目前谷歌推荐的使用方法。
- 引入依赖
// 这种依赖支持是 精简版本
implementation "androidx.lifecycle:lifecycle-runtime:2.0.0"
implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
implementation "androidx.lifecycle:lifecycle-common-java8:2.0.0"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.0.0"
- 创建一个LifecycleEventObserver类,作为观察者,实现了LifecycleObserver接口
/**
* author : weishixiong
* e-mail : weishixiong@pudutech.com
* date : 2022/2/21 13:50
* desc :MyLifecycleEventObserver 观察者、监听Activity生命周期
*/
class MyLifecycleEventObserver : LifecycleEventObserver {
val TAG = javaClass.simpleName
/**
* '
* @param source LifecycleOwner 宿主、比如当前是MainActivity
* @param event Event 事件 比如Activity的生命周期
*/
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
Log.e(TAG, "onStateChanged: source = ${source} and event = ${event.targetState}")
}
}
- 创建一个MainActivity作为被观察者,继承了ComponentActivity,并实现了LifecycleOwner接口
调用addObserver将被观察者和观察者关联
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifecycle.addObserver(MyLifecycleEventObserver())
}
}
- 启动Activity,观察Activity生命周期变化的时候,onStateChanged方法的回调
E/MyLifecycleEventObserver: onStateChanged: source = com.example.lifecycle.MainActivity@bcfe03c and event = CREATED
E/MyLifecycleEventObserver: onStateChanged: source = com.example.lifecycle.MainActivity@bcfe03c and event = STARTED
E/MyLifecycleEventObserver: onStateChanged: source = com.example.lifecycle.MainActivity@bcfe03c and event = RESUMED
3、源码的简单分析
- 从初始化的地方出发
lifecycle.addObserver(MyLifecycleEventObserver())
创建我们定义的MyLifecycleEventObserver的对象,然后通过Activity的成员变量LifecycleRegistry mLifecycleRegistry 调用addObserver方法,
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
enforceMainThreadIfNeeded("addObserver");
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
.............
以下源码省略
在addObserver方法中通过一个mObserverMap存储ObserverWithState对象,其中ObserverWithState对象包含了我们的LifecycleEventObserver对象和当前的状态mState = INITIALIZED(初始化的状态)。
此时我们总结就是:被观察者将当前的状态和观察者关联并存储起来。
- 再来观察Activity生命周期变化的时候发生了什么?
以上我们知道Activity已经将当前的状态和观察者LifecycleEventObserver存储到了map里。接着Activity生命周期变化的时候,怎么通知LifecycleEventObserver呢?
来看一下ComponentActivity的onCreate方法
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
mSavedStateRegistryController.performRestore(savedInstanceState);
mContextAwareHelper.dispatchOnContextAvailable(this);
super.onCreate(savedInstanceState);
//绑定一个空白的ReportFragment
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
LifecycleCallbacks.registerIn(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();
}
}
核心的代码就是我们的Activity绑定了一个空白的ReportFragment。这样一来Activity的生命周期和ReportFragment的生命周期就会关联起来。接着我们就直接观察ReportFragment生命周期即可,
我们看到onActivityCreated,其实就等于Activity的onCreated
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
//将事件分发下去
dispatch(Lifecycle.Event.ON_CREATE);
}
onActivityCreated方法中核心代码调用了dispatch方法,将事件分发下去,我们再观察dispatch方法
@SuppressWarnings("deprecation")
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
//我们的Activity 实现了LifecycleOwner接口,因此观察此代码
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
拿到宿主Activity 中的LifecycleRegistry对象,调用handleLifecycleEvent方法,继续分发事件
对齐事件
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);
}
Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
以上的代码主要就是对齐事件,接着调用两个核心的函数分发事件backwardPass和forwardPass,我们直接观察其实一个即可因为最终都会调用observer.dispatchEvent(lifecycleOwner, event);
private void forwardPass(LifecycleOwner lifecycleOwner) {
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();
}
}
}
在分发事件的时候就获取之前mObserverMap存储的的ObserverWithState对象 调用其dispatchEvent方法,传入lifecycleOwner和当前事件,lifecycleOwner就是当前Activity,因为我们Activity实现了该接口。event就是当前的CREATED事件。
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 = event.getTargetState();
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
在dispatchEvent方法中就拿到LifecycleEventObserver mLifecycleObserver对象,调用其onStateChanged方法。mLifecycleObserver对象就是我们调用addObserver添加进来的。这样就触发了我们自定义的MyLifecycleEventObserver的onStateChanged方法,在onStateChanged方法就拿到了CREATED事件和宿主Activity
我们用一张图来概况大概的流程:
image.png
在源码中还有一段关键的部分:状态机的对齐,我们在上面没有详细讲解。主要介绍了整体的事件分发的流程
网友评论