Android 官方架構組件(一)——Lifecycle

初到掘金,人生地不熟,喜歡的朋友,點個贊鼓勵下新手唄~
java

參考文章: 
https://mp.weixin.qq.com/s/VJif0D5PlrmyA1_emV-k0g 
https://mp.weixin.qq.com/s/jU-UHkRbiruBq6BcNOjr5w

下面大量源碼,請耐心點看~
android

什麼是Lifecycle?

Lifecycle 組件指的是 android.arch.lifecycle 包下提供的各類類與接口,可讓開發者構建能感知其餘組件(主要指Activity 、Fragment)生命週期(lifecycle-aware)的類。web

爲何要引進Lifecycle?

前面說了,Lifecycle可以讓開發者構建能感知其餘組件(主要指Activity 、Fragment)生命週期(lifecycle-aware)的類。劃重點,讓開發者構建能感知其餘組件(主要指Activity 、Fragment)生命週期(lifecycle-aware)的類。在android開發的過程當中,咱們經常須要讓一些操做可以感知Activity/Fragment的生命週期,從而實如今活動狀態下容許操做,而在銷燬狀態下須要自動禁止操做,釋放資源,防止內存泄露。例如大名鼎鼎的圖片加載框架Glide在Acticiy/Fragment處於前臺的時候加載圖片,而在不可見的狀態下中止圖片的加載,又例如咱們但願RxJava的Disposable可以在Activity/Fragment銷燬是自動dispose。Lifecycle的出現,讓開發者們可以輕易地實現上述的功能。安全

一個用Lifecycle改造的MVP例子

好比咱們如今須要實現這樣一個功能:監聽某個 Activity 生命週期的變化,在生命週期改變的時候打印日誌。
  • 通常作法構造回調的方式

先定義基礎IPresent接口:
session

public interface IPresent {

    void onCreate();
    void onStart();
    void onResume();
    void onPause();
    void onStop();
    void onDestory();
}複製代碼

而後在自定義的Present中繼承IPresent接口:app

public class MyPresent implements IPresent {

    private String TAG = "tag";

    @Override
    public void onCreate() {
        LogUtil.i(TAG, "onCreate");
    }

    @Override
    public void onStart() {
        LogUtil.i(TAG, "onStart");
    }

    @Override
    public void onResume() {
        LogUtil.i(TAG, "onResume");
    }

    @Override
    public void onPause() {
        LogUtil.i(TAG, "onPause");
    }

    @Override
    public void onStop() {
        LogUtil.i(TAG, "onStop");
    }

    @Override
    public void onDestory() {
        LogUtil.i(TAG, "onDestory");
    }複製代碼

最後在Activity依次調用回調方法分發事件:框架

public class MyActivity extends AppCompatActivity {

    protected MyPresent myPresent;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        myPresent = new MyPresent();
        myPresent.onCreate();
    }

    @Override
    protected void onStart() {
        super.onStart();
        myPresent.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        myPresent.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        myPresent.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        myPresent.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myPresent.onDestory();
    }
}複製代碼

經過這麼一個簡單的例子,咱們能夠看出,實現流程雖然很簡單,可是代碼實現繁瑣,不夠靈活,且代碼侵入性太強。該例子只是展現了Present監聽Activity生命週期,若是說還有類1,類2,類3......想要監聽Activity的生命週期,那麼就要在Activity的回調中添加對類1,類2,類3.....的回調。這就引發了一個思考,咱們是否可以實現Activity在生命週期發生變化時主動通知需求方的功能呢?能夠的,答案就是Lifecycle。ide

  • Lifecycle實現Present

先實現MyPresent,同時在每個方法實現上增長@OnLifecycleEvent(Lifecycle.Event.XXXX)註解,OnLifecycleEvent對應了Activity的生命週期方法:函數

