版權聲明:本文已受權微信公衆號:Android必修課,轉載請申明出處java
衆所周知,Android凡是須要展現給用戶看的,都包含着生命週期這個概念,例如Activity、Fragment、View等都與生命週期息息相關,在生命週期函數裏,它們各自完成建立、渲染、銷燬等工做。android
可是一旦咱們往某個生命週期函數中,加入咱們本身的邏輯,如果處理不當,就有可能破壞其原有的生命週期,形成內存泄漏甚至應用崩潰等問題。程序員
Android官方彷佛也注意到了這一點,所以在Google IO 2018大會上,推出了Android Jetpack開發工具包,其中就包含了一個很是重要的生命週期組件,即本篇的主角-Lifecycle微信
本文篇幅較長,請你們耐心閱讀。app
Lifecycle是一個生命週期感知組件,通常用來響應Activity、Fragment等組件的生命週期變化,並將變化通知到已註冊的觀察者。有助於更好地組織代碼,讓代碼邏輯符合生命週期規範,減小內存泄漏,加強穩定性。ide
Lifecycle已經歸入新版本的AppCompatActivity和Fragment中了,而且Lifecycle仍是Android Jetpack中其餘兩個組件LiveData和ViewModel的基礎,意味着這個庫可能將持續伴隨着咱們後續的開發,所以有什麼理由不學習一番呢?函數
按照國際規範,咱們先講使用,後解析源碼。工具
在app或者module目錄下的build.gradle中,添加依賴:post
dependencies { ...... implementation "android.arch.lifecycle:runtime:1.1.1" implementation "android.arch.lifecycle:extensions:1.1.1" // 若是你使用java8開發,能夠添加這個依賴,裏面只有一個類 implementation "android.arch.lifecycle:common-java8:1.1.1" }
public class Java7Observer implements LifecycleObserver { private static final String TAG = Java7Observer.class.getSimpleName(); @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public void onCreate() { Log.d(TAG, "onCreate"); } @OnLifecycleEvent(Lifecycle.Event.ON_START) public void onStart() { Log.d(TAG, "onStart"); } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void onResume() { Log.d(TAG, "onResume"); } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void onPause() { Log.d(TAG, "onPause"); } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) public void onStop() { Log.d(TAG, "onStop"); } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) public void onDestroy() { Log.d(TAG, "onDestroy"); } }
首先,咱們須要實現LifecycleObserver這個接口,而後在咱們的方法上加上@OnLifecycleEvent註解,註解值表示該方法對應生命週期的哪一個函數,這裏咱們把全部生命週期函數都加上了,並簡單地打印了一句Log。學習
我想有人會問,爲何這個class要命名Java7Observer ? 沒錯,由於Java8中,官方推薦用另一種方式:
public class Java8Observer implements DefaultLifecycleObserver { private static final String TAG = Java8Observer.class.getSimpleName(); @Override public void onCreate(@NonNull LifecycleOwner owner) { Log.d(TAG, "onCreate"); } @Override public void onStart(@NonNull LifecycleOwner owner) { Log.d(TAG, "onStart"); } @Override public void onResume(@NonNull LifecycleOwner owner) { Log.d(TAG, "onResume"); } @Override public void onPause(@NonNull LifecycleOwner owner) { Log.d(TAG, "onPause"); } @Override public void onStop(@NonNull LifecycleOwner owner) { Log.d(TAG, "onStop"); } @Override public void onDestroy(@NonNull LifecycleOwner owner) { Log.d(TAG, "onDestroy"); } }
理由很簡單,Lifecycle源碼中有一段註釋:
/* ..... * </pre> * If you use <b>Java 7 Language</b>, Lifecycle events are observed using annotations. * Once Java 8 Language becomes mainstream on Android, annotations will be deprecated, so between * {@link DefaultLifecycleObserver} and annotations, * you must always prefer {@code DefaultLifecycleObserver}. * <pre> * ...... */
翻譯一下就是:「若是你丫的用的是java7,那你就用註解唄,可是我告訴你,一旦java8上位了,你那些註解就過期了,我勸你最好用DefaultLifecycleObserver」
若是你使用新版本的AppcompatActivity(>26.1.0),能夠這麼寫:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 直接調用getLifecycle(),添加Observer getLifecycle().addObserver(new Java7Observer()); getLifecycle().addObserver(new Java8Observer()); } }
若是你的AppCompatActivity沒有更新到最新,那麼你須要自實現LifecycleOwner接口,並在Activity生命週期函數中分發事件
public class MainActivity extends Activity implements LifecycleOwner { private LifecycleRegistry mLifecycleRegistry; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mLifecycleRegistry = new LifecycleRegistry(this); mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE); mLifecycleRegistry.addObserver(new TestObserver()); } @NonNull @Override public Lifecycle getLifecycle() { return mLifecycleRegistry; } @Override public void onStart() { super.onStart(); mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START); } @Override public void onResume() { super.onResume(); mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); } @Override public void onPause() { mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE); super.onPause(); } @Override public void onStop() { mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP); super.onStop(); } @Override public void onDestroy() { mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY); super.onDestroy(); } }
ok,完事兒了,我們跑起來看一哈,已經成功和生命週期關聯上了。
MVP想必你們都用過,或者據說過,View層經過Presenter層和Model層進行通訊,所以Presenter層若是作了什麼超出View生命週期的事,又沒有及時釋放內存,就會形成內存泄漏。
因此,原來的Presenter,爲了響應生命週期,咱們可能會這麼寫:
先定義全部的生命週期函數
public class MainPresenter { public void onCreate() { } public void onStart() { } public void onResume() { } public void onPause() { } public void onStop() { } public void onDestroy() { } }
而後再與Activity生命週期一一綁定,若是有多個相似的須要響應生命週期的類,Activity的生命週期函數就會變得很是臃腫
public class MainActivity extends AppCompatActivity { private MainPresenter mPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mPresenter = new MainPresenter(); mPresenter.onCreate(); } @Override protected void onResume() { super.onResume(); mPresenter.onCreate(); // VideoPlayer.onResume(); // ... } @Override protected void onStart() { super.onStart(); mPresenter.onStart(); // VideoPlayer.onStart(); // ... } @Override protected void onPause() { super.onPause(); mPresenter.onPause(); // VideoPlayer.onPause(); // ... } @Override protected void onStop() { super.onStop(); mPresenter.onStop(); // VideoPlayer.onStop(); // ... } @Override protected void onDestroy() { super.onDestroy(); mPresenter.onDestroy(); // VideoPlayer.onDestroy(); // ... } }
所以,Lifecycle就是爲了解決這個痛點,將生命週期的響應分發到各個觀察者中去,咱們只須要在Activity中調用一行代碼:
getLifecycle().addObserver(mPresenter);
代碼量蹭蹭就下來了。諸如音視頻播放、圖片加載,這些吃內存大戶,都應該響應生命週期,及時釋放內存,不然極可能就會形成OOM。
在項目中引入一個庫,卻不懂是怎麼實現的,是一件很是危險的行爲,所以咱們不只要學會怎麼用,還得知道其中的原理。
先看一張官方的圖:
lifecycle-states
能夠看到兩個很顯眼的單詞:State和Event,這也是貫穿整個Lifecycle的兩個概念:狀態和事件。
Lifecycle將Activity的生命週期函數對應成State,生命週期改變,會形成State改變,而State變化將觸發Event事件,從而被LifecycleObser接收。
State:狀態,是Lifecycle中對應Activity生命週期的一種狀態標識,從圖中能夠看到,它有INITIALIZED、DESTROYED、CREATED、STARTED、RESUMED這5中狀態。
Event:事件,當State發生變化時,Lifecycle會向已註冊的LifecycleObserver發送事件,例如:當State從INITIALIZED變化到CREATED時,就會發出ON_CREATE事件。
所以,弄懂Lifecycle,其實也就是須要弄懂兩件事:
ok,帶着這兩個問題,咱們開始看源碼:
直接ctrl+左鍵跟進源碼,因爲AppCompatActivity繼承自SupportActivity,咱們發現,AppCompatActivity.getLifecycle(),最終定位在了SupportActivity.getLifecycle()方法中
public class SupportActivity extends Activity implements LifecycleOwner { ...... private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this); } @Override public Lifecycle getLifecycle() { return mLifecycleRegistry; } ...... }
不難看到:
字面意思:生命週期登記處
這個類是Lifecycle中最重要的一個類,它是Lifecycle的子類,起着添加觀察者,響應生命週期事件,分發生命週期事件的做用
public class LifecycleRegistry extends Lifecycle { // LifecycleObserver Map,每個Observer都有一個State private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>(); // 當前的狀態 private State mState; // 生命週期擁有者,上述的SupportActivity繼承了LifecycleOwner private final WeakReference<LifecycleOwner> mLifecycleOwner; public LifecycleRegistry(@NonNull LifecycleOwner provider) { mLifecycleOwner = new WeakReference<>(provider); mState = INITIALIZED; } /** * 添加LifecycleObserver觀察者,並將以前的狀態分發給這個Observer,例如咱們在onResume以後註冊這個Observer, * 該Observer依然能收到ON_CREATE事件 */ public void addObserver(@NonNull LifecycleObserver observer) { State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED; ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver); ...... // 例如:Observer初始狀態是INITIALIZED,當前狀態是RESUMED,須要將INITIALIZED到RESUMED之間的 // 全部事件分發給Observer // while ((statefulObserver.mState.compareTo(targetState) < 0 && mObserverMap.contains(observer))) { pushParentState(statefulObserver.mState); statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState)); popParentState(); targetState = calculateTargetState(observer); } ...... } /** * 處理生命週期事件 */ public void handleLifecycleEvent(@NonNull Lifecycle.Event event) { State next = getStateAfter(event); moveToState(next); } /** * 改變狀態 */ private void moveToState(State next) { if (mState == next) { return; } mState = next; ...... sync(); ...... } /** * 同步Observer狀態,並分發事件 */ private void sync() { LifecycleOwner lfecycleOwner = mLifecycleOwner.get(); if (lifecycleOwner == null) { Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch " + "new events from it."); return; } while (!isSynced()) { mNewEventOccurred = false; // State中,狀態值是從DESTROYED-INITIALIZED-CREATED-STARTED-RESUMED增大 // 若是當前狀態值 < Observer狀態值,須要通知Observer減少狀態值,直到等於當前狀態值 if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) { backwardPass(lifecycleOwner); } Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest(); // 若是當前狀態值 > Observer狀態值,須要通知Observer增大狀態值,直到等於當前狀態值 if (!mNewEventOccurred && newest != null && mState.compareTo(newest.getValue().mState) > 0) { forwardPass(lifecycleOwner); } } mNewEventOccurred = false; } /** * 向前傳遞事件,對應圖中的INITIALIZED -> RESUMED * 增長Observer的狀態值,直到狀態值等於當前狀態值 */ private void forwardPass(LifecycleOwner lifecycleOwner) { Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator = mObserverMap.iteratorWithAdditions(); while (ascendingIterator.hasNext() && !mNewEventOccurred) { Entry<LifecycleObserver, ObserverWithState> 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(); } } } /** * 向後傳遞事件,對應圖中的RESUMED -> DESTROYED * 減少Observer的狀態值,直到狀態值等於當前狀態值 */ private void backwardPass(LifecycleOwner lifecycleOwner) { Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator = mObserverMap.descendingIterator(); while (descendingIterator.hasNext() && !mNewEventOccurred) { Entry<LifecycleObserver, ObserverWithState> 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(); } } } }
咱們再看看新版AppCompatActivity是如何將事件分發給LifecycleRegistry的,還記得SupportActivity中有這麼一段邏輯嗎:
public class SupportActivity extends Activity implements LifecycleOwner { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this); } }
咱們看看ReportFragment是什麼
public class ReportFragment extends Fragment { public static void injectIfNeededIn(Activity activity) { 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 onStart() { super.onStart(); dispatchStart(mProcessListener); dispatch(Lifecycle.Event.ON_START); } // ...... 其餘生命週期也是一樣調用了dispatch(Lifecycle.Event.xxx)分發事件 @Override public void onPause() { super.onPause(); dispatch(Lifecycle.Event.ON_PAUSE); } 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); } } } }
能夠看到,SupportActivity添加了一個沒有頁面的ReportFragment,在ReportFragment的生命週期函數中,調用了LifecycleRegistry.handleLifecycleEvent()方法來分發生命週期事件。用一張圖總結一下就是:
AppCompatActivity中添加了一個ReportFragment,其生命週期變化時,調用LifecycleRegistry.handleLifecycleEvent()方法通知LifecycleRegistry改變狀態,LifecycleRegistry內部調用moveToState()改變狀態,並調用每一個LifecycleObserver.onStateChange()方法通知生命週期變化。
爲何不直接在SupportActivity的生命週期函數中給Lifecycle分發生命週期事件,而是要加一個Fragment呢?
由於不是全部的頁面都繼承AppCompatActivity,爲了兼容非AppCompatActivity,因此封裝一個一樣具備生命週期的Fragment來給Lifecycle分發生命週期事件。
這裏咱們直接使用AndroidStudio強大的搜索功能,alt+F7搜索ReportFragment的調用者,咱們發現:除了SupportActivity之外,還有兩個地方使用到了ReportFragment:LifecycleDispatcher和ProcessLifecycleOwner
字面意思:生命週期分發者
class LifecycleDispatcher { static void init(Context context) { ((Application) context.getApplicationContext()) .registerActivityLifecycleCallbacks(new DispatcherActivityCallback()); } /** * 給全部子Fragment設置State */ private static void markState(FragmentManager manager, State state) { Collection<Fragment> fragments = manager.getFragments(); if (fragments == null) { return; } for (Fragment fragment : fragments) { if (fragment == null) { continue; } markStateIn(fragment, state); if (fragment.isAdded()) { markState(fragment.getChildFragmentManager(), state); } } } private static void markStateIn(Object object, State state) { if (object instanceof LifecycleRegistryOwner) { LifecycleRegistry registry = ((LifecycleRegistryOwner) object).getLifecycle(); registry.markState(state); } } // 經過註冊Application.registerActivityLifecycleCallbacks來獲取Activity的生命週期回調 static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { if (activity instanceof FragmentActivity) { ((FragmentActivity) activity).getSupportFragmentManager() .registerFragmentLifecycleCallbacks(mFragmentCallback, true); } // 給每一個Activity添加ReportFragment ReportFragment.injectIfNeededIn(activity); } @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); } } } }
能夠看到LifecycleDispatcher是經過註冊Application.registerActivityLifecycleCallbacks來監聽Activity的生命週期回調的。
字面意思:線程生命週期擁有者
public class ProcessLifecycleOwner implements LifecycleOwner { public static LifecycleOwner get() { return sInstance; } static void init(Context context) { sInstance.attach(context); } 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); } } private ActivityInitializationListener mInitializationListener = new ActivityInitializationListener() { @Override public void onCreate() {} @Override public void onStart() { activityStarted(); } @Override public void onResume() { activityResumed(); } }; 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) { ReportFragment.get(activity).setProcessListener(mInitializationListener); } @Override public void onActivityPaused(Activity activity) { activityPaused(); } @Override public void onActivityStopped(Activity activity) { activityStopped(); } }); } }
根據官方註釋,咱們能夠了解到:
那麼問題又來了,ProcessLifecycleOwner和LifecycleDispatcher兩個類是在哪裏初始化呢?
從源碼中咱們看到,他們的入口都是init(Context),繼續搜索源碼,咱們發現:
public class ProcessLifecycleOwnerInitializer extends ContentProvider { @Override public boolean onCreate() { LifecycleDispatcher.init(getContext()); ProcessLifecycleOwner.init(getContext()); return true; } // ...... } AndroidManifest.xml <manifest xmlns:android="http://schemas.android.com/apk/res/android"> ...... <provider android:name="android.arch.lifecycle.ProcessLifecycleOwnerInitializer" android:authorities="me.baron.achitecturelearning.lifecycle-trojan" android:exported="false" android:multiprocess="true" /> </manifest>
瞭然,Lifecycle自動在咱們的AndroidManifest.xml中添加了一個ContentProvider,用於初始化ProcessLifecycleOwner和LifecycleDispatcher,這麼作的好處是,不須要咱們在Application中顯示調用,不須要咱們寫一行代碼。
回到咱們最初的兩個問題:
在Activity中添加一個ReportFragment(若是你的Activity繼承AppCompatActivity,會在父類的onCreate()中添加ReportFragment,不然由LifecycleDispatcher添加),在ReportFragment生命週期函數中調用LifecycleRegistry.handleLifecycleEvent()方法改變State。
LifecycleRegistry在收到handleLifecycleEvent()後,內部調用moveToState()方法,改變State值,每一次State值改變,都會調用LifecycleObserver.onStateChanged()方法將Event分發到LifecycleObserver
最後,但願每一個單身的程序員,都能找到屬於本身的她,注入你的生命週期
喜歡這篇文章的話,記得給我一個當心心哦
做者:XBaron 連接:https://www.jianshu.com/p/2c9bcbf092bc 來源:簡書 簡書著做權歸做者全部,任何形式的轉載都請聯繫做者得到受權並註明出處。