LifeCycle
一、LifeCyle介绍
LifeCycle翻译过来就是生命周期,android中所有有生命周期的组件如Activity、Fragment、Application等等都可以通过LifeCycle监听分发生命周期的变化。Android官方为什么会提供这个架构组件呢?原因是大部分开发者都喜欢在生命周期的开始和结束做一些初始化和回收的代码。比如在Activity的的Oncreate中创建handler、presenter的attachView等需要在Activity销毁时进行回收,handler要移除所有消息,presenter要dettachView防止activity被持有无法被销毁。这样的模板代码会随着逻辑的复杂程度会越来越多,不利于维护看着也不够清爽,违背了View只负责界面显示的初衷。
二、LifeCycle的使用场景
新的SDK中AppCompatActivity已经实现了LifeCycle,因此我们只需要调用getLifecycle()
方法然后使用addObserver()
注册我们自己的Observer即可监听生命周期的变化。拿MVP中的Presenter举例,如介绍中提到的我们在OnCreate中注册View在OnDestroy中解绑View很不优雅,那么我们用LifeCycle进行优化。
- 优化前的代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//绑定View
presenter.attach(this);
//请求数据
presenter.getDataFromNet();
}
@Override
protected void onDestroy() {
super.onDestroy();
//解绑View防止页面销毁时更新UI
presenter.dettach(this);
}
- 优化后的代码
public class Presenter implements DefaultLifecycleObserver {
private View view;
public Presenter(View view) {
this.view = view;
}
@Override
public void onCreate(@NonNull LifecycleOwner owner) {
DefaultLifecycleObserver.super.onCreate(owner);
//请求数据
getDataFromNet();
}
@Override
public void onDestroy(@NonNull LifecycleOwner owner) {
DefaultLifecycleObserver.super.onDestroy(owner);
//解绑view
view = null;
}
public void getDataFromNet(){
if (view !=null){
NetWorkUtil.requestData();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//初始化Presenter
Presenter presenter = new Presenter(this);
//注册Observer
getLifecycle().addObserver(presenter);
}
从上面的示例代码中可以看到我们把在Activity中初始化的模板代码通过Presenter实现DefaultLifecycleObserver
并在Activity中进行注册监听Activity的生命周期移动到了Presenter中进行调用。
三、Lifecycle实现流程分析
高版本的Activity源码中已经为我们默认实现了Lifecycle组件,我们直接用Activity中的源码作为示例进行分析。
在ComponentActivity 中实现了LifecycleOwner接口,创建了LifecycleRegistry成员变量,并在onCreate方法中创建了ReportFragment,这个Fragment是一个空白的Fragment用于通知生命周期变化。
ComponentActivity.java
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
ContextAware,
LifecycleOwner,
ViewModelStoreOwner,
HasDefaultViewModelProviderFactory,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner,
ActivityResultRegistryOwner,
ActivityResultCaller,
OnConfigurationChangedProvider,
OnTrimMemoryProvider,
OnNewIntentProvider,
OnMultiWindowModeChangedProvider,
OnPictureInPictureModeChangedProvider,
MenuHost {
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
...
//创建空白的Fragment
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
...
}
ReportFragment.java
如果api>=29则调用activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
方法监听声明周期,这个监听应该是注册到系统底层。在收到回调的同时调用dispatch
方法分发生命周期事件。
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();
}
}
@RequiresApi(29)
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
static void registerIn(Activity activity) {
activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
}
@Override
public void onActivityCreated(@NonNull Activity activity,
@Nullable Bundle bundle) {
}
@Override
public void onActivityPostCreated(@NonNull Activity activity,
@Nullable Bundle savedInstanceState) {
dispatch(activity, Lifecycle.Event.ON_CREATE);
}
@Override
public void onActivityStarted(@NonNull Activity activity) {
}
@Override
public void onActivityPostStarted(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_START);
}
@Override
public void onActivityResumed(@NonNull Activity activity) {
}
@Override
public void onActivityPostResumed(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_RESUME);
}
@Override
public void onActivityPrePaused(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_PAUSE);
}
@Override
public void onActivityPaused(@NonNull Activity activity) {
}
@Override
public void onActivityPreStopped(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_STOP);
}
@Override
public void onActivityStopped(@NonNull Activity activity) {
}
@Override
public void onActivitySaveInstanceState(@NonNull Activity activity,
@NonNull Bundle bundle) {
}
@Override
public void onActivityPreDestroyed(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_DESTROY);
}
@Override
public void onActivityDestroyed(@NonNull Activity activity) {
}
}
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);
}
}
}
如果声明api<29则走fragment的生命周期调用dispatch
方法分发事件。
@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;
}
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);
}
}
不管是哪个api最终调用的都是handleLifecycleEvent()
方法。
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);
}
}
}
LifecycleRegistry.java
通过Event的getTargetState()
获取事件对应的状态
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
moveToState(event.getTargetState());
}
public enum Event {
/**
* Constant for onCreate event of the {@link LifecycleOwner}.
*/
ON_CREATE,
/**
* Constant for onStart event of the {@link LifecycleOwner}.
*/
ON_START,
/**
* Constant for onResume event of the {@link LifecycleOwner}.
*/
ON_RESUME,
/**
* Constant for onPause event of the {@link LifecycleOwner}.
*/
ON_PAUSE,
/**
* Constant for onStop event of the {@link LifecycleOwner}.
*/
ON_STOP,
/**
* Constant for onDestroy event of the {@link LifecycleOwner}.
*/
ON_DESTROY,
/**
* An {@link Event Event} constant that can be used to match all events.
*/
ON_ANY;
/**
* Returns the {@link Lifecycle.Event} that will be reported by a {@link Lifecycle}
* leaving the specified {@link Lifecycle.State} to a lower state, or {@code null}
* if there is no valid event that can move down from the given state.
*
* @param state the higher state that the returned event will transition down from
* @return the event moving down the lifecycle phases from state
*/
@Nullable
public static Event downFrom(@NonNull State state) {
switch (state) {
case CREATED:
return ON_DESTROY;
case STARTED:
return ON_STOP;
case RESUMED:
return ON_PAUSE;
default:
return null;
}
}
/**
* Returns the {@link Lifecycle.Event} that will be reported by a {@link Lifecycle}
* entering the specified {@link Lifecycle.State} from a higher state, or {@code null}
* if there is no valid event that can move down to the given state.
*
* @param state the lower state that the returned event will transition down to
* @return the event moving down the lifecycle phases to state
*/
@Nullable
public static Event downTo(@NonNull State state) {
switch (state) {
case DESTROYED:
return ON_DESTROY;
case CREATED:
return ON_STOP;
case STARTED:
return ON_PAUSE;
default:
return null;
}
}
/**
* Returns the {@link Lifecycle.Event} that will be reported by a {@link Lifecycle}
* leaving the specified {@link Lifecycle.State} to a higher state, or {@code null}
* if there is no valid event that can move up from the given state.
*
* @param state the lower state that the returned event will transition up from
* @return the event moving up the lifecycle phases from state
*/
@Nullable
public static Event upFrom(@NonNull State state) {
switch (state) {
case INITIALIZED:
return ON_CREATE;
case CREATED:
return ON_START;
case STARTED:
return ON_RESUME;
default:
return null;
}
}
/**
* Returns the {@link Lifecycle.Event} that will be reported by a {@link Lifecycle}
* entering the specified {@link Lifecycle.State} from a lower state, or {@code null}
* if there is no valid event that can move up to the given state.
*
* @param state the higher state that the returned event will transition up to
* @return the event moving up the lifecycle phases to state
*/
@Nullable
public static Event upTo(@NonNull State state) {
switch (state) {
case CREATED:
return ON_CREATE;
case STARTED:
return ON_START;
case RESUMED:
return ON_RESUME;
default:
return null;
}
}
/**
* 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");
}
}
再看下moveToState()
方法,如果通过event获取的状态和当前存储的状态相同则直接返回不处理,如果当前状态mState
是初始化状态而传入的状态是DESTROYED
状态则抛出异常。把传入的next赋值给mState,然后调用sync()
方法进行状态同步,最后如果mState == DESTROYED
则重新对mObserverMap
进行赋值,等于清空了之前存储的Observer。
private void moveToState(State next) {
if (mState == next) {
return;
}
if (mState == INITIALIZED && next == DESTROYED) {
throw new IllegalStateException("no event down from " + mState);
}
//mState是类的成员变量,保存了当前的生命周期状态
mState = next;
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
//同步状态
sync();
mHandlingEvent = false;
if (mState == DESTROYED) {
mObserverMap = new FastSafeIterableMap<>();
}
}
看下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<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
最外层while循环根据isSynced()
判断mObserverMap中所有的observer是否状态都更新过
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;
}
如果没有全部更新则进入循环,分别通过compareTo方法看判断是调用backwardPass
和forwardPass
。
backwardPass方法中先是循环获取map中的所有ObserverWithState,然后再次进入循环调用downFrom获取对应的事件并分发。
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()))) {
//每次循环都是用Observer的成员变量获取下一步的Event
Event event = Event.downFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event down from " + observer.mState);
}
pushParentState(event.getTargetState());
//observer分发事件
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
forwardPass
和上面的backwardPass
逻辑类似
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();
}
}
}
dispatchEvent
方法中会将mState更新
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;
}
}
再来看下添加观察者的代码
while循环中同样是比对状态然后调用tatefulObserver.dispatchEvent(lifecycleOwner, event)
同步状态
@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);
if (previous != null) {
return;
}
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
// it is null we should be destroyed. Fallback quickly
return;
}
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
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);
}
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
mAddingObserverCounter--;
}