public class MyPresent implements IPresent, LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    @Override
    public void onCreate() {
        LogUtil.i(TAG, "onCreate");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    @Override
    public void onStart() {
        LogUtil.i(TAG, "onStart");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    @Override
    public void onResume() {
        LogUtil.i(TAG, "onResume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    @Override
    public void onPause() {
        LogUtil.i(TAG, "onPause");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    @Override
    public void onStop() {
        LogUtil.i(TAG, "onStop");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    @Override
    public void onDestory() {
        LogUtil.i(TAG, "onDestory");
    }
}複製代碼

而後在須要監聽的 Activity 中註冊:源碼分析

public class MyActivity extends AppCompatActivity {

    protected MyPresent myPresent;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        
        getLifecycle().addObserver(new MyPresent()); //添加監聽對象
    }

}複製代碼

運行以下:

com.cimu.lifecycle I/MyPresent : onCreate()
com.cimu.lifecycle I/MyPresent : onStart()
com.cimu.lifecycle I/MyPresent : onResume()
com.cimu.lifecycle I/MyPresent : onPause()
com.cimu.lifecycle I/MyPresent : onStop()
com.cimu.lifecycle I/MyPresent : onDestroy()複製代碼

是否是很簡單,咱們但願MyPresent感知監聽Activity的生命週期,只須要在Activity中調用一句getLifecycle().addObserver(new MyPresent())就能夠了。Lifecycle是怎樣實現感知生命週期進而通知觀察者的功能的呢?

進入源碼分析了,前方大量眼花繚亂的代碼~~~

                           


Lifecycle源碼分析

首先須要知道三個關鍵的東西:

  • LifecycleOwner:生命週期的事件分發者,在 Activity/Fragment 他們的生命週期發生變化的時發出相應的 Event 給LifecycleRegistry。
  • LifecycleObserver:生命週期的觀察者,經過註解將處理函數與但願監聽的Event綁定,當相應的Event發生時,LifecycleRegistry會通知相應的函數進行處理。
  • LifecycleRegistry:控制中心。它負責控制state的轉換、接受分發event事件。

LifeCycle的源碼分析,咱們分爲兩個步驟來分析:

  • 註冊/註銷監聽流程
  • 生命週期分發流程


註冊/註銷監聽流程源碼分析

從上面的MVP例子,咱們已經知道,註冊只須要調用getLifecycle().addObserver(observer)便可,那麼addObserver就能夠做爲源碼分析的入口。

經過追蹤,咱們發現getLifecycle返回的是SupportActivity中的mLifecycleRegistry,類型爲LifecycleRegistry:

public class SupportActivity extends Activity implements LifecycleOwner {

    ......

    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap
                                                             = new FastSafeIterableMap<>();
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    ......

    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

    ......
}複製代碼

那麼addObserver其實是調用了LifecycleRegistry的addObserver方法,咱們來看一下這個方法:

@Override
public void addObserver(@NonNull LifecycleObserver observer) {
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;

    //將傳進來的監聽者observer封裝成一個ObserverWithState
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    //將封裝好的ObserverWithState存入集合中
    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();
        // 咱們 dispatch 了一個事件給觀察者,在回調觀察者代碼的時候,觀察者可能會
        // 修改咱們的狀態
        // mState / subling may have been changed recalculate
        targetState = calculateTargetState(observer);
    }

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

關於註冊流程,上面咱們重點關注封裝了observer的ObserverWithState:

static class ObserverWithState {
    State mState;
    GenericLifecycleObserver mLifecycleObserver;

    ObserverWithState(LifecycleObserver observer, State initialState) {
        //getCallback()經過不一樣的類型的observer返回不一樣GenericLifecycleObserver實現類
        mLifecycleObserver = Lifecycling.getCallback(observer);
        mState = initialState;
    }

    //生命週期event的分發,最終會調用到這個方法,這個方法中在調用了GenericLifecycleObserver的
    //的onStateChanged方法
    void dispatchEvent(LifecycleOwner owner, Event event) {
        State newState = getStateAfter(event);
        mState = min(mState, newState);
        mLifecycleObserver.onStateChanged(owner, event);
        mState = newState;
    }
}複製代碼
public interface GenericLifecycleObserver extends LifecycleObserver {
    void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
}複製代碼

ObserverWithState的構造方法調用了Lifecycling.getCallback()將傳入的observer進行解析,生成了對接口類GenericLifecycleObserver的具體實現返回,而且在具體實現類中重寫了onStateChanged方法,在onStateChanged實現了生命週期的分發。當Activity/Fragment的生命週期發生變化時,會遍歷LifecycleRegistry中的mObserverMap集合,取出其中的ObserverWithState節點,調用它的onStateChanged方法,而在ObserverWithState的onStateChanged的方法中又調用了實現了具體生命週期分發的GenericLifecycleObserver.onStateChanged方法。

在分析Lifecycling.getCallback()方法以前,咱們先來看一下Lifecycle使用的三種基本使用方式:

  • 第一種使用方式。使用@onLifecycleEvent註解。註解處理器會將該註解解析並動態生成GeneratedAdapter代碼,這個GeneratedAdapter會把對應的 Lifecycle.Event 封裝爲方法調用。最終經過GenericLifecycleObserver的onStateChanged方法調用生成的GeneratedAdapter的callMechods方法進行事件分發(結合下面例子理解)

public class MyLifeCycleObserver implements LifeCycleObserver {

    @onLifecycleEvent(LifeCycle.Event.ON_CREATE)
    public onCreate(LifeCycleOwner owner) {
         //doSomething
    }
    
    @onLifecycleEvent(LifeCycle.Event.ON_DESTROY)
    public onDestroy(LifeCycleOwner owner) {
        //doSomething
    }
}

public class MainActivity extends AppCompatActivity {

    @override
    public void onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getLifecycle().addObserver(new MyLifeCycleObserver());
    }
}
複製代碼

上述的例子中的MyLifeCycleObserver將會在編譯時,生成GeneratedAdapter代碼以下:

public class MyLifeCycleObserver_LifecycleAdapter implements GeneratedAdapter {

    final MyLifeCycleObserver mReceiver;

    MyLifeCycleObserver_LifecycleAdapter(MyLifeCycleObserver receiver) {
        //mReceiver就是咱們開發者傳入的MyLifeCycleObserver 
        this.mReceiver = receiver;
    }

    //callMechod方法會被GenericLifecycleObserver的onStateChanged方法調用,用以分發生命週期
    @Override
    public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny, MethodCallsLogger logger) {
        boolean hasLogger = logger != null;
        if (onAny) {
            return;
        }

        //若是生命週期事件是ON_CREATE,那麼調用MyLifeCycleObserver的onCreate方法
        if (event == Lifecycle.Event.ON_CREATE) {
            if (!hasLogger || logger.approveCall("onCreate", 2)) {
                mReceiver.onCreate(owner);
            }
            return;
        }

        //若是生命週期事件是ON_DESTROY,那麼調用MyLifeCycleObserver的onDestroy方法
        if (event == Lifecycle.Event.ON_DESTROY) {
            if (!hasLogger || logger.approveCall("onDestroy", 2)) {
                mReceiver.onDestroy(owner);
            }
            return;
        }
    }
}複製代碼
  • 第二種使用方式。直接繼承GenericLifecycleObserver,並實現onStateChange方法

public class MyLifeCycleObserver extends GenericLifeCycleObserver {
    
    @override
    void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        if(event == LifeCycleEvent.Event.ON_CREATE) {
            //dosomething
        } else if(event == LifeCycleEvent.Event.ON_DESTROY) {
            //doSomething
        }    
    }
}

public class MainActivity extends AppCompatActivity {

    @override
    public void onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getLifecycle().addObserver(new MyLifeCycleObserver());
    }
}複製代碼
  • 第三種使用方式。繼承DefaultLifecycleObserver接口(DefaultLifecycleObserver又繼承自FullLifecycleObserver接口),並實現FullLifecycleObserver接口的onCreate、onStart、onResume、onPause、onStop、onDestroy等對應各自生命週期的方法
