Lifecycle-aware Components 源碼分析
注:本文所有代碼基于 android.arch.lifecycle 1.0.0-alpha1
另外,為了避免混淆,Fragment、Activity 等組件自身的生命周期直用 “生命周期” 一詞,而由 Lifecycle 提供的生命周期則稱為 “Lifecyle”
最近看到不少人討論 Google 推的 Android Architecture Components ,其中 Handling Lifecycles 一章展現了如何利用 android.arch.lifecycle 包提供的類來控制數據、監聽器等的 Lifecycle。同時, LiveData 與 ViewModel 的 Lifecycle 也依賴于 Lifecycle 框架,所以分析 Lifecyle 顯然是有必要的。
Lifecycle到底是通過怎樣的方式來綁定 Android 組件的生命周期以及如何通知 LifecycleObserver 狀態變化的呢?本文將會圍繞這兩個問題深入分析 Lifecycle 源碼。
前置工作
由于完整的 Lifecycle 分為 common , core , extensions , runtime 四個包,并包含 ViewModel 、 LiveData 部分內容。為了方便分析,利用 proguard(只添加 -dontobfuscate ) 剔除所有不需要用到的類。
最終剩下的類:
android.arch.core.internal( core )
- SafeIterableMap
android.arch.lifecycle( runtime )
- EmptyActivityLifecycleCallbacks
- LifecycleActivity
- LifecycleDispatcher
- LifecycleFragment
- LifecycleRegistry
- LifecycleRegistryOwner
- LifecycleRuntimeTrojanProvider
- LifecycleService
- ProcessLifecycleOwner
- ReportFragment
- ServiceLifecycleDispatcher
android.arch.lifecycle( common )
- GenericLifecycleObserver
- Lifecycle
- LifecycleObserver
- LifecycleOwner
- Lifecycling
- OnLifecycleEvent
- ReflectiveGenericLifecycleObserver
Runtime
先看 Lifecycle 的 AndroidManifest.xml(可以在 build/outputs/logs/manifest-merger-*.txt 中找到對應的路徑):
<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>
可以看到 Lifecycle 會給應用添加一個 exported="false" 的 LifecycleRuntimeTrojanProvider 。
LifecycleRuntimeTrojanProvider
/**
* Internal class to initialize Lifecycles.
* @hide
*/
public class LifecycleRuntimeTrojanProviderextends ContentProvider{
@Override
public boolean onCreate(){
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
return true;
}
...
}
javadoc 已經寫得很明顯, LifecycleRuntimeTrojanProvider 就是用于初始化 Lifecycle 的,其余 ContentProvider 應實現的方法返回的均為默認值(null 或 0),順著代碼先看 LifecycleDispatcher 。
LifecycleDispatcher
LifecycleDispatcher的初始化代碼比較簡單:
private static AtomicBoolean sInitialized = new AtomicBoolean(false);
static void init(Context context){
if (sInitialized.getAndSet(true)) {
return;
}
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
}
主要就是注冊了一個 ActivityLifecycleCallbacks —— DispatcherActivityCallback 。
DispatcherActivityCallback
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);
}
}
}
DispatcherActivityCallback的 onActivityStopped 和 onActivitySaveInstanceState 方法會將 LifecycleRegistryOwner 的狀態重置成 CREATED (為何是 CREATED 可以查看 Lifecycle 的狀態圖 及 各狀態的描述 )。再看 onActivityCreated ,當 activity 是 FragmentActivity 時,額外注冊 FragmentLifecycleCallbacks —— FragmentCallback 。接著添加 ReportFragment 到 activity 中,考慮到并不是所有人都會使用 FragmentActivity,所以添加 ReportFragment 時使用的是原生的 FragmentManager。
ReportFragment
接著來看一下 ReportFragment 的源碼:
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();
}
}
不難看出 ReportFragment 主要是在所有生命周期發生變化時生成對應的 Lifecycle 事件發送到 LifecycleRegistryOwner(Activity)中。并在 onActivityCreated , onStart , onResume 時額外通知 ActivityInitializationListener (暫且記住,后面會用到)。可能會有讀者有疑問,為什么要使用 ReportFragment 的生命周期而不直接使用 ActivityLifecycleCallbacks 的回調來處理 Lifecycle 的變化?由于 ActivityLifecycleCallbacks 的回調比 Fragment 和 Activity 還要早,實際上未真正執行對應的生命周期方法。至于為什么用 Fragment 而不直接重載 Activity 的生命周期,顯然用 Fragment 侵入性低。
FragmentCallback
再看回 FragmentCallback :
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);
}
}
與 DispatcherActivityCallback 類似,當 Fragment 為 Parent Fragment 且實現了 LifecycleRegistryOwner 接口時,FragmentCallback 會添加一個 Child Fragment —— DestructionReportFragment 。
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);
}
}
與 DispatcherActivityCallback 不一樣的是, FragmentCallback 混合了 FragmentLifecycleCallbacks 及 Fragment 的生命周期來通知 Child Fragment Lifecycle 發生變化。這樣做是為了確保 ON_CREATE , ON_START , ON_RESUME 在對應的生命周期之后分發, ON_PAUSE , ON_STOP , ON_DESTROY 在對應的生命周期之前分發。
所以 FragmentCallback 主要是通知 Parent Fragment(LifecycleRegistryOwner)Lifecycle 發生變化,從而給 Child Fragment(LifecycleObserver)分發 Lifecycle 事件。
值得注意的是,由于 FragmentLifecycleCallbacks 只存在于 v4 包中,如果 Child 是 android.app.Fragment,即使 Child 通過 ((LifecycleRegistryOwner) getParentFragment()).getLifecycle().addObserver(this) 注冊了監聽也不會接收到相關的 Lifecycle 事件,因為 LifecycleRegistryOwner 的 handleLifecycleEvent 從未被調用過。(暫時未知 Google 是有意為之,抑或是個 BUG。)
ProcessLifecycleOwner
看完 LifecycleDispatcher ,接著來了解一下 ProcessLifecycleOwner :
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;
}
}
比起 LifecycleDispatcher , ProcessLifecycleOwner 的代碼要簡單得多。 ProcessLifecycleOwner 的作用就是監聽當前進程中 Activity 的狀態變化以統計 Activity 的數量從而通知 LifecycleObserver Lifecycle 發生變化。
而為了達到這一目的, ProcessLifecycleOwner 的做法是為 LifecycleDispatcher 注冊 ActivityInitializationListener 從而確保 Activity 進入了 onStart 或 onResume 生命周期(還記得前面 ReportFragment 提到的這部分內容?),并配合 ActivityLifecycleCallbacks 的 onActivityPaused , onActivityStopped 確保 Lifecycle 事件發生在 Activity 的 onPause , onStop 之前。
另外,由于 ProcessLifecycleOwner 沒有 ON_DESTROY ,接收到 ON_STOP 時已經表示當前進程無存活的 Activity。同時需注意一點: ProcessLifecycleOwner 的統計不包含 Service,換句話說,即使接收到 ON_STOP 事件,并不意味著當前進程結束。
LifecycleService
了解完 Lifecycle 框架中 Activity、Fragment 相關的生命周期事件是如何生成的,接下來就看看 Service 相關的生命周期事件是如何生成的。
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();
}
}
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;
}
}
}
}
ServiceLifecycleDispatcher用于協助 LifecycleService 分發 Lifecycle 事件并確保每次發生變化時回調執行于 Worker Thread。同時我們可以看到 LifecycleService 只會產生 ON_CREATE , ON_START , ON_STOP , ON_DESTROY 四種事件。
需注意的是繼承 LifecycleService 時如需重寫 onStart 或 onStartCommand 方法,必須調用 super.onStart 或 super.onStartCommand 以確保 ON_START 事件能夠被觸發。
小結
至此,我們了解到 Lifecycle 框架是如何將 Lifecycle 事件與 Android 組件的生命周期綁定的:
- LifecycleDispatcher ,通過 ActivityLifecycleCallbacks、FragmentLifecycleCallbacks 及 Fragment 獲知 Activity、Fragment 的生命周期變化并產生相應的 Lifecycle 事件;
- ProcessLifecycleOwner ,通過 ActivityLifecycleCallbacks 與 LifecycleDispatcher 配合監聽當前進程中 Activities 的生命周期變化并在必要時產生相應的 Lifecycle 事件;
- LifecycleService ,通過重載 Service 的生命周期方法并在相應方法內產生相應的 Lifecycle 事件。
Common
LifecycleRegistry 的 addObserver 流程
我們使用的 LifecycleActivity 以及 LifecycleFragment 內部都是通過 LifecycleRegistry 來管理及分發 Lifecycle 事件。
先了解下 LifecycleRegistry 中 addObserver 的內部邏輯:
private SafeIterableMap<LifecycleObserver, ObserverWithState> mObserverSet =
new SafeIterableMap<>();
@Override
public void addObserver(LifecycleObserver observer){
ObserverWithState observerWithState = new ObserverWithState(observer);
mObserverSet.putIfAbsent(observer, observerWithState);
observerWithState.sync();
}
class ObserverWithState{
private State mObserverCurrentState = INITIALIZED;
private GenericLifecycleObserver mCallback;
ObserverWithState(LifecycleObserver observer) {
mCallback = Lifecycling.getCallback(observer);
}
...
}
在調用 LifecycleRegistry 的 addObserver 方法時,LifecycleObserver 被傳至 ObserverWithState 并通過 Lifecycling.getCallback(observer) 生成 GenericLifecycleObserver 。
Lifecycling
@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
}
當調用 getCallback 時, Lifecycling 會根據傳入的 Object(LifecycleObserver)調用 getGeneratedAdapterConstructor 。
LifecycleAdapter 的實例化
@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";
}
不難看出, getGeneratedAdapterConstructor 主要是獲取 annotationProcessor 生成的 xxx_LifecycleAdapter (關于 LifecycleAdapter 后面補充說明)的構造函數,并實例化返回到 getCallback 中。需注意的是,如果找不到 LifecycleAdapter 且 object(LifecycleObserver) 存在父類時會試圖獲取父類的 LifecycleAdapter (估計是為了應對混淆時只混淆了子類的情況)。
ReflectiveGenericLifecycleObserver 的實例化
當獲取 LifecycleAdapter 失敗后, Lifecycling 會直接實例化 ReflectiveGenericLifecycleObserver 作為替代(估計也是為了應對混淆)。
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;
}
...
}
ReflectiveGenericLifecycleObserver在實例化時會獲取 Object(LifecycleObserver)的 class 并作為參數調用 createInfo 方法。
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;
不難看出 createInfo 主要是獲取所有帶 OnLifecycleEvent 注解的方法,在判斷這些方法的合法性后,根據對應方法的參數個數、事件類型及方法名實例化 MethodReference 并添加到 List 中,同時亦會將 Object(LifecycleObserver) 涉及的所有事件類型保存到 Set 中。當遍歷完 Object(LifecycleObserver) 定義的所有方法后,會根據 List 和 Set 實例化 CallbackInfo 并緩存至 sInfoCache 中。最后對 Object(LifecycleObserver) 的父類和接口執行同樣的操作(即以它們作為參數傳入 createInfo 中),并將返回的 CallbackInfo 分別賦值給 info.mSuper 和 info.mInterfaces 供后面使用。
ObserverWithState 的 sync 流程
在 GenericLifecycleObserver 的實例化完成后, addObserver 會調用 ObserverWithState 的 sync 方法:
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);
}
}
其中 mState 表示的是 LifecycleRegistry 當前所處的狀態。
如果當前 LifecycleRegistry 處于 DESTROYED , ObserverWithState 處于 INITIALIZED 時, ObserverWithState 會直接進入 DESTROYED ,并且此時 LifecycleObserver 不會收到任何回調。
當 ObserverWithState 與 LifecycleRegistry 的狀態不相同時, ObserverWithState 會通過 mObserverCurrentState.isAtLeast(mState) 比較自身狀態是高于或低于 LifecycleRegistry 的狀態。狀態的高低順序(升序)如下:
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(State state){
return compareTo(state) >= 0;
}
}
當 ObserverWithState 的狀態高于或低于 LifecycleRegistry 時,會分別調用 downEvent 或 upEvent 決定 LifecycleObserver 的下一個 Lifecycle 事件:
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);
}
緊接著 ObserverWithState 會將獲得的事件類型傳入 getStateAfter 中獲取新的狀態:
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);
}
如果修改完狀態后 ObserverWithState 與 LifecycleRegistry 的狀態依然不相同,上述過程會一直重復執行直到相同為止。例如,當 LifecycleRegistry 處于 RESUMED 而 ObserverWithState 處于 INITIALIZED 時, ObserverWithState 的狀態會按照 INITIALIZED -> CREATED -> STARTED -> RESUMED 這樣的順序變遷。
下面再來了解下每次狀態變遷之后調用的 OnStateChanged 方法內部做了些什么。
從前面 GenericLifecycleObserver 的生成過程中我們可以知道,這里的分析也需要分為兩種情況分析:
- LifecycleAdapter
- ReflectiveGenericLifecycleObserver
LifecycleAdapter
由于沒有找到 LifecycleProcessor 的源碼,這里我就寫了個 DataObserver 來讓各位稍微了解一下 LifecycleAdapter :
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(){
}
}
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;
}
}
從 DataObserver_LifecycleAdapter 中可以大概猜測到, LifecycleProcessor 生成的 LifecycleAdapter 會根據 LifecycleObserver 中帶 OnLifecycleEvent 注解的方法生成 onStateChanged 。
從上面的代碼不難看出, LifecycleAdapter 的 onStateChanged 會根據不同的事件分別執行 LifecycleObserver 中對應的方法。
ReflectiveGenericLifecycleObserver
當 Lifecycle 發生變化調用 onStateChanged 時:
@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);
}
}
}
ReflectiveGenericLifecycleObserver會判斷接收到的事件是否存在于 createInfo 生成的 mInfo 中的事件集之中。當存在時,會遍歷此前緩存的方法列表并由 MethodReference 判斷是否處理該事件。當需要處理時,會根據此前得到的 callType 決定傳遞哪些參數。同樣的,在處理完 class(LifecycleObserver) 自身定義的方法后,會將事件分發給父類和接口的 MethodReference 處理。
小結
所以 sync 方法的用途是使 LifecycleObserver 的狀態與 LifecycleRegistry 的狀態同步并通知 LifecycleObserver 狀態已經發生變化。
至此, addObserver 完成了自身的工作。
handleLifecycleEvent 流程
從 ServiceLifecycleDispatcher , LifecycleDispatcher 等的源碼我們可以看出所有 Lifecycle 事件都是通過 LifecycleRegistry 的 handleLifecycleEvent 來處理:
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();
}
}
有了前面的經驗,我們就能很容易地知道當 Lifecycle 發生變化時, handleLifecycleEvent
會通過 getStateAfter 獲取當前應處的狀態并修改 mState 值,緊接著遍歷所有 ObserverWithState 并調用他們的 sync 方法來同步且通知 LifecycleObserver 狀態發生變化。
小結
至此,我們了解到當 LifecycleRegistry 的 addObserver 或 handleLifecycleEvent 被調用時,新的 Lifecycle 事件會被傳到 LifecycleAdapter 或 ReflectiveGenericLifecycleObserver 的 onStateChanged 中從而通知 LifecycleObserver Lifecycle 發生變化。
最后
結合來看,Lifecycle 事件可由 LifecycleDispatcher (ActivityLifecycleCallbacks, FragmentLifecycleCallbacks, Fragment), ProcessLifecycleOwner , LifecycleService 產生,并通過 LifecycleRegistry , LifecycleAdapter / ReflectiveGenericLifecycleObserver 傳遞給 LifecycleObserver。
至此,Lifecycle-aware Components 的基礎框架分析完畢。
稍微再說幾句
- 個人認為該框架最有趣的地方在于使用 ReportFragment 監聽 Activity 的生命周期;
- Lifecycle 確實能幫助我們分拆 onCreate , onStart 等生命周期方法內所做的初始化、銷毀操作,避免過多的代碼堆在生命周期方法之中。只不過與 MVP 一樣,會增加不少類,很小的項目也沒什么必要使用;
- 整個框架的代碼比較干凈利落,反正看起來壓力不大,學到的東西也不少。
來自:http://chaosleong.github.io/2017/05/27/How-Lifecycle-aware-Components-actually-works/