Lifecycle源码分析

一、Lifecycle简介
Lifecycle是 Android Architecture Components架构设计方案中的生命周期管理框架。也是LiveData、ViewModel搭建MVVM架构的基础,目前在SupportActivity(AppCompatActivity的父类)和Fragment中都已植入这个框架。
Lifecycle优点:
1)无侵入式监听生命周期。
2)对需要与Activity或者Fragment生命周期相关的业务处理抽离出Activity和Fragment。
二、Lifecycle用法
1)实现LifecycleObserver接口创建观察者类,通过注解给方法绑定生命周期。

class MediaPlayerObserver(var mediaPlayer: MediaPlayer?) : LifecycleObserver {@OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun initMediaPlayer() { try { mediaPlayer = MediaPlayer() mediaPlayer?.setDataSource("") mediaPlayer?.prepareAsync() } catch (e: Exception) { } }@OnLifecycleEvent(Lifecycle.Event.ON_START) fun startMediaPlayer() { mediaPlayer?.start() }@OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun stopMediaPlayer() { mediaPlayer?.stop() }@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun releaseMediaPlayer() { mediaPlayer?.release() mediaPlayer = null } }

2)通过Activity或者Fragment获取Lifecycle添加观察者订阅。
this.lifecycle.addObserver(MediaPlayerObserver(mediaPlayer))

用法上比较简单,只需要完成实现观察者接口和订阅事件就可以。
三、源码分析
1)LifecycleObserver接口
public interface LifecycleObserver {}

接口中没有定义任何方法,接下来分析获取Lifecycle。
2)获取Lifecycle
由Activity一层一层向下查找,发现Lifecycle的实现最终在SupportActivity中。
@RestrictTo(LIBRARY_GROUP) public class SupportActivity extends Activity implements LifecycleOwner { /** * Storage for {@link ExtraData} instances. * * Note that these objects are not retained across configuration changes
*/ private SimpleArrayMap, ExtraData> mExtraDataMap = new SimpleArrayMap<>(); private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); /** * Store an instance of {@link ExtraData} for later retrieval by class name * via {@link #getExtraData}. * * Note that these objects are not retained across configuration changes
* * @see #getExtraData * @hide */ @RestrictTo(LIBRARY_GROUP) public void putExtraData(ExtraData extraData) { mExtraDataMap.put(extraData.getClass(), extraData); }@Override @SuppressWarnings("RestrictedApi") protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this); }@CallSuper @Override protected void onSaveInstanceState(Bundle outState) { mLifecycleRegistry.markState(Lifecycle.State.CREATED); super.onSaveInstanceState(outState); }/** * Retrieves a previously set {@link ExtraData} by class name. * * @see #putExtraData * @hide */ @RestrictTo(LIBRARY_GROUP) public T getExtraData(Class extraDataClass) { return (T) mExtraDataMap.get(extraDataClass); }@Override public Lifecycle getLifecycle() { return mLifecycleRegistry; }/** * @hide */ @RestrictTo(LIBRARY_GROUP) public static class ExtraData { } }

【Lifecycle源码分析】发现获取的Lifecycle其实是Lifecycle的实现类LifecycleRegistry,这里不对这个类进行详细分析,如果想了解可以查看我的上一篇博客LiveData源码分析。
3)添加观察者完成订阅,订阅方法源码如下:
@Override public void addObserver(@NonNull LifecycleObserver observer) { 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); statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState)); popParentState(); // mState / subling may have been changed recalculate targetState = calculateTargetState(observer); }if (!isReentrance) { // we do sync only on the top level. sync(); } mAddingObserverCounter--; }

分析方法发现订阅者Observer会被存储在mObserverMap中,这个变量内部维护一个HashMap来完成对订阅者的存储。
4)分析生命周期状态响应
接下来分析Lifecycle如何响应到Activity的生命周期变化的,订阅成功之后观察者被存储到mObserverMap中,那就从mObserverMap变量入手,通过查找发现在Lifecycle实现类LifecycleRegistry中存在两个方法对mObserverMap中的数据进行了遍历。
private void forwardPass(LifecycleOwner lifecycleOwner) { Iterator> ascendingIterator = mObserverMap.iteratorWithAdditions(); while (ascendingIterator.hasNext() && !mNewEventOccurred) { Entry entry = ascendingIterator.next(); ObserverWithState observer = entry.getValue(); while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred && mObserverMap.contains(entry.getKey()))) { pushParentState(observer.mState); observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState)); popParentState(); } } }private void backwardPass(LifecycleOwner lifecycleOwner) { Iterator> descendingIterator = mObserverMap.descendingIterator(); while (descendingIterator.hasNext() && !mNewEventOccurred) { Entry entry = descendingIterator.next(); ObserverWithState observer = entry.getValue(); while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred && mObserverMap.contains(entry.getKey()))) { Event event = downEvent(observer.mState); pushParentState(getStateAfter(event)); observer.dispatchEvent(lifecycleOwner, event); popParentState(); } } }

这两个方法是分别完成Activity创建的生命周期执行和Activity销毁的生命周期执行。从中可以发现,observer会执行dispatchEvent方法执行生命周期响应,这个方法在内部类ObserverWithState中,代码如下:
static class ObserverWithState { State mState; GenericLifecycleObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { mLifecycleObserver = Lifecycling.getCallback(observer); mState = initialState; }void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; } }

然后通过mLifecycleObserver的onStateChanged方法进行生命周期传递,这个变量是通过Lifecycling.getCallback(observer)方法从observer中获取的。看一下Lifecycling.getCallback方法的源码。
@NonNull static GenericLifecycleObserver getCallback(Object object) { if (object instanceof FullLifecycleObserver) { return new FullLifecycleObserverAdapter((FullLifecycleObserver) object); }if (object instanceof GenericLifecycleObserver) { return (GenericLifecycleObserver) object; }final Class klass = object.getClass(); int type = getObserverConstructorType(klass); if (type == GENERATED_CALLBACK) { List> constructors = sClassToAdapters.get(klass); if (constructors.size() == 1) { GeneratedAdapter generatedAdapter = createGeneratedAdapter( constructors.get(0), object); return new SingleGeneratedAdapterObserver(generatedAdapter); } GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()]; for (int i = 0; i < constructors.size(); i++) { adapters[i] = createGeneratedAdapter(constructors.get(i), object); } return new CompositeGeneratedAdaptersObserver(adapters); } return new ReflectiveGenericLifecycleObserver(object); }

可以知道,我们自定义的LifecycleObserver会执行最后一行代码通过反射的方式完成。通过反射方法获取注解信息,然后满足当前生命周期的方法则执行invoke。执行代码如下:
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) { //noinspection TryWithIdenticalCatches try { switch (mCallType) { case CALL_TYPE_NO_ARG: mMethod.invoke(target); break; case CALL_TYPE_PROVIDER: mMethod.invoke(target, source); break; case CALL_TYPE_PROVIDER_WITH_EVENT: mMethod.invoke(target, source, event); break; } } catch (InvocationTargetException e) { throw new RuntimeException("Failed to call observer method", e.getCause()); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }

    推荐阅读