class MyLifycycleObserver implements DefaultLifecycleObserver {

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        //doSomething
    }

    ......

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        //doSomething 
    }
}

public class MainActivity extends AppCompatActivity {

    @override
    public void onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getLifecycle().addObserver(new MyLifeCycleObserver());
    }
}
複製代碼

上面咱們學習了使用Lifecycle的三種基本方法,下面咱們簡單看看Lifecycling.getCallback()方法是如何生成GenericLifecycleObserver具體實現類返回的:

//首先,咱們先熟悉一下resolveObserverCallbackType這個方法,這個方法在Lifecycling.getCallback()
//中被調用,getCallback中會根據它的返回值決定返回什麼類型的GenericLifecycleObserver實現類
private static int resolveObserverCallbackType(Class<?> klass) {
       
    if (klass.getCanonicalName() == null) {
        return REFLECTIVE_CALLBACK;
    }
    
    //當使用第一種方式註解時,會自動生成代碼,生成的adapter繼承了GeneratedAdapter,
    //因此返回值是GENERATED_CALLBACK
    Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
    if (constructor != null) {
        sClassToAdapters.put(klass, Collections
                .<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
        return GENERATED_CALLBACK;
    }

    //hasLifecycleMethods方法是判斷klass中是否包含了onLifecycleEvent.class註解
    //若是包含,返回REFLECTIVE_CALLBACK
    boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
    if (hasLifecycleMethods) {
        return REFLECTIVE_CALLBACK;
    }

    //遞歸調用resolveObserverCallbackType方法,遍歷klass的父類
    Class<?> superclass = klass.getSuperclass();
    List<Constructor<? extends GeneratedAdapter>> adapterConstructors = null;
    if (isLifecycleParent(superclass)) {
        if (getObserverConstructorType(superclass) == REFLECTIVE_CALLBACK) {
            return REFLECTIVE_CALLBACK;
        }
        adapterConstructors = new ArrayList<>(sClassToAdapters.get(superclass));
    }

    //遍歷而且遞歸kclass的接口
    for (Class<?> intrface : klass.getInterfaces()) {
        if (!isLifecycleParent(intrface)) {
            continue;
        }
        if (getObserverConstructorType(intrface) == REFLECTIVE_CALLBACK) {
            return REFLECTIVE_CALLBACK;
        }
        if (adapterConstructors == null) {
            adapterConstructors = new ArrayList<>();
        }
        adapterConstructors.addAll(sClassToAdapters.get(intrface));
    }
    if (adapterConstructors != null) {
        sClassToAdapters.put(klass, adapterConstructors);
        return GENERATED_CALLBACK;
    }

    return REFLECTIVE_CALLBACK;
}複製代碼
//getCallBack的參數object是咱們getLifeCycle().addObserver(observer)時傳入的監聽者observer
static GenericLifecycleObserver getCallback(Object object) {

    if (object instanceof FullLifecycleObserver) {
       //第三種使用方式,由於DefaultLifecycleObserver繼承與FullLifecycleObserver
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
    }

    if (object instanceof GenericLifecycleObserver) {
        //第二種使用方式,當咱們使用直接繼承GenericLifecycleObserver這種方法時,直接返回
        return (GenericLifecycleObserver) object;
    }

    final Class<?> klass = object.getClass();
    //第一種使用方式,當使用註解時,getObserverConstructorType的返回值是GENERATED_CALLBACK
    int type = getObserverConstructorType(klass);
    if (type == GENERATED_CALLBACK) {
        List<Constructor<? extends GeneratedAdapter>> constructors = sClassToAdapters.get(klass);
        if (constructors.size() == 1) {
            GeneratedAdapter generatedAdapter = createGeneratedAdapter(constructors.get(0), object);
            return new SingleGeneratedAdapterObserver(generatedAdapter);
        }
        GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
        for (int i = 0; i < constructors.size(); i++) {
            adapters[i] = createGeneratedAdapter(constructors.get(i), object);
        }
        return new CompositeGeneratedAdaptersObserver(adapters);
    }

    //當oberver都不符合上面幾種類型時,會直接實例化ReflectiveGenericLifecycleObserver
    //做爲替代返回(通常狀況下,是不會走到這裏的,多是爲了應對混淆機制而作的的一種安全模式)
    //在ReflectiveGenericLifecycleObserver中會找oberver中的onLifecyleEvent註解,而且將這些帶註解
    //的方法生成MethodReference並添加到List<MethodReference>中,做爲生命週期分發的調用方法
    return new ReflectiveGenericLifecycleObserver(object);
}複製代碼

好了,Lifecycling.getCallback()若是真的要詳細的分析,篇幅會很大,在這裏,咱們粗略的分析了下。你們若是想深刻了解,本身結合源碼看是最好不過的。

總結一下注冊的流程:

  1. Acitivty中調用LifecycleRegistry的addObserver,傳入一個LifecycleObserver
  2. 傳入的LifecycleObserver被封裝成一個ObserverWithState存入集合中,當生命週期發生改變的時候,就會遍歷這個ObserverWithState集合,而且調用ObserverWithState的dispatchEvent進行分發
  3. 在ObserverWithState構造方法中,調用了Lifecycling.getCallback(observer)生成了具體的 GenericLifecycleObserver對象返回。在ObserverWithState的dispatchEvent()方法中調用了GenericLifecycleObserver對象的onStateChanged方法進行事件分發


至於註銷流程就很簡單了,直接將observer從集合中remove,代碼以下:

@Override
public void removeObserver(@NonNull LifecycleObserver observer) {
    // we consciously decided not to send destruction events here in opposition to addObserver.
    // Our reasons for that:
    // 1. These events haven't yet happened at all. In contrast to events in addObservers, that
    // actually occurred but earlier.
    // 2. There are cases when removeObserver happens as a consequence of some kind of fatal
    // event. If removeObserver method sends destruction events, then a clean up routine becomes
    // more cumbersome. More specific example of that is: your LifecycleObserver listens for
    // a web connection, in the usual routine in OnStop method you report to a server that a
    // session has just ended and you close the connection. Now let's assume now that you
    // lost an internet and as a result you removed this observer. If you get destruction
    // events in removeObserver, you should have a special case in your onStop method that
    // checks if your web connection died and you shouldn't try to report anything to a server.
    mObserverMap.remove(observer);
}複製代碼


生命週期的分發流程

咱們註冊observer的時候,其實是調用了SupportActivity中的mLifecycleRegistry對象的方法,那麼咱們分析下SupportActivity的onCreate方法:

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

在onCreate中調用了ReportFragment的injectIfNeedIn方法。這個方法其實就是往Activity中添加了一個Fragment。咱們知道,Fragment是依附於Activity上的,Fragment的生命週期跟隨Activity的生命週期。既然這個ReportFragment可以感知Activity的生命週期,那麼它是否是就是負責將生命週期事件分發給LifecycleObserver的呢?

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) {
        // 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();
        }
    }

    static ReportFragment get(Activity activity) {
        return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
                REPORT_FRAGMENT_TAG);
    }

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

    void setProcessListener(ActivityInitializationListener processListener) {
        mProcessListener = processListener;
    }

    interface ActivityInitializationListener {
        void onCreate();

        void onStart();

        void onResume();
    }
}複製代碼

