Lifecycle是什么
Lifecycle是Google官方提供的方便管理生命周期事件的方式,可以更方便的监听生命周期变化事件,它以注解的方式作用在方法上,当生命周期方法调用时,它也会被跟随调用。
Lifecycle是一个抽象类,它持有关于组件(如Activity 或 Fragment)生命周期状态的信息,并且允许其他对象观察此状态。
从Lifecycle类作切入点读代码:
public abstract class Lifecycle {
AtomicReference<Object> mInternalScopeRef = new AtomicReference<>();
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
@MainThread
@NonNull
public abstract State getCurrentState();
@SuppressWarnings("WeakerAccess")
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
@SuppressWarnings("WeakerAccess")
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
}
}
分析:Lifecycle使用两个枚举来跟踪其关联组件的生命周期状态,这两个枚举分别是Event和State。Event中的事件和Activity的生命周期几乎是对应的,除了ON_ANY,它可用于匹配所有事件。还有添加和删除观察者的方法。
State:当前生命周期所处状态
Event:当前生命周期改变对应的事件
Lifecycle如何观察到Activity和Fragment的生命周期
Activity的继承关系:
AppCompatActivity继承了FragmentActivity,FragmentActivity继承了ComponentActivity,ComponentActivity最终去实现了LifecycleOwner接口。
LifecycleOwner接口代码:只有一个getLifecycle()抽象方法。
@SuppressWarnings({"WeakerAccess", "unused"})
public interface LifecycleOwner {
@NonNull
Lifecycle getLifecycle();
}
ComponentActivity类关于实现lifecycle的代码:
public class ComponentActivity extends androidx.core.app.ComponentActivity implements LifecycleOwner {
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
ReportFragment.injectIfNeededIn(this); //注释处
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
正常来说应该在ComponentActivity的各个生命周期方法中改变Lifecycle的State,显然在ComponentActivity中没有做这些,注释处表明是通过injectIfNeededIn()这个方法将这个任务交给了ReportFragment,让fragment监听activity生命周期,这个fragment是一个空白fragment,这里估计是借鉴了前辈Glide观察组件生命周期的方式。
ReportFragment类部分实现:
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
public class ReportFragment extends Fragment {
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);
}
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();
}
}
@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(Lifecycle.Event event) {
Activity activity = getActivity();
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);
}
}
}
}
同时,ComponentActivity中获取LifecycleOwner,返回LifecycleRegistry对象,LifecycleRegistry继承了Lifecycle,让LifecycleRegistry去实现Lifecycle的功能。
LifecycleRegistry类部分代码实现:
public class LifecycleRegistry extends Lifecycle {
private State mState;
private final WeakReference<LifecycleOwner> mLifecycleOwner;
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
...
}
@Override
public void removeObserver(@NonNull LifecycleObserver observer) {
...
}
static State getStateAfter(Event event) {
switch (event) {
case ON_CREATE:
case ON_STOP:
return CREATED;
case ON_START:
case ON_PAUSE:
return STARTED;
case ON_RESUME:
return RESUMED;
case ON_DESTROY:
return DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException("Unexpected event value " + event);
}
private static Event downEvent(State state) {
switch (state) {
case INITIALIZED:
throw new IllegalArgumentException();
case CREATED:
return ON_DESTROY;
case STARTED:
return ON_STOP;
case RESUMED:
return ON_PAUSE;
case DESTROYED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException("Unexpected state value " + state);
}
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 = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
}
分析这个核心过程:
当ReportFragment生命周期发生改变时,调用dispatch()方法并将当前生命周期对应的事件Event分发,交给当前所属的实现了lifecycle或LifecycleOwner的activity处理,通过activity.getLifecycle()获取到内部持有的LifecycleRegistry,最终是调用了LifecycleRegistry的handleLifecycleEvent(event)方法处理。
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
getStateAfter方法会获取“即将的事件” :当前事件执行后,修改生命周期状态为下一个状态,事件变化有正向和反向两种方式。代码如下:
static State getStateAfter(Event event) {
switch (event) {
case ON_CREATE:
case ON_STOP:
return CREATED;
case ON_START:
case ON_PAUSE:
return STARTED;
case ON_RESUME:
return RESUMED;
case ON_DESTROY:
return DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException("Unexpected event value " + event);
}
为什么要做这么复杂的时间变化呢。因为lifecycle需要支持Livedata,Viewmodel,activity,fragment,以及任意组件使用,需要做得更加灵活。
同样在LifecycleRegistry类中,在handleLifecycleEvent方法调用moveToState:
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;
}
让观察的生命周期状态进行平移与被观察者对齐。
然后执行moveToState中的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;
}
根据状态的差异调用backwardPass或者forwardPass将状态进行前进或者后退,然后调用observer的dispatchEvent进行事件分发。
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();
}
}
}
而通过getLifecycle().addObserver(new MyLifecycleObserver())给组件添加观察着,会将该observer添加进lifecycleRegistry的mObserverMap中。
ObserverWithState类代码:
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.getCallback(observer);//1
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
/**
* An internal implementation of {@link LifecycleObserver} that relies on reflection.
*/
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
mInfo.invokeCallbacks(source, event, mWrapped); //注释处
}
}
当调用dispatchEvent后,遍历map中的观察者,获取观察者对象。实现LifecycleObserver接口的类中,注解修饰的方法和事件会被保存起来,通过反射对事件的对应方法进行调用。