jetpack lifecycle源碼學(xué)習(xí)

開(kāi)發(fā)中掸刊,在Activity或者fragment的各個(gè)生命周期階段琢蛤,可能未對(duì)資源進(jìn)行正確操作導(dǎo)致一些問(wèn)題害捕,從而導(dǎo)致內(nèi)存泄露甚至引發(fā)Crash鹰晨。
在mvp時(shí)代墨叛,我們會(huì)在P層定義一些接口止毕,在組件回調(diào)生命周期函數(shù)時(shí)調(diào)用接口方法,在這些方法中進(jìn)行資源釋放或者取消一些操作的處理漠趁。lifecycle就是為了解決這個(gè)問(wèn)題出現(xiàn)的扁凛,可以讓一些組件擁有生命周期感知的能力。lifecycle已經(jīng)成為android的基礎(chǔ)組件闯传。
在Activity的父類ComponentActivity中谨朝,做了這些操作。
在該父類Activity的onCreate中甥绿,谷歌使用了一個(gè)空布局的Fragment依附于Activity字币,而后這個(gè)fragment組件是可以感知到activity的一些生命周期的,為什么要用fragment呢妹窖?是因?yàn)閘ifecycle是從api29開(kāi)始增加的,28以及之前都是使用的support庫(kù)收叶,也沒(méi)有ComponentActivity骄呼。因此為了兼容低版本,谷歌想到了這么一個(gè)合適的方法判没。從源碼中可以看出相關(guān)的版本判斷蜓萄。大于28的版本,直接使用LifecycleCallbacks注冊(cè)接口澄峰。

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        // Restore the Saved State first so that it is available to
        // OnContextAvailableListener instances
        mSavedStateRegistryController.performRestore(savedInstanceState);
        mContextAwareHelper.dispatchOnContextAvailable(this);
        super.onCreate(savedInstanceState);
        mActivityResultRegistry.onRestoreInstanceState(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
        if (mContentLayoutId != 0) {
            setContentView(mContentLayoutId);
        }
    }
    public static void injectIfNeededIn(Activity activity) {
        if (Build.VERSION.SDK_INT >= 29) {
            // On API 29+, we can register for the correct Lifecycle callbacks directly
            LifecycleCallbacks.registerIn(activity);
        }
        // Prior to API 29 and to maintain compatibility with older versions of
        // ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and
        // need to support activities that don't extend from FragmentActivity from support lib),
        // use a framework fragment to get the correct timing of Lifecycle events
        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();
        }
    }

在ComponentActivity中會(huì)創(chuàng)建一個(gè)mLifecycleRegistry對(duì)象嫉沽,會(huì)在getLifecycle()方法中返回該對(duì)象。在依附的空布局fragment的生命周期函數(shù)中俏竞,會(huì)調(diào)用dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event)绸硕,event即為生命周期的狀態(tài)。

 @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);
    }

該函數(shù)會(huì)判斷Activity的類型魂毁,如果為lifecycleowner玻佩,則會(huì)調(diào)用到一個(gè)getLifecycle(),其實(shí)就是上面說(shuō)的mLifecycleRegistry,LifecycleRegistry.handleLifecycleEvent(event)席楚,由于ComponentActivity實(shí)現(xiàn)了lifecycleOwner接口咬崔,則肯定滿足該條件,另外一個(gè)判斷是為了兼容其他情況烦秩。

    @SuppressWarnings("deprecation")
    static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
        if (activity instanceof LifecycleRegistryOwner) {
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
            return;
        }

        if (activity instanceof LifecycleOwner) {
          //getLifecycle()返回的就是在ComponentActivity中的
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }
/**
     * Sets the current state and notifies the observers.
     * <p>
     * Note that if the {@code currentState} is the same state as the last call to this method,
     * calling this method has no effect.
     *
     * @param event The event that was received
     */
    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        enforceMainThreadIfNeeded("handleLifecycleEvent");
        moveToState(event.getTargetState());
    }

    private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        sync();
        mHandlingEvent = false;
    }

    private boolean isSynced() {
        if (mObserverMap.size() == 0) {
            return true;
        }
        State eldestObserverState = mObserverMap.eldest().getValue().mState;
        State newestObserverState = mObserverMap.newest().getValue().mState;
        return eldestObserverState == newestObserverState && mState == newestObserverState;
    }
  /**
         * Returns the new {@link Lifecycle.State} of a {@link Lifecycle} that just reported
         * this {@link Lifecycle.Event}.
         *
         * Throws {@link IllegalArgumentException} if called on {@link #ON_ANY}, as it is a special
         * value used by {@link OnLifecycleEvent} and not a real lifecycle event.
         *
         * @return the state that will result from this event
         */
        @NonNull
        public State getTargetState() {
            switch (this) {
                case ON_CREATE:
                case ON_STOP:
                    return State.CREATED;
                case ON_START:
                case ON_PAUSE:
                    return State.STARTED;
                case ON_RESUME:
                    return State.RESUMED;
                case ON_DESTROY:
                    return State.DESTROYED;
                case ON_ANY:
                    break;
            }
            throw new IllegalArgumentException(this + " has no target state");
        }