ReportFragment的代碼很好理解,咱們可以在代碼裏面發現Lifecycle.Event.xxx事件,而且在它的生命週期回調方法中將Lifecycle.Event.xxx事件傳給了dispatch方法,很明顯是用來分發生命週期的。在ReportFragment的dispatch方法中,調用了LifecycleRegistry的handleLifecycleEvent方法:

public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    State next = getStateAfter(event);
    moveToState(next);
}複製代碼

在分析這個方法以前,咱們先要了解Lifecycle的事件與狀態:

public abstract class Lifecycle {

    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
    }

    public enum State {
        /** * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch * any more events. For instance, for an {@link android.app.Activity}, this state is reached * <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call. */
        DESTROYED,

        /** * Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is * the state when it is constructed but has not received * {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet. */
        INITIALIZED,

        /** * Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached in two cases: * <ul> * <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call; * <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call. * </ul> */
        CREATED,

        /** * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached in two cases: * <ul> * <li>after {@link android.app.Activity#onStart() onStart} call; * <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call. * </ul> */
        STARTED,

        /** * Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached after {@link android.app.Activity#onResume() onResume} is called. */
        RESUMED;
    }
}複製代碼

Lifecycle.Event對應activity的各個聲明週期,Lifecycle.State則是Lifecycle的狀態。在LifecycleRegistry 中定義了狀態間的轉化關係:

