lifecycle
Lifecycle是个抽象类,抛去里面的枚举Event和State,只有三个方法,分别是addObserver、removeObserver和getCurrentState
LifecycleEventObserver
观察者,LifecycleObserver的子接口,与Lifecycle配合使用,观察Lifecycle的生命状态,通过里面的onStateChanged方法收到通知
注册观察者
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
移除观察者
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
获取当前的状态
@MainThread
@NonNull
public abstract State getCurrentState();
那么它是怎么监听activity的生命周期的呢,在开始一直以为是在activity的某一级子类中,每个生命周期的方法中更改Lifecycle中记录的状态,但是一路查看下去发现并没有这个行为。
直到在ComponentActivity才发现跟Lifecycle相关的东西
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
HasDefaultViewModelProviderFactory,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
对,就是这个LifecycleOwner,LifecycleOwner是个接口,里面只定义一个行为,获取Lifecycle
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
这种面向接口和单一职责的设计方式,深得我心...
回去看ComponentActivity 中的实现,getLifecycle方法返回一个LifecycleRegistry类型的对象,不用想了,这个LifecycleRegistry肯定是Lifecycle的实现类,
这个实现类除了实现了Lifecycle的三个方法,另外多了好几个方法,其中最令人欣喜的就是终于有了设置生命状态和通知观察者的方法
@Deprecated
@MainThread
public void markState(@NonNull State state) {
setCurrentState(state);
}
@MainThread
public void setCurrentState(@NonNull State state) {
moveToState(state);
}
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
private void moveToState(State next) {
if (mState == next) {
return;
}
//在这里更改了lifecycle当前的状态
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() {
//...省略部分代码
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
//通知lifecycleOwner
backwardPass(lifecycleOwner);
}
Entry newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
//通知lifecycleOwner
forwardPass(lifecycleOwner);
}
}
其中有两个主要逻辑方法,都是分发状态事件(dispatchEvent)的
在里面会遍历观察者们(注意:此观察者是并非直接注册的LifecycleObserver,而是经过包装的ObserverWithState)
再调用观察者们的onStateChanged方法,那直接看分发事件的逻辑就好了
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
到这里,就完成了lifecycle的注册观察者、状态更改、通知观察者的流程
接下来只需要把activity的生命周期通知给lifecycle,那么就相当于完成activity的生命周期管理。
可是ComponentActivity 类中并没有在生命周期方法中调用LifecycleRegistry中更改的方法...
如果全交给LifecycleRegistry处理的话,肯定要再activity的初始化时做工作(才能及时管理到各个生命周期)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
// Restore the Saved State first so that it is available to
// OnContextAvailableListener instances
mSavedStateRegistryController.performRestore(savedInstanceState);
mContextAwareHelper.dispatchOnContextAvailable(this);
super.onCreate(savedInstanceState);
mActivityResultRegistry.onRestoreInstanceState(savedInstanceState);
//只有这里看起来合适和可疑(其实就是它了……)
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
进去看看
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
// On API 29+, we can register for the correct Lifecycle callbacks directly
LifecycleCallbacks.registerIn(activity);
}
// Prior to API 29 and to maintain compatibility with older versions of
// ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and
// need to support activities that don't extend from FragmentActivity from support lib),
// use a framework fragment to get the correct timing of Lifecycle events
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();
}
}
看到是添加了个空fragment...
然后是再fragment中的生命周期方法中更新Lifecycle的状态...
@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;
}
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
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);
}
}
}
这个内容不是很多,也谈不上难,只是做个给自己解惑的记录好了