Lifecycle用法與解析

Android Architecture Component -- Lifecycle 淺析

LifecycleAndroid Architecture Components 的一個組件咏花,用于將系統(tǒng)組件(Activity、Fragment等等)的生命周期分離到 Lifecycle 類,Lifecycle 允許其他類作為觀察者,觀察組件生命周期的變化禾蚕。

public class LifecycleObserverDemo implements LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    void onAny(LifecycleOwner owner, Lifecycle.Event event) {
        System.out.println("onAny:" + event.name());
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void onCreate() {
        System.out.println("onCreate");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void onDestroy() {
        System.out.println("onDestroy");
    }
}

然后在 LifecycleRegistryOwner 比如 LifecycleActivity 加入這么一行代碼:

    getLifecycle().addObserver(new LifecycleObserverDemo());

然后邑退?然后就沒了,運行起來可以看到 LifecycleActivity 的生命周期發(fā)生變化時勉失,LifecycleObserverDemo 總能得到通知。而 LifecycleActivity 只有寥寥幾行代碼原探,并沒有覆蓋任何回調(diào)方法乱凿。那么 Lifecycle 是怎么做到的顽素,是不是有點黑魔法的感覺?

代碼解析

FragmentActivity繼承自SupportActivity

ReportFragment

ReportFragment的主要作用是:

  1. 生命周期中分發(fā)各個Lifecycle.Event, 到FragmentActivity
    dispatch(Lifecycle.Event.ON_CREATE);

在SupportActivity.onCreate中加入ReportFragment

    @Override
    @SuppressWarnings("RestrictedApi")
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
    }

.......

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dispatchCreate(mProcessListener);
        dispatch(Lifecycle.Event.ON_CREATE);//Event.ON_CREATE是在onActivityCreated之后才發(fā)送的徒蟆,其他還是在生命周期中發(fā)送
    }

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


注意RecordFragment控制的是FragmentActivity的生命周期胁出,對于其中的其他的Fragment,在Fragment中有mLifecycleRegistry變量來控制段审,代碼如下:

    void performCreate(Bundle savedInstanceState) {
        if (mChildFragmentManager != null) {
            mChildFragmentManager.noteStateNotSaved();
        }
        mState = CREATED;
        mCalled = false;
        onCreate(savedInstanceState);
        mIsCreated = true;
        if (!mCalled) {
            throw new SuperNotCalledException("Fragment " + this
                    + " did not call through to super.onCreate()");
        }
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
    }

addObserver, 注冊

LifecycleRegistry.java 重點類全蝶,Observer管理,event關(guān)于與分發(fā)

    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); //反射出observer中的注解為@OnLifecycleEvent的方法寺枉,并初始化Observer的狀態(tài)INITIALIZED. 整個反射的過程抑淫,請查看ReflectiveGenericLifecycleObserver,ClassesInfoCache.createInfo
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

        if (previous != null) {
            return;
        }
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            // it is null we should be destroyed. Fallback quickly
            return;
        }

        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
        State targetState = calculateTargetState(observer);
        mAddingObserverCounter++;
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) {
            pushParentState(statefulObserver.mState);
            statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
            popParentState();
            // mState / subling may have been changed recalculate
            targetState = calculateTargetState(observer);
        }

        if (!isReentrance) {
            // we do sync only on the top level.
            sync();
        }
        mAddingObserverCounter--;
    }