public class LifecycleRegistry extends Lifecycle {

    static State getStateAfter(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);
    }

    private static Event downEvent(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);
    }

    private static Event upEvent(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);
    }
}複製代碼

這三個方法,能夠總結爲下面這樣一張圖:

downEvent 在圖中表示從一個狀態到他下面的那個狀態,upEvent 則是往上。

瞭解了 Lifecycle 的狀態後,咱們繼續來看 LifecycleRegistry。上面咱們知道,當Activity的生命週期發生變化後,ReportFragment會感知到,從而會調用到dispatch方法,最終調用到LifecycleRegistry的 handleLifecycleEvent方法:

public class LifecycleRegistry extends Lifecycle {

    private int mAddingObserverCounter = 0;

    private boolean mHandlingEvent = false;
    private boolean mNewEventOccurred = false;

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }

    private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        // 當咱們在 LifecycleRegistry 回調 LifecycleObserver 的時候觸發狀態變化時,
        // mHandlingEvent 爲 true;
        // 添加 observer 的時候,也可能會執行回調方法,這時候若是觸發了狀態變化,
        // 則 mAddingObserverCounter != 0
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // 不須要執行 sync。
            // 執行到這裏的狀況是:sync() -> LifecycleObserver -> moveToState()
            // 這裏直接返回後,仍是會回到 sync(),而後繼續同步狀態給 observer
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        // sync() 會把狀態的變化轉化爲生命週期事件,而後轉發給 LifecycleObserver
        sync();
        mHandlingEvent = false;
    }
}複製代碼

