开发中,在Activity或者fragment的各个生命周期阶段,可能未对资源进行正确操作导致一些问题,从而导致内存泄露甚至引发Crash。
在mvp时代,我们会在P层定义一些接口,在组件回调生命周期函数时调用接口方法,在这些方法中进行资源释放或者取消一些操作的处理。lifecycle就是为了解决这个问题出现的,可以让一些组件拥有生命周期感知的能力。lifecycle已经成为android的基础组件。
在Activity的父类ComponentActivity中,做了这些操作。
在该父类Activity的onCreate中,谷歌使用了一个空布局的Fragment依附于Activity,而后这个fragment组件是可以感知到activity的一些生命周期的,为什么要用fragment呢?是因为lifecycle是从api29开始增加的,28以及之前都是使用的support库,也没有ComponentActivity。因此为了兼容低版本,谷歌想到了这么一个合适的方法。从源码中可以看出相关的版本判断。大于28的版本,直接使用LifecycleCallbacks注册接口。
@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();
}
}
在ComponentActivity中会创建一个mLifecycleRegistry对象,会在getLifecycle()方法中返回该对象。在依附的空布局fragment的生命周期函数中,会调用dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event),event即为生命周期的状态。
@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);
}
该函数会判断Activity的类型,如果为lifecycleowner,则会调用到一个getLifecycle(),其实就是上面说的mLifecycleRegistry,LifecycleRegistry.handleLifecycleEvent(event),由于ComponentActivity实现了lifecycleOwner接口,则肯定满足该条件,另外一个判断是为了兼容其他情况。
@SuppressWarnings("deprecation")
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
if (activity instanceof LifecycleOwner) {
//getLifecycle()返回的就是在ComponentActivity中的
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
/**
* Sets the current state and notifies the observers.
* <p>
* Note that if the {@code currentState} is the same state as the last call to this method,
* calling this method has no effect.
*
* @param event The event that was received
*/
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
moveToState(event.getTargetState());
}
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 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;
}
/**
* Returns the new {@link Lifecycle.State} of a {@link Lifecycle} that just reported
* this {@link Lifecycle.Event}.
*
* Throws {@link IllegalArgumentException} if called on {@link #ON_ANY}, as it is a special
* value used by {@link OnLifecycleEvent} and not a real lifecycle event.
*
* @return the state that will result from this event
*/
@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");
}
该函数里面有一个比较有趣的状态机制。event.getTargetState(),我们平时开发能接触到的基本都是onCreate onStart这种回调函数,在谷歌的设计里,这些回调函数是属于事件,相对应的 组件还会有一些状态。这些状态我们实际开发中不太能接触到。说回这个状态机制,核心是事件驱动状态。当调用了onCreate之后,组件状态就由INITALIZED走向Created,当调用了onStart之后,组件就从created走向started,当调用onResume,就从started变为resumed。这是事件的正向流动,如果用户返回关闭页面或者将app放到后台,事件就会回流,先调用onPause,resumed状态会变为started,调用onStop,就从started更改为created,然后调用onDestory,就从created更改为Destoryed。下图概括了一下事件的流向以及状态的变化。

状态变更之后,需要根据组件的状态同步LifecycleRegistry中保存的mState状态,通过调用moveToState函数来进行同步,函数中有一个sysnc(),其中开启了一个死循环,条件为 当前状态与保存起来的状态是否一致,如果不一致,则同步。
这里注意,不论事件是前进或者回流,都是根据State的枚举类型进行compareTo,如果被观察者比观察者新,同步时状态正向更新,前进,就会调用Event.upFrom(observer.mState)更新状态,若为回流,会调用Event.downFrom(observer.mState)更新状态,随即调用observer的dispatchEvent(lifecycleOwner, event),这里的observer实际上就是lifecycle.addObserver( LifecycleObserver observer)传进来的这个observer,只不过这个需要我们自己手动去传入,而后调用mLifecycleRegistry的addObserver,源码中会将这些保存在一个observerMap中,源码如下:
// happens only on the top of stack (never in reentrance),
// so it doesn't have to take in account parents
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;
}
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Map.Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
Event event = Event.downFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event down from " + observer.mState);
}
pushParentState(event.getTargetState());
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
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();
}
}
}


那最后还有一个问题,Activity触发生命周期之后,是如何调用相应的observer中的同名方法的呢,其实在backwardPass()或者forwardPass()中,最后有一个遍历map集合,取出其中的statefulObserver,调用dispatchEvent,这个statefulObserver实际上里面包装了咱们传进去的那个Observer,也就是lifecycle.addObserver( LifecycleObserver observer)这里的observer,只不过api30之前可能是使用了反射的方式调用method,api30这里是用map里的对象调用的。
该状态在后面为liveData+ViewModel功能提供了扩展,所以这两个库可以感知到生命周期,在合适的时候发送数据,这是后话。
网友评论