該函數(shù)里面有一個(gè)比較有趣的狀態(tài)機(jī)制垮斯。event.getTargetState(),我們平時(shí)開(kāi)發(fā)能接觸到的基本都是onCreate onStart這種回調(diào)函數(shù)只祠,在谷歌的設(shè)計(jì)里兜蠕,這些回調(diào)函數(shù)是屬于事件,相對(duì)應(yīng)的 組件還會(huì)有一些狀態(tài)抛寝。這些狀態(tài)我們實(shí)際開(kāi)發(fā)中不太能接觸到牺氨。說(shuō)回這個(gè)狀態(tài)機(jī)制狡耻,核心是事件驅(qū)動(dòng)狀態(tài)。當(dāng)調(diào)用了onCreate之后猴凹,組件狀態(tài)就由INITALIZED走向Created夷狰,當(dāng)調(diào)用了onStart之后,組件就從created走向started郊霎,當(dāng)調(diào)用onResume沼头,就從started變?yōu)閞esumed。這是事件的正向流動(dòng)书劝,如果用戶返回關(guān)閉頁(yè)面或者將app放到后臺(tái)进倍,事件就會(huì)回流,先調(diào)用onPause购对,resumed狀態(tài)會(huì)變?yōu)閟tarted猾昆,調(diào)用onStop,就從started更改為created骡苞,然后調(diào)用onDestory垂蜗,就從created更改為Destoryed。下圖概括了一下事件的流向以及狀態(tài)的變化解幽。


微信圖片_20220831095847.png

狀態(tài)變更之后贴见,需要根據(jù)組件的狀態(tài)同步LifecycleRegistry中保存的mState狀態(tài),通過(guò)調(diào)用moveToState函數(shù)來(lái)進(jìn)行同步躲株,函數(shù)中有一個(gè)sysnc(),其中開(kāi)啟了一個(gè)死循環(huán)片部,條件為 當(dāng)前狀態(tài)與保存起來(lái)的狀態(tài)是否一致,如果不一致霜定,則同步档悠。
這里注意,不論事件是前進(jìn)或者回流望浩,都是根據(jù)State的枚舉類型進(jìn)行compareTo站粟,如果被觀察者比觀察者新,同步時(shí)狀態(tài)正向更新,前進(jìn)曾雕,就會(huì)調(diào)用Event.upFrom(observer.mState)更新?tīng)顟B(tài)奴烙,若為回流,會(huì)調(diào)用Event.downFrom(observer.mState)更新?tīng)顟B(tài)剖张,隨即調(diào)用observer的dispatchEvent(lifecycleOwner, event)切诀,這里的observer實(shí)際上就是lifecycle.addObserver( LifecycleObserver observer)傳進(jìn)來(lái)的這個(gè)observer,只不過(guò)這個(gè)需要我們自己手動(dòng)去傳入搔弄,而后調(diào)用mLifecycleRegistry的addObserver幅虑,源碼中會(huì)將這些保存在一個(gè)observerMap中,源碼如下:

 // happens only on the top of stack (never in reentrance),
    // so it doesn't have to take in account parents
    private void sync() {
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
                    + "garbage collected. It is too late to change lifecycle state.");
        }
        while (!isSynced()) {
            mNewEventOccurred = false;
            // no need to check eldest for nullability, because isSynced does it for us.
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
            Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }
private void backwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
                mObserverMap.descendingIterator();
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Map.Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                Event event = Event.downFrom(observer.mState);
                if (event == null) {
                    throw new IllegalStateException("no event down from " + observer.mState);
                }
                pushParentState(event.getTargetState());
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }
private void forwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
            Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                pushParentState(observer.mState);
                final Event event = Event.upFrom(observer.mState);
                if (event == null) {
                    throw new IllegalStateException("no event up from " + observer.mState);
                }
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }
Snipaste_2022-08-31_11-44-39.png

Snipaste_2022-08-31_11-55-07.png