LifecycleRegistry 原本要作的事實際上是很簡單的,但因爲他須要執行客戶的代碼,由此引入了不少額外的複雜度。緣由是,客戶代碼並不處在咱們的控制之下,他們可能作出任何能夠作到的事。例如這裏,在回調中又觸發狀態變化。相似的狀況是,在持有鎖的時候不調用客戶代碼,這個也會讓實現變得比較複雜。

接下來咱們看 sync():

public class LifecycleRegistry extends Lifecycle {

    /** * Custom list that keeps observers and can handle removals / additions during traversal. * * 這個 Invariant 很是重要,他會影響到 sync() 的邏輯 * Invariant: at any moment of time for observer1 & observer2: * if addition_order(observer1) < addition_order(observer2), then * state(observer1) >= state(observer2), */
    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();

    private void sync() {
        LifecycleOwner lifecycleOwner = 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 是爲了在 observer 觸發狀態變化時讓 backwardPass/forwardPass()
            // 提早返回用的。咱們剛準備調他們,這裏設置爲 false 便可。
            mNewEventOccurred = false;
            // no need to check eldest for nullability, because isSynced does it for us.
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                // mObserverMap 裏的元素的狀態是非遞增排列的,也就是說,隊頭的 state 最大
                // 若是 mState 小於隊列裏最大的那個,說明有元素須要更新狀態
                // 爲了維持 mObserverMap 的 Invariant,這裏咱們須要從隊尾往前更新元素的狀態
                backwardPass(lifecycleOwner);
            }
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            // 若是 mNewEventOccurred,說明在上面調用 backwardPass() 時,客戶觸發了狀態修改
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

    // 判斷是否須要同步,若是全部的observer的狀態都已經同步完,返回 true,不然返回false
    private boolean isSynced() {
        if (mObserverMap.size() == 0) {
            return true;
        }
        //eldestObserverState是最先添加的observer,newestObserverState是最新添加的observer
        State eldestObserverState = mObserverMap.eldest().getValue().mState;
        State newestObserverState = mObserverMap.newest().getValue().mState;
        //由於咱們保證隊頭的state >= 後面的元素的state,因此只要判斷頭尾就夠了
        //若是最新的和最老的Observer的狀態不一致或者當前的狀態和最新的狀態不一致時,那麼須要進行狀態同步
        return eldestObserverState == newestObserverState && mState == newestObserverState;
    }

}複製代碼

