參考Android Jetpack架構組件之 Lifecycle(源碼篇)android
關於Lifecycle的使用考上一篇文章Android Jetpack框架之 Lifecycles(使用篇),從使用的方法中咱們知道Lifecycle的實現主要依賴:LifecycleObserver、LifecycleOwner;經過像Owner註冊Observer實現感知Owner的生命週期,下面一塊兒看看源碼是如何巧妙設計的;架構
// 實現LifecycleObserver class MyObserver(var lifecycle: Lifecycle, var callback: CallBack) : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public fun connectOnCreate() { p("connectOnCreate") } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public fun connectOnResume() { p("connectOnResume") } } // LifecycleObserver 是一個空接口 public interface LifecycleObserver { }
上面過程作了三件事情:app
@OnLifecycleEvent:運行註解框架
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OnLifecycleEvent { Lifecycle.Event value(); }
// 生命週期Event 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 } //5個對應的生命週期狀態 public enum State { DESTROYED, INITIALIZED, CREATED, STARTED, RESUMED; public boolean isAtLeast(@NonNull State state) { return compareTo(state) >= 0; } }
經過Lifecycle.Event和State的查看,系統提供了Activity每一個生命週期對應的Event,而Event有會有對應的State,此時 以大體猜測到上面的執行過程:ide
LifecycleOwner源碼分析
class LifeCyclerActivity : AppCompatActivity() { ... var myObserver = MyObserver(lifecycle, object : CallBack { // 建立LifecyclerObserver override fun update() { ... } }) lifecycle.addObserver(myObserver) // 添加觀察者 } }
從上面的使用狀況看出,使用的活動須要調用getLifecycle()方法,返回LifecycleRegistry,這裏的getLifecycle()方法實際上是接口LifecycleOwner接口中的方法,this
@SuppressWarnings({"WeakerAccess", "unused"}) public interface LifecycleOwner { /** * Returns the Lifecycle of the provider. * * @return The lifecycle of the provider. */ @NonNull Lifecycle getLifecycle(); }
此時LifecycleActivity雖然沒有實現接口,由於他繼承的AppCompatActivity繼承了SupportActivity,而SupportActivity實現了接口spa
@RestrictTo(LIBRARY_GROUP) public class SupportActivity extends Activity implements LifecycleOwner { private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); //建立 @Override public Lifecycle getLifecycle() { // 重寫方法返回LifecycleRegistry return mLifecycleRegistry; } }
SupportActivity除了執行上述操做外,在onCrate的方法中還有一句重要的代碼,初始化了一個ReportFragment.net
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this); } ReportFragment public class ReportFragment extends Fragment { private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle" + ".LifecycleDispatcher.report_fragment_tag"; public static void injectIfNeededIn(Activity activity) { //初始化Fragment android.app.FragmentManager manager = activity.getFragmentManager(); if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) { manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit(); 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); 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); } } } }
上面代碼中作了兩件事:設計
在dispatch()方法中根據LifecyclerOwner和LifecyclerRegistryOwner實例分別處理,由於LifecyclerRegistryOwner也是繼承LifecyclerOwner,而在咱們SupportActivity中的getLifecycler()中返回的是LifecycleRegistry,因此此處回調的都是LifecycleRegistry的handleLifecycleEvent;