那最后還有一個(gè)問(wèn)題顾犹,Activity觸發(fā)生命周期之后倒庵,是如何調(diào)用相應(yīng)的observer中的同名方法的呢褒墨,其實(shí)在backwardPass()或者forwardPass()中,最后有一個(gè)遍歷map集合擎宝,取出其中的statefulObserver郁妈,調(diào)用dispatchEvent,這個(gè)statefulObserver實(shí)際上里面包裝了咱們傳進(jìn)去的那個(gè)Observer绍申,也就是lifecycle.addObserver( LifecycleObserver observer)這里的observer噩咪,只不過(guò)api30之前可能是使用了反射的方式調(diào)用method,api30這里是用map里的對(duì)象調(diào)用的极阅。
lifecycle為liveData+ViewModel功能提供了擴(kuò)展胃碾,所以這兩個(gè)庫(kù)可以感知到生命周期,在合適的時(shí)候發(fā)送數(shù)據(jù)筋搏,這是后話仆百。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市奔脐,隨后出現(xiàn)的幾起案子俄周,更是在濱河造成了極大的恐慌,老刑警劉巖帖族,帶你破解...
    沈念sama閱讀 211,743評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件栈源,死亡現(xiàn)場(chǎng)離奇詭異挡爵,居然都是意外死亡竖般,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,296評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門(mén)茶鹃,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)涣雕,“玉大人,你說(shuō)我怎么就攤上這事闭翩≌豕” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 157,285評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵疗韵,是天一觀的道長(zhǎng)兑障。 經(jīng)常有香客問(wèn)我,道長(zhǎng)蕉汪,這世上最難降的妖魔是什么流译? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,485評(píng)論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮者疤,結(jié)果婚禮上福澡,老公的妹妹穿的比我還像新娘。我一直安慰自己驹马,他們只是感情好革砸,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,581評(píng)論 6 386
  • 文/花漫 我一把揭開(kāi)白布除秀。 她就那樣靜靜地躺著,像睡著了一般算利。 火紅的嫁衣襯著肌膚如雪册踩。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 49,821評(píng)論 1 290
  • 那天笔时,我揣著相機(jī)與錄音棍好,去河邊找鬼。 笑死允耿,一個(gè)胖子當(dāng)著我的面吹牛借笙,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播较锡,決...
    沈念sama閱讀 38,960評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼业稼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了蚂蕴?” 一聲冷哼從身側(cè)響起低散,我...
    開(kāi)封第一講書(shū)人閱讀 37,719評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎骡楼,沒(méi)想到半個(gè)月后熔号,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,186評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡鸟整,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,516評(píng)論 2 327
  • 正文 我和宋清朗相戀三年引镊,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片篮条。...
    茶點(diǎn)故事閱讀 38,650評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡弟头,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出涉茧,到底是詐尸還是另有隱情赴恨,我是刑警寧澤,帶...
    沈念sama閱讀 34,329評(píng)論 4 330
  • 正文 年R本政府宣布伴栓,位于F島的核電站伦连,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏钳垮。R本人自食惡果不足惜惑淳,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,936評(píng)論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望扔枫。 院中可真熱鬧汛聚,春花似錦、人聲如沸短荐。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,757評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至痕貌,卻和暖如春风罩,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背舵稠。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,991評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工超升, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人哺徊。 一個(gè)月前我還...
    沈念sama閱讀 46,370評(píng)論 2 360
  • 正文 我出身青樓室琢,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親落追。 傳聞我的和親對(duì)象是個(gè)殘疾皇子盈滴,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,527評(píng)論 2 349

推薦閱讀更多精彩內(nèi)容

  • Lifecycle 簡(jiǎn)介 Lifecycle 是一個(gè)可以感知宿主生命周期變化的組件。常見(jiàn)的宿主包括 Activit...
    wuchao226閱讀 1,417評(píng)論 0 0
  • 使用生命周期感知型組件處理生命周期 生命周期感知型組件可執(zhí)行操作來(lái)響應(yīng)另一個(gè)組件(如 Activity 和 Fra...
    有腹肌的豌豆Z閱讀 299評(píng)論 0 0
  • Q:什么是LifeCycle androidx.lifecycle[https://developer.andro...
    施洛辛閱讀 389評(píng)論 0 1
  • 介紹 Lifecycle 它是 Jetpack 組件庫(kù)的的核心基礎(chǔ) 轿钠,具備宿主生命周期感知能力的組件巢钓。它能持有組件...
    明朗__閱讀 481評(píng)論 0 1
  • 前言 Jetpack的眾多組件都依賴于Lifecycle,例如LiveData疗垛、ViewModel等症汹,可見(jiàn)Life...
    h2coder閱讀 320評(píng)論 0 2