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

刺目啊1199發表於2018-12-27

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

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

下面大量原始碼,請耐心點看~

什麼是Lifecycle?

Lifecycle 元件指的是 android.arch.lifecycle 包下提供的各種類與介面,可以讓開發者構建能感知其他元件(主要指Activity 、Fragment)生命週期(lifecycle-aware)的類。

為什麼要引進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介面:

public interface IPresent {

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

然後在自定義的Present中繼承IPresent介面:

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。

  • 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是怎樣實現感知生命週期進而通知觀察者的功能的呢?

進入原始碼分析了,前方大量眼花繚亂的程式碼~~~

                           Android 官方架構元件(一)——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);
    }
}複製程式碼

這三個方法,可以總結為下面這樣一張圖:Android 官方架構元件(一)——Lifecycle

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的分析我們在這裡就到此為止了,最後附上幅流程圖,幫助理解並記憶:

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

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

相關文章