.........

 /**
     * 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) {
        State next = getStateAfter(event);
        moveToState(next);
    }

...........


ObserverWithState.java姥闪,Observer和state組成的類始苇,在LifecycleRegistry中會調(diào)用observer.dispatchEvent

void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }

ClassInfoCache.java CallbackInfo,通過反射獲取event和method筐喳,并建立緩存催式,最終會根據(jù)傳進(jìn)來的event,調(diào)用對應(yīng)的方法避归。

  @SuppressWarnings("WeakerAccess")
    static class CallbackInfo {
        final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;
        final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;

        CallbackInfo(Map<MethodReference, Lifecycle.Event> handlerToEvent) {
            mHandlerToEvent = handlerToEvent;
            mEventToHandlers = new HashMap<>();
            for (Map.Entry<MethodReference, Lifecycle.Event> entry : handlerToEvent.entrySet()) {
                Lifecycle.Event event = entry.getValue();
                List<MethodReference> methodReferences = mEventToHandlers.get(event);
                if (methodReferences == null) {
                    methodReferences = new ArrayList<>();
                    mEventToHandlers.put(event, methodReferences);
                }
                methodReferences.add(entry.getKey());
            }
        }

        @SuppressWarnings("ConstantConditions")
        void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
            invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
            invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
                    target);
        }

        private static void invokeMethodsForEvent(List<MethodReference> handlers,
                LifecycleOwner source, Lifecycle.Event event, Object mWrapped) {
            if (handlers != null) {
                for (int i = handlers.size() - 1; i >= 0; i--) {
                    handlers.get(i).invokeCallback(source, event, mWrapped);
                }
            }
        }
    }

//MethodReference
 void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
            //noinspection TryWithIdenticalCatches
            try {
                switch (mCallType) {
                    case CALL_TYPE_NO_ARG:
                        mMethod.invoke(target);
                        break;
                    case CALL_TYPE_PROVIDER:
                        mMethod.invoke(target, source);
                        break;
                    case CALL_TYPE_PROVIDER_WITH_EVENT:
                        mMethod.invoke(target, source, event);
                        break;
                }
            } catch (InvocationTargetException e) {
                throw new RuntimeException("Failed to call observer method", e.getCause());
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蓄氧,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子槐脏,更是在濱河造成了極大的恐慌喉童,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,378評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件顿天,死亡現(xiàn)場離奇詭異堂氯,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)牌废,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,356評論 2 382
  • 文/潘曉璐 我一進(jìn)店門咽白,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人鸟缕,你說我怎么就攤上這事晶框。” “怎么了懂从?”我有些...
    開封第一講書人閱讀 152,702評論 0 342
  • 文/不壞的土叔 我叫張陵授段,是天一觀的道長。 經(jīng)常有香客問我番甩,道長侵贵,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,259評論 1 279
  • 正文 為了忘掉前任缘薛,我火速辦了婚禮窍育,結(jié)果婚禮上卡睦,老公的妹妹穿的比我還像新娘。我一直安慰自己漱抓,他們只是感情好表锻,可當(dāng)我...
    茶點故事閱讀 64,263評論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著乞娄,像睡著了一般浩嫌。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上补胚,一...
    開封第一講書人閱讀 49,036評論 1 285
  • 那天,我揣著相機(jī)與錄音追迟,去河邊找鬼溶其。 笑死,一個胖子當(dāng)著我的面吹牛敦间,可吹牛的內(nèi)容都是我干的瓶逃。 我是一名探鬼主播,決...
    沈念sama閱讀 38,349評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼廓块,長吁一口氣:“原來是場噩夢啊……” “哼厢绝!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起带猴,我...
    開封第一講書人閱讀 36,979評論 0 259
  • 序言:老撾萬榮一對情侶失蹤昔汉,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后拴清,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體靶病,經(jīng)...
    沈念sama閱讀 43,469評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,938評論 2 323
  • 正文 我和宋清朗相戀三年口予,在試婚紗的時候發(fā)現(xiàn)自己被綠了娄周。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,059評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡沪停,死狀恐怖煤辨,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情木张,我是刑警寧澤众辨,帶...
    沈念sama閱讀 33,703評論 4 323
  • 正文 年R本政府宣布,位于F島的核電站舷礼,受9級特大地震影響泻轰,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜且轨,卻給世界環(huán)境...
    茶點故事閱讀 39,257評論 3 307
  • 文/蒙蒙 一浮声、第九天 我趴在偏房一處隱蔽的房頂上張望虚婿。 院中可真熱鬧,春花似錦泳挥、人聲如沸然痊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,262評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽剧浸。三九已至,卻和暖如春矗钟,著一層夾襖步出監(jiān)牢的瞬間唆香,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工吨艇, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留躬它,地道東北人。 一個月前我還...
    沈念sama閱讀 45,501評論 2 354
  • 正文 我出身青樓东涡,卻偏偏與公主長得像冯吓,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子疮跑,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,792評論 2 345

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