sync() 的主要做用就是根據把 mObserverMap 裏全部元素的狀態都同步爲 mState。咱們繼續看剩下的 backwardPass/forwardPass:

public class LifecycleRegistry extends Lifecycle {

    // 這段註釋應該是這整個類裏面最難理解的了吧,至少對於我來講是這樣
    // we have to keep it for cases:
    // void onStart() {
    // // removeObserver(this),說明 this 是一個 LifecycleObserver
    // // 因此這裏說的是,咱們在回調裏執行了下面兩個操做
    // mRegistry.removeObserver(this);
    // mRegistry.add(newObserver);
    // }
    // 假定如今咱們要從 CREATED 轉到 STARTED 狀態(也就是說,mState 如今是 STARTED)。
    // 這種狀況下,只有將新的 observer 設置爲 CREATED 狀態,它的 onStart 纔會被調用
    // 爲了獲得這個 CREATED,在這裏才引入了 mParentStates。在 forwardPass 中執行
    // pushParentState(observer.mState) 時,observer.mState 就是咱們須要的 CREATED。
    // backwardPass 的狀況相似。
    // newObserver should be brought only to CREATED state during the execution of
    // this onStart method. our invariant with mObserverMap doesn't help, because parent observer
    // is no longer in the map.
    private ArrayList<State> mParentStates = new ArrayList<>();

    //第一個while循壞遍歷咱們存儲觀察者的集合,
    //第二個是要處理各個狀態通過的event
    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);
                //upEvent 返回所要經歷的event
                //例如:當前是 STARTED , 那麼他的通過的 events 就是 ON_RESUME
                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
                popParentState();
            }
        }
    }

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

    private void popParentState() {
        mParentStates.remove(mParentStates.size() - 1);
    }

    private void pushParentState(State state) {
        mParentStates.add(state);
    }
}複製代碼

提示:在看這forwardPass以及backwardPass這兩個方法時,參考上面的狀態轉換圖

  1. 假設當前集合中全部ObserverWithState元素都處於CREATED狀態。此時接着收到了一個ON_START事件,從圖能夠看出,接下來應該是要轉換到STARTED狀態。因爲STARTED大於CREATED,因此會執行forwardPass方法。forwardPass裏調用 upEvent(observer.mState),返回從CREATED往上到STARTED須要發送的事件,也就是ON_START,因而ON_START事件發送給了觀察者。
  2. 假設當前 LifecycleRegistrymState處於RESUMED狀態。而後調用addObserver方法新添加一個LifecycleObserver,該observer會被封裝成ObserverWithState存進集合中,此時這個新的ObserverWithState處於INITIALIZED狀態,因爲RESUMED大於INITIALIZED,因此會執行forwardPass方法。ObserverWithState狀態會按照 INITIALIZED -> CREATED -> STARTED -> RESUMED 這樣的順序變遷。


總結

一些我的疑問:

  • 疑點1:爲何不直接在SupportActivity的生命週期函數中給Lifecycle分發生命週期事件,而是要加一個Fragment呢?
由於不是全部的頁面都繼承AppCompatActivity,爲了兼容非AppCompatActivity,因此封裝一個一樣具備生命週期的Fragment來給Lifecycle分發生命週期事件。顯然Fragment 侵入性低。
  • 疑點2:爲何用ReportFragment分發生命週期而不直接使用ActivityLifecycleCallbacks的回調來處理Lifecycle生命週期的變化?
因爲 ActivityLifecycleCallbacks 的回調比 Fragment 和 Activity 還要早,實際上未真正執行對應的生命週期方法


Lifecycle的分析咱們在這裏就到此爲止了,最後附上幅流程圖,幫助理解並記憶:


初到掘金,人生地不熟,喜歡的朋友,點個贊鼓勵下新手唄~
相關文章
相關標籤/搜索