Lifecycle-aware Components 源码分析
OrvA16
7年前
<p>注:本文所有代码基于 android.arch.lifecycle 1.0.0-alpha1</p> <p>另外,为了避免混淆,Fragment、Activity 等组件自身的生命周期直用 “生命周期” 一词,而由 <strong>Lifecycle</strong> 提供的生命周期则称为 “Lifecyle”</p> <p>最近看到不少人讨论 Google 推的 <a href="/misc/goto?guid=4959749169673805620" rel="nofollow,noindex">Android Architecture Components</a> ,其中 <a href="/misc/goto?guid=4959749486617582349" rel="nofollow,noindex">Handling Lifecycles</a> 一章展现了如何利用 android.arch.lifecycle 包提供的类来控制数据、监听器等的 Lifecycle。同时, <a href="/misc/goto?guid=4959749258932581264" rel="nofollow,noindex">LiveData</a> 与 <a href="/misc/goto?guid=4959749486736650405" rel="nofollow,noindex">ViewModel</a> 的 Lifecycle 也依赖于 <strong>Lifecycle</strong> 框架,所以分析 <strong>Lifecyle</strong> 显然是有必要的。</p> <p>Lifecycle到底是通过怎样的方式来绑定 Android 组件的生命周期以及如何通知 <strong>LifecycleObserver</strong> 状态变化的呢?本文将会围绕这两个问题深入分析 <strong>Lifecycle</strong> 源码。</p> <h2>前置工作</h2> <p>由于完整的 <strong>Lifecycle</strong> 分为 common , core , extensions , runtime 四个包,并包含 <strong>ViewModel</strong> 、 <strong>LiveData</strong> 部分内容。为了方便分析,利用 proguard(只添加 -dontobfuscate ) 剔除所有不需要用到的类。</p> <p>最终剩下的类:</p> <p>android.arch.core.internal( <strong>core</strong> )</p> <ul> <li>SafeIterableMap</li> </ul> <p>android.arch.lifecycle( <strong>runtime</strong> )</p> <ul> <li>EmptyActivityLifecycleCallbacks</li> <li>LifecycleActivity</li> <li>LifecycleDispatcher</li> <li>LifecycleFragment</li> <li>LifecycleRegistry</li> <li>LifecycleRegistryOwner</li> <li>LifecycleRuntimeTrojanProvider</li> <li>LifecycleService</li> <li>ProcessLifecycleOwner</li> <li>ReportFragment</li> <li>ServiceLifecycleDispatcher</li> </ul> <p>android.arch.lifecycle( <strong>common</strong> )</p> <ul> <li>GenericLifecycleObserver</li> <li>Lifecycle</li> <li>LifecycleObserver</li> <li>LifecycleOwner</li> <li>Lifecycling</li> <li>OnLifecycleEvent</li> <li>ReflectiveGenericLifecycleObserver</li> </ul> <h2>Runtime</h2> <p>先看 <strong>Lifecycle</strong> 的 AndroidManifest.xml(可以在 build/outputs/logs/manifest-merger-*.txt 中找到对应的路径):</p> <pre> <code class="language-java"><manifestxmlns:android="http://schemas.android.com/apk/res/android" package="android.arch.lifecycle" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="26" /> <application> <provider android:name="android.arch.lifecycle.LifecycleRuntimeTrojanProvider" android:authorities="${applicationId}.lifecycle-trojan" android:exported="false" android:multiprocess="true" /> </application> </manifest> </code></pre> <p>可以看到 <strong>Lifecycle</strong> 会给应用添加一个 exported="false" 的 <strong>LifecycleRuntimeTrojanProvider</strong> 。</p> <h3>LifecycleRuntimeTrojanProvider</h3> <pre> <code class="language-java">/** * Internal class to initialize Lifecycles. * @hide */ public class LifecycleRuntimeTrojanProviderextends ContentProvider{ @Override public boolean onCreate(){ LifecycleDispatcher.init(getContext()); ProcessLifecycleOwner.init(getContext()); return true; } ... } </code></pre> <p>javadoc 已经写得很明显, <strong>LifecycleRuntimeTrojanProvider</strong> 就是用于初始化 <strong>Lifecycle</strong> 的,其余 ContentProvider 应实现的方法返回的均为默认值(null 或 0),顺着代码先看 <strong>LifecycleDispatcher</strong> 。</p> <h3>LifecycleDispatcher</h3> <p>LifecycleDispatcher的初始化代码比较简单:</p> <pre> <code class="language-java">private static AtomicBoolean sInitialized = new AtomicBoolean(false); static void init(Context context){ if (sInitialized.getAndSet(true)) { return; } ((Application) context.getApplicationContext()) .registerActivityLifecycleCallbacks(new DispatcherActivityCallback()); } </code></pre> <p>主要就是注册了一个 ActivityLifecycleCallbacks —— <strong>DispatcherActivityCallback</strong> 。</p> <p>DispatcherActivityCallback</p> <pre> <code class="language-java">static class DispatcherActivityCallbackextends EmptyActivityLifecycleCallbacks{ private final FragmentCallback mFragmentCallback; DispatcherActivityCallback() { mFragmentCallback = new FragmentCallback(); } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState){ if (activity instanceof FragmentActivity) { ((FragmentActivity) activity).getSupportFragmentManager() .registerFragmentLifecycleCallbacks(mFragmentCallback, true); } // ProcessLifecycleOwner should always correctly work and some activities may not extend // FragmentActivity from support lib, so we use framework fragments for activities 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 onActivityStopped(Activity activity){ if (activity instanceof FragmentActivity) { markState((FragmentActivity) activity, CREATED); } } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState){ if (activity instanceof FragmentActivity) { markState((FragmentActivity) activity, CREATED); } } } </code></pre> <p>DispatcherActivityCallback的 onActivityStopped 和 onActivitySaveInstanceState 方法会将 LifecycleRegistryOwner 的状态重置成 CREATED (为何是 CREATED 可以查看 <a href="/misc/goto?guid=4959749486822533409" rel="nofollow,noindex">Lifecycle 的状态图</a> 及 <a href="/misc/goto?guid=4959749486909232187" rel="nofollow,noindex">各状态的描述</a> )。再看 onActivityCreated ,当 activity 是 FragmentActivity 时,额外注册 FragmentLifecycleCallbacks —— <strong>FragmentCallback</strong> 。接着添加 <strong>ReportFragment</strong> 到 activity 中,考虑到并不是所有人都会使用 FragmentActivity,所以添加 <strong>ReportFragment</strong> 时使用的是原生的 FragmentManager。</p> <p>ReportFragment</p> <p>接着来看一下 <strong>ReportFragment</strong> 的源码:</p> <pre> <code class="language-java">public class ReportFragmentextends Fragment{ private ActivityInitializationListener mProcessListener; private void dispatchCreate(ActivityInitializationListener listener){ if (listener != null) { listener.onCreate(); } } private void dispatchStart(ActivityInitializationListener listener){ if (listener != null) { listener.onStart(); } } private void dispatchResume(ActivityInitializationListener listener){ if (listener != null) { listener.onResume(); } } @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){ if (getActivity() instanceof LifecycleRegistryOwner) { ((LifecycleRegistryOwner) getActivity()).getLifecycle().handleLifecycleEvent(event); } } void setProcessListener(ActivityInitializationListener processListener){ mProcessListener = processListener; } interface ActivityInitializationListener{ void onCreate(); void onStart(); void onResume(); } } </code></pre> <p>不难看出 <strong>ReportFragment</strong> 主要是在所有生命周期发生变化时生成对应的 Lifecycle 事件发送到 LifecycleRegistryOwner(Activity)中。并在 onActivityCreated , onStart , onResume 时额外通知 <strong>ActivityInitializationListener</strong> (暂且记住,后面会用到)。可能会有读者有疑问,为什么要使用 <strong>ReportFragment</strong> 的生命周期而不直接使用 ActivityLifecycleCallbacks 的回调来处理 Lifecycle 的变化?由于 ActivityLifecycleCallbacks 的回调比 Fragment 和 Activity 还要早,实际上未真正执行对应的生命周期方法。至于为什么用 Fragment 而不直接重载 Activity 的生命周期,显然用 Fragment 侵入性低。</p> <p>FragmentCallback</p> <p>再看回 <strong>FragmentCallback</strong> :</p> <pre> <code class="language-java">static class FragmentCallbackextends FragmentManager.FragmentLifecycleCallbacks{ @Override public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState){ dispatchIfLifecycleOwner(f, ON_CREATE); if (!(f instanceof LifecycleRegistryOwner)) { return; } if (f.getChildFragmentManager().findFragmentByTag(REPORT_FRAGMENT_TAG) == null) { f.getChildFragmentManager().beginTransaction().add(new DestructionReportFragment(), REPORT_FRAGMENT_TAG).commit(); } } @Override public void onFragmentStarted(FragmentManager fm, Fragment f){ dispatchIfLifecycleOwner(f, ON_START); } @Override public void onFragmentResumed(FragmentManager fm, Fragment f){ dispatchIfLifecycleOwner(f, ON_RESUME); } } </code></pre> <p>与 <strong>DispatcherActivityCallback</strong> 类似,当 Fragment 为 Parent Fragment 且实现了 LifecycleRegistryOwner 接口时,FragmentCallback 会添加一个 Child Fragment —— <strong>DestructionReportFragment</strong> 。</p> <pre> <code class="language-java">public static class DestructionReportFragmentextends Fragment{ @Override public void onPause(){ super.onPause(); dispatch(ON_PAUSE); } @Override public void onStop(){ super.onStop(); dispatch(ON_STOP); } @Override public void onDestroy(){ super.onDestroy(); dispatch(ON_DESTROY); } protected void dispatch(Lifecycle.Event event){ dispatchIfLifecycleOwner(getParentFragment(), event); } } private static void dispatchIfLifecycleOwner(Fragment fragment, Lifecycle.Event event){ if (fragment instanceof LifecycleRegistryOwner) { ((LifecycleRegistryOwner) fragment).getLifecycle().handleLifecycleEvent(event); } } </code></pre> <p>与 <strong>DispatcherActivityCallback</strong> 不一样的是, <strong>FragmentCallback</strong> 混合了 FragmentLifecycleCallbacks 及 Fragment 的生命周期来通知 Child Fragment Lifecycle 发生变化。这样做是为了确保 ON_CREATE , ON_START , ON_RESUME 在对应的生命周期之后分发, ON_PAUSE , ON_STOP , ON_DESTROY 在对应的生命周期之前分发。</p> <p>所以 <strong>FragmentCallback</strong> 主要是通知 Parent Fragment(LifecycleRegistryOwner)Lifecycle 发生变化,从而给 Child Fragment(LifecycleObserver)分发 Lifecycle 事件。</p> <p>值得注意的是,由于 FragmentLifecycleCallbacks 只存在于 v4 包中,如果 Child 是 android.app.Fragment,即使 Child 通过 ((LifecycleRegistryOwner) getParentFragment()).getLifecycle().addObserver(this) 注册了监听也不会接收到相关的 Lifecycle 事件,因为 LifecycleRegistryOwner 的 handleLifecycleEvent 从未被调用过。(暂时未知 Google 是有意为之,抑或是个 BUG。)</p> <h3>ProcessLifecycleOwner</h3> <p>看完 <strong>LifecycleDispatcher</strong> ,接着来了解一下 <strong>ProcessLifecycleOwner</strong> :</p> <pre> <code class="language-java">public class ProcessLifecycleOwnerimplements LifecycleOwner{ @VisibleForTesting static final long TIMEOUT_MS = 700; //mls // ground truth counters private int mStartedCounter = 0; private int mResumedCounter = 0; private boolean mPauseSent = true; private boolean mStopSent = true; private Handler mHandler; private final LifecycleRegistry mRegistry = new LifecycleRegistry(this); private Runnable mDelayedPauseRunnable = new Runnable() { @Override public void run(){ dispatchPauseIfNeeded(); dispatchStopIfNeeded(); } }; private ActivityInitializationListener mInitializationListener = new ActivityInitializationListener() { @Override public void onCreate(){ } @Override public void onStart(){ activityStarted(); } @Override public void onResume(){ activityResumed(); } }; private static final ProcessLifecycleOwner sInstance = new ProcessLifecycleOwner(); public staticLifecycleOwnerget(){ return sInstance; } static void init(Context context){ sInstance.attach(context); } void activityStarted(){ mStartedCounter++; if (mStartedCounter == 1 && mStopSent) { mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START); mStopSent = false; } } void activityResumed(){ mResumedCounter++; if (mResumedCounter == 1) { if (mPauseSent) { mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); mPauseSent = false; } else { mHandler.removeCallbacks(mDelayedPauseRunnable); } } } void activityPaused(){ mResumedCounter--; if (mResumedCounter == 0) { mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS); } } void activityStopped(){ mStartedCounter--; dispatchStopIfNeeded(); } private void dispatchPauseIfNeeded(){ if (mResumedCounter == 0) { mPauseSent = true; mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE); } } private void dispatchStopIfNeeded(){ if (mStartedCounter == 0 && mPauseSent) { mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP); mStopSent = true; } } private ProcessLifecycleOwner(){ } void attach(Context context){ mHandler = new Handler(); mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE); Application app = (Application) context.getApplicationContext(); app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() { @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState){ LifecycleDispatcher.get(activity).setProcessListener(mInitializationListener); } @Override public void onActivityPaused(Activity activity){ activityPaused(); } @Override public void onActivityStopped(Activity activity){ activityStopped(); } }); } @Override publicLifecyclegetLifecycle(){ return mRegistry; } } </code></pre> <p>比起 <strong>LifecycleDispatcher</strong> , <strong>ProcessLifecycleOwner</strong> 的代码要简单得多。 <strong>ProcessLifecycleOwner</strong> 的作用就是监听当前进程中 Activity 的状态变化以统计 Activity 的数量从而通知 LifecycleObserver Lifecycle 发生变化。</p> <p>而为了达到这一目的, <strong>ProcessLifecycleOwner</strong> 的做法是为 <strong>LifecycleDispatcher</strong> 注册 <strong>ActivityInitializationListener</strong> 从而确保 Activity 进入了 onStart 或 onResume 生命周期(还记得前面 <strong>ReportFragment</strong> 提到的这部分内容?),并配合 ActivityLifecycleCallbacks 的 onActivityPaused , onActivityStopped 确保 Lifecycle 事件发生在 Activity 的 onPause , onStop 之前。</p> <p>另外,由于 <strong>ProcessLifecycleOwner</strong> 没有 ON_DESTROY ,接收到 ON_STOP 时已经表示当前进程无存活的 Activity。同时需注意一点: <strong>ProcessLifecycleOwner</strong> 的统计不包含 Service,换句话说,即使接收到 ON_STOP 事件,并不意味着当前进程结束。</p> <h3>LifecycleService</h3> <p>了解完 Lifecycle 框架中 Activity、Fragment 相关的生命周期事件是如何生成的,接下来就看看 Service 相关的生命周期事件是如何生成的。</p> <pre> <code class="language-java">public class LifecycleServiceextends Serviceimplements LifecycleOwner{ private final ServiceLifecycleDispatcher mDispatcher = new ServiceLifecycleDispatcher(this); @CallSuper @Override public void onCreate(){ mDispatcher.onServicePreSuperOnCreate(); super.onCreate(); } @CallSuper @Nullable @Override publicIBinderonBind(Intent intent){ mDispatcher.onServicePreSuperOnBind(); return null; } @SuppressWarnings("deprecation") @CallSuper @Override public void onStart(Intent intent,intstartId){ mDispatcher.onServicePreSuperOnStart(); super.onStart(intent, startId); } @CallSuper @Override public int onStartCommand(Intent intent,intflags,intstartId){ return super.onStartCommand(intent, flags, startId); } @CallSuper @Override public void onDestroy(){ mDispatcher.onServicePreSuperOnDestroy(); super.onDestroy(); } @Override publicLifecyclegetLifecycle(){ return mDispatcher.getLifecycle(); } } </code></pre> <pre> <code class="language-java">public class ServiceLifecycleDispatcher{ private final LifecycleRegistry mRegistry; private final Handler mHandler; private DispatchRunnable mLastDispatchRunnable; public ServiceLifecycleDispatcher(@NonNull LifecycleOwner provider){ mRegistry = new LifecycleRegistry(provider); mHandler = new Handler(); } private void postDispatchRunnable(Lifecycle.Event event){ if (mLastDispatchRunnable != null) { mLastDispatchRunnable.run(); } mLastDispatchRunnable = new DispatchRunnable(mRegistry, event); mHandler.postAtFrontOfQueue(mLastDispatchRunnable); } public void onServicePreSuperOnCreate(){ postDispatchRunnable(Lifecycle.Event.ON_CREATE); } public void onServicePreSuperOnBind(){ postDispatchRunnable(Lifecycle.Event.ON_START); } public void onServicePreSuperOnStart(){ postDispatchRunnable(Lifecycle.Event.ON_START); } public void onServicePreSuperOnDestroy(){ postDispatchRunnable(Lifecycle.Event.ON_STOP); postDispatchRunnable(Lifecycle.Event.ON_DESTROY); } publicLifecyclegetLifecycle(){ return mRegistry; } static class DispatchRunnableimplements Runnable{ private final LifecycleRegistry mRegistry; final Lifecycle.Event mEvent; private boolean mWasExecuted = false; DispatchRunnable(@NonNull LifecycleRegistry registry, Lifecycle.Event event) { mRegistry = registry; mEvent = event; } @Override public void run(){ if (!mWasExecuted) { mRegistry.handleLifecycleEvent(mEvent); mWasExecuted = true; } } } } </code></pre> <p>ServiceLifecycleDispatcher用于协助 <strong>LifecycleService</strong> 分发 Lifecycle 事件并确保每次发生变化时回调执行于 Worker Thread。同时我们可以看到 <strong>LifecycleService</strong> 只会产生 ON_CREATE , ON_START , ON_STOP , ON_DESTROY 四种事件。</p> <p>需注意的是继承 <strong>LifecycleService</strong> 时如需重写 onStart 或 onStartCommand 方法,必须调用 super.onStart 或 super.onStartCommand 以确保 ON_START 事件能够被触发。</p> <h3>小结</h3> <p>至此,我们了解到 <strong>Lifecycle</strong> 框架是如何将 Lifecycle 事件与 Android 组件的生命周期绑定的:</p> <ul> <li><strong>LifecycleDispatcher</strong> ,通过 ActivityLifecycleCallbacks、FragmentLifecycleCallbacks 及 Fragment 获知 Activity、Fragment 的生命周期变化并产生相应的 Lifecycle 事件;</li> <li><strong>ProcessLifecycleOwner</strong> ,通过 ActivityLifecycleCallbacks 与 <strong>LifecycleDispatcher</strong> 配合监听当前进程中 Activities 的生命周期变化并在必要时产生相应的 Lifecycle 事件;</li> <li><strong>LifecycleService</strong> ,通过重载 Service 的生命周期方法并在相应方法内产生相应的 Lifecycle 事件。</li> </ul> <h2>Common</h2> <h3>LifecycleRegistry 的 addObserver 流程</h3> <p>我们使用的 LifecycleActivity 以及 LifecycleFragment 内部都是通过 <strong>LifecycleRegistry</strong> 来管理及分发 Lifecycle 事件。</p> <p>先了解下 <strong>LifecycleRegistry</strong> 中 addObserver 的内部逻辑:</p> <pre> <code class="language-java">private SafeIterableMap<LifecycleObserver, ObserverWithState> mObserverSet = new SafeIterableMap<>(); @Override public void addObserver(LifecycleObserver observer){ ObserverWithState observerWithState = new ObserverWithState(observer); mObserverSet.putIfAbsent(observer, observerWithState); observerWithState.sync(); } </code></pre> <pre> <code class="language-java">class ObserverWithState{ private State mObserverCurrentState = INITIALIZED; private GenericLifecycleObserver mCallback; ObserverWithState(LifecycleObserver observer) { mCallback = Lifecycling.getCallback(observer); } ... } </code></pre> <p>在调用 <strong>LifecycleRegistry</strong> 的 addObserver 方法时,LifecycleObserver 被传至 <strong>ObserverWithState</strong> 并通过 Lifecycling.getCallback(observer) 生成 <strong>GenericLifecycleObserver</strong> 。</p> <p>Lifecycling</p> <pre> <code class="language-java">@NonNull staticGenericLifecycleObservergetCallback(Object object){ if (object instanceof GenericLifecycleObserver) { return (GenericLifecycleObserver) object; } ... // try final Class<?> klass = object.getClass(); Constructor<? extends GenericLifecycleObserver> cachedConstructor; ... // 缓存部分 cachedConstructor = getGeneratedAdapterConstructor(klass); if (cachedConstructor != null) { sCallbackCache.put(klass, cachedConstructor); if (!cachedConstructor.isAccessible()) { cachedConstructor.setAccessible(true); } return cachedConstructor.newInstance(object); } else { sCallbackCache.put(klass, sREFLECTIVE); } return new ReflectiveGenericLifecycleObserver(object); ... // catch } </code></pre> <p>当调用 getCallback 时, <strong>Lifecycling</strong> 会根据传入的 Object(LifecycleObserver)调用 getGeneratedAdapterConstructor 。</p> <p>LifecycleAdapter 的实例化</p> <pre> <code class="language-java">@Nullable private static Constructor<? extends GenericLifecycleObserver> getGeneratedAdapterConstructor( Class<?> klass) { final String fullPackage = klass.getPackage().getName(); String name = klass.getCanonicalName(); // anonymous class bug:35073837 if (name == null) { return null; } final String adapterName = getAdapterName(fullPackage.isEmpty() ? name : name.substring(fullPackage.length() + 1)); try { @SuppressWarnings("unchecked") final Class<? extends GenericLifecycleObserver> aClass = (Class<? extends GenericLifecycleObserver>) Class.forName( fullPackage.isEmpty() ? adapterName : fullPackage + "." + adapterName); return aClass.getDeclaredConstructor(klass); } catch (ClassNotFoundException e) { final Class<?> superclass = klass.getSuperclass(); if (superclass != null) { return getGeneratedAdapterConstructor(superclass); } } catch (NoSuchMethodException e) { // this should not happen throw new RuntimeException(e); } return null; } staticStringgetAdapterName(String className){ return className.replace(".", "_") + "_LifecycleAdapter"; } </code></pre> <p>不难看出, getGeneratedAdapterConstructor 主要是获取 annotationProcessor 生成的 <strong>xxx_LifecycleAdapter</strong> (关于 <strong>LifecycleAdapter</strong> 后面补充说明)的构造函数,并实例化返回到 getCallback 中。需注意的是,如果找不到 <strong>LifecycleAdapter</strong> 且 object(LifecycleObserver) 存在父类时会试图获取父类的 <strong>LifecycleAdapter</strong> (估计是为了应对混淆时只混淆了子类的情况)。</p> <p>ReflectiveGenericLifecycleObserver 的实例化</p> <p>当获取 <strong>LifecycleAdapter</strong> 失败后, <strong>Lifecycling</strong> 会直接实例化 <strong>ReflectiveGenericLifecycleObserver</strong> 作为替代(估计也是为了应对混淆)。</p> <pre> <code class="language-java">class ReflectiveGenericLifecycleObserverimplements GenericLifecycleObserver{ private final Object mWrapped; private final CallbackInfo mInfo; @SuppressWarnings("WeakerAccess") static final Map<Class, CallbackInfo> sInfoCache = new HashMap<>(); ReflectiveGenericLifecycleObserver(Object wrapped) { mWrapped = wrapped; mInfo = getInfo(mWrapped.getClass()); } ... private staticCallbackInfogetInfo(Class klass){ CallbackInfo existing = sInfoCache.get(klass); if (existing != null) { return existing; } existing = createInfo(klass); return existing; } ... } </code></pre> <p>ReflectiveGenericLifecycleObserver在实例化时会获取 Object(LifecycleObserver)的 class 并作为参数调用 createInfo 方法。</p> <pre> <code class="language-java">private staticCallbackInfocreateInfo(Class klass){ Method[] methods = klass.getDeclaredMethods(); List<MethodReference> methodReferences = null; Set<Event> allEvents = new HashSet<>(); for (Method method : methods) { OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class); if (annotation == null) { continue; } Class<?>[] params = method.getParameterTypes(); int callType = CALL_TYPE_NO_ARG; if (params.length > 0) { callType = CALL_TYPE_PROVIDER; // 有参第一个参数必须为 LifecycleOwner if (!params[0].isAssignableFrom(LifecycleOwner.class)) { throw new IllegalArgumentException( "invalid parameter type. Must be one and instanceof LifecycleOwner"); } } if (params.length > 1) { callType = CALL_TYPE_PROVIDER_WITH_EVENT; // 有两个参数时第二个参数必须为 Event if (!params[1].isAssignableFrom(Event.class)) { throw new IllegalArgumentException( "invalid parameter type. second arg must be an event"); } } if (params.length > 2) { // 最多只能有两个参数 throw new IllegalArgumentException("cannot have more than 2 params"); } if (methodReferences == null) { methodReferences = new ArrayList<>(); } // 获取应该执行回调的事件集 Set<Event> events = expandOnAnyEvents(annotation.value()); methodReferences.add(new MethodReference(events, callType, method)); allEvents.addAll(events); } CallbackInfo info = new CallbackInfo(allEvents, methodReferences); sInfoCache.put(klass, info); Class superclass = klass.getSuperclass(); if (superclass != null) { // 获取父类中带 OnLifecycleEvent 注解的方法集及事件集等 info.mSuper = getInfo(superclass); } Class[] interfaces = klass.getInterfaces(); // 获取接口中带 OnLifecycleEvent 注解的方法集及事件集等 for (Class intrfc : interfaces) { CallbackInfo interfaceInfo = getInfo(intrfc); if (!interfaceInfo.mEvents.isEmpty()) { if (info.mInterfaces == null) { info.mInterfaces = new ArrayList<>(); } info.mInterfaces.add(interfaceInfo); } } return info; } @SuppressWarnings("WeakerAccess") static class CallbackInfo{ final Set<Event> mEvents; @Nullable List<MethodReference> mMethodReferences; @Nullable List<CallbackInfo> mInterfaces; @Nullable CallbackInfo mSuper; CallbackInfo(Set<Event> events, @Nullable List<MethodReference> methodReferences) { mEvents = events; mMethodReferences = methodReferences; } } @SuppressWarnings("WeakerAccess") static class MethodReference{ final Set<Event> mEvents; final int mCallType; final Method mMethod; MethodReference(Set<Event> events, int callType, Method method) { mEvents = events; mCallType = callType; mMethod = method; mMethod.setAccessible(true); } } private staticSet<Event>expandOnAnyEvents(Event[] events){ boolean hasOnAllEvents = false; for (Event e: events) { if (e == Event.ON_ANY) { hasOnAllEvents = true; break; } } if (!hasOnAllEvents) { HashSet<Event> set = new HashSet<>(); Collections.addAll(set, events); return set; } else { return ALL_EVENTS; } } private static final Set<Event> ALL_EVENTS = new HashSet<Event>() { { add(Event.ON_CREATE); add(Event.ON_START); add(Event.ON_RESUME); add(Event.ON_PAUSE); add(Event.ON_STOP); add(Event.ON_DESTROY); } }; private static final int CALL_TYPE_NO_ARG = 0; private static final int CALL_TYPE_PROVIDER = 1; private static final int CALL_TYPE_PROVIDER_WITH_EVENT = 2; </code></pre> <p>不难看出 createInfo 主要是获取所有带 OnLifecycleEvent 注解的方法,在判断这些方法的合法性后,根据对应方法的参数个数、事件类型及方法名实例化 <strong>MethodReference</strong> 并添加到 List 中,同时亦会将 Object(LifecycleObserver) 涉及的所有事件类型保存到 Set 中。当遍历完 Object(LifecycleObserver) 定义的所有方法后,会根据 List 和 Set 实例化 <strong>CallbackInfo</strong> 并缓存至 <em>sInfoCache</em> 中。最后对 Object(LifecycleObserver) 的父类和接口执行同样的操作(即以它们作为参数传入 createInfo 中),并将返回的 <strong>CallbackInfo</strong> 分别赋值给 info.mSuper 和 info.mInterfaces 供后面使用。</p> <p>ObserverWithState 的 sync 流程</p> <p>在 <strong>GenericLifecycleObserver</strong> 的实例化完成后, addObserver 会调用 <strong>ObserverWithState</strong> 的 sync 方法:</p> <pre> <code class="language-java">observerWithState.sync(); void sync(){ if (mState == DESTROYED && mObserverCurrentState == INITIALIZED) { mObserverCurrentState = DESTROYED; } while (mObserverCurrentState != mState) { Event event = mObserverCurrentState.isAtLeast(mState) ? downEvent(mObserverCurrentState) : upEvent(mObserverCurrentState); mObserverCurrentState = getStateAfter(event); mCallback.onStateChanged(mLifecycleOwner, event); } } </code></pre> <p>其中 mState 表示的是 <strong>LifecycleRegistry</strong> 当前所处的状态。</p> <p>如果当前 <strong>LifecycleRegistry</strong> 处于 DESTROYED , <strong>ObserverWithState</strong> 处于 INITIALIZED 时, <strong>ObserverWithState</strong> 会直接进入 DESTROYED ,并且此时 LifecycleObserver 不会收到任何回调。</p> <p>当 <strong>ObserverWithState</strong> 与 <strong>LifecycleRegistry</strong> 的状态不相同时, <strong>ObserverWithState</strong> 会通过 mObserverCurrentState.isAtLeast(mState) 比较自身状态是高于或低于 <strong>LifecycleRegistry</strong> 的状态。状态的高低顺序(升序)如下:</p> <pre> <code class="language-java">public enum State { DESTROYED, INITIALIZED, CREATED, STARTED, RESUMED; public boolean isAtLeast(State state){ return compareTo(state) >= 0; } } </code></pre> <p>当 <strong>ObserverWithState</strong> 的状态高于或低于 <strong>LifecycleRegistry</strong> 时,会分别调用 downEvent 或 upEvent 决定 LifecycleObserver 的下一个 Lifecycle 事件:</p> <pre> <code class="language-java">staticEventdownEvent(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); } staticEventupEvent(State state){ switch (state) { case INITIALIZED: case DESTROYED: return ON_CREATE; case CREATED: return ON_START; case STARTED: return ON_RESUME; case RESUMED: throw new IllegalArgumentException(); } throw new IllegalArgumentException("Unexpected state value " + state); } </code></pre> <p>紧接着 <strong>ObserverWithState</strong> 会将获得的事件类型传入 getStateAfter 中获取新的状态:</p> <pre> <code class="language-java">staticStategetStateAfter(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); } </code></pre> <p>如果修改完状态后 <strong>ObserverWithState</strong> 与 <strong>LifecycleRegistry</strong> 的状态依然不相同,上述过程会一直重复执行直到相同为止。例如,当 <strong>LifecycleRegistry</strong> 处于 RESUMED 而 <strong>ObserverWithState</strong> 处于 INITIALIZED 时, <strong>ObserverWithState</strong> 的状态会按照 INITIALIZED -> CREATED -> STARTED -> RESUMED 这样的顺序变迁。</p> <p>下面再来了解下每次状态变迁之后调用的 OnStateChanged 方法内部做了些什么。</p> <p>从前面 <strong>GenericLifecycleObserver</strong> 的生成过程中我们可以知道,这里的分析也需要分为两种情况分析:</p> <ul> <li>LifecycleAdapter</li> <li>ReflectiveGenericLifecycleObserver</li> </ul> <p>LifecycleAdapter</p> <p>由于没有找到 <strong>LifecycleProcessor</strong> 的源码,这里我就写了个 DataObserver 来让各位稍微了解一下 <strong>LifecycleAdapter</strong> :</p> <pre> <code class="language-java">public class DataObserverimplements LifecycleObserver{ @OnLifecycleEvent(Lifecycle.Event.ON_ANY) public void onAny(){ } @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public void onCreate(){ } @OnLifecycleEvent(Lifecycle.Event.ON_START) public void onStart(){ } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void onResume(){ } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void onPause(){ } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) public void onStop(){ } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) public void onDestroy(){ } } </code></pre> <pre> <code class="language-java">public class DataObserver_LifecycleAdapterimplements GenericLifecycleObserver{ final DataObserver mReceiver; DataObserver_LifecycleAdapter(DataObserver receiver) { this.mReceiver = receiver; } @Override public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event){ mReceiver.onAny(); if (event == Lifecycle.Event.ON_CREATE) { mReceiver.onCreate(); } if (event == Lifecycle.Event.ON_START) { mReceiver.onStart(); } if (event == Lifecycle.Event.ON_RESUME) { mReceiver.onResume(); } if (event == Lifecycle.Event.ON_PAUSE) { mReceiver.onPause(); } if (event == Lifecycle.Event.ON_STOP) { mReceiver.onStop(); } if (event == Lifecycle.Event.ON_DESTROY) { mReceiver.onDestroy(); } } publicObjectgetReceiver(){ return mReceiver; } } </code></pre> <p>从 DataObserver_LifecycleAdapter 中可以大概猜测到, <strong>LifecycleProcessor</strong> 生成的 <strong>LifecycleAdapter</strong> 会根据 LifecycleObserver 中带 OnLifecycleEvent 注解的方法生成 onStateChanged 。</p> <p>从上面的代码不难看出, <strong>LifecycleAdapter</strong> 的 onStateChanged 会根据不同的事件分别执行 LifecycleObserver 中对应的方法。</p> <p>ReflectiveGenericLifecycleObserver</p> <p>当 Lifecycle 发生变化调用 onStateChanged 时:</p> <pre> <code class="language-java">@Override public void onStateChanged(LifecycleOwner source, Event event){ invokeCallbacks(mInfo, source, event); } @SuppressWarnings("ConstantConditions") private void invokeCallbacks(CallbackInfo info, LifecycleOwner source, Event event){ // 当前 ReflectiveGenericLifecycleObserver 有无该事件的相关注解 if (info.mEvents.contains(event)) { for (int i = info.mMethodReferences.size() - 1; i >= 0; i--) { MethodReference reference = info.mMethodReferences.get(i); invokeCallback(reference, source, event); } } // TODO prevent duplicate calls into the same method. Preferably while parsing if (info.mSuper != null) { // 交由此前传入的 LifecycleObserver 的父类处理 invokeCallbacks(info.mSuper, source, event); } if (info.mInterfaces != null) { final int size = info.mInterfaces.size(); for (int i = 0; i < size; i++) { // 交由此前传入的 LifecycleObserver 的接口处理 invokeCallbacks(info.mInterfaces.get(i), source, event); } } } private void invokeCallback(MethodReference reference, LifecycleOwner source, Event event){ // MethodReference 是否包含该事件 if (reference.mEvents.contains(event)) { try { switch (reference.mCallType) { case CALL_TYPE_NO_ARG: reference.mMethod.invoke(mWrapped); break; case CALL_TYPE_PROVIDER: reference.mMethod.invoke(mWrapped, source); break; case CALL_TYPE_PROVIDER_WITH_EVENT: reference.mMethod.invoke(mWrapped, source, event); break; } } catch (InvocationTargetException e) { throw new RuntimeException("Failed to call observer method", e.getCause()); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } </code></pre> <p>ReflectiveGenericLifecycleObserver会判断接收到的事件是否存在于 createInfo 生成的 mInfo 中的事件集之中。当存在时,会遍历此前缓存的方法列表并由 <strong>MethodReference</strong> 判断是否处理该事件。当需要处理时,会根据此前得到的 callType 决定传递哪些参数。同样的,在处理完 class(LifecycleObserver) 自身定义的方法后,会将事件分发给父类和接口的 <strong>MethodReference</strong> 处理。</p> <p>小结</p> <p>所以 sync 方法的用途是使 LifecycleObserver 的状态与 LifecycleRegistry 的状态同步并通知 LifecycleObserver 状态已经发生变化。</p> <p>至此, addObserver 完成了自身的工作。</p> <h3>handleLifecycleEvent 流程</h3> <p>从 <strong>ServiceLifecycleDispatcher</strong> , <strong>LifecycleDispatcher</strong> 等的源码我们可以看出所有 Lifecycle 事件都是通过 <strong>LifecycleRegistry</strong> 的 handleLifecycleEvent 来处理:</p> <pre> <code class="language-java">public void handleLifecycleEvent(Lifecycle.Event event){ if (mLastEvent == event) { return; } mLastEvent = event; mState = getStateAfter(event); for (Map.Entry<LifecycleObserver, ObserverWithState> entry : mObserverSet) { entry.getValue().sync(); } } </code></pre> <p>有了前面的经验,我们就能很容易地知道当 Lifecycle 发生变化时, handleLifecycleEvent<br> 会通过 getStateAfter 获取当前应处的状态并修改 mState 值,紧接着遍历所有 <strong>ObserverWithState</strong> 并调用他们的 sync 方法来同步且通知 LifecycleObserver 状态发生变化。</p> <h3>小结</h3> <p>至此,我们了解到当 <strong>LifecycleRegistry</strong> 的 addObserver 或 handleLifecycleEvent 被调用时,新的 Lifecycle 事件会被传到 <strong>LifecycleAdapter</strong> 或 <strong>ReflectiveGenericLifecycleObserver</strong> 的 onStateChanged 中从而通知 LifecycleObserver Lifecycle 发生变化。</p> <h2>最后</h2> <p>结合来看,Lifecycle 事件可由 <strong>LifecycleDispatcher</strong> (ActivityLifecycleCallbacks, FragmentLifecycleCallbacks, Fragment), <strong>ProcessLifecycleOwner</strong> , <strong>LifecycleService</strong> 产生,并通过 <strong>LifecycleRegistry</strong> , <strong>LifecycleAdapter</strong> / <strong>ReflectiveGenericLifecycleObserver</strong> 传递给 LifecycleObserver。</p> <p>至此,Lifecycle-aware Components 的基础框架分析完毕。</p> <h3>稍微再说几句</h3> <ul> <li>个人认为该框架最有趣的地方在于使用 <strong>ReportFragment</strong> 监听 Activity 的生命周期;</li> <li>Lifecycle 确实能帮助我们分拆 onCreate , onStart 等生命周期方法内所做的初始化、销毁操作,避免过多的代码堆在生命周期方法之中。只不过与 MVP 一样,会增加不少类,很小的项目也没什么必要使用;</li> <li>整个框架的代码比较干净利落,反正看起来压力不大,学到的东西也不少。</li> </ul> <p> </p> <p>来自:http://chaosleong.github.io/2017/05/27/How-Lifecycle-aware-Components-actually-works/</p> <p> </p>