banner
jzman

jzman

Coding、思考、自觉。
github

Android Jetpack元件之Lifecycle篇

Lifecycle-Aware 组件是 Android Jetpack 的一部分,该组件可以感知 Activity 和 Fragment 的生命周期状态的改变,有利於生成更易組織、更輕量化、更易於維護的代碼,常用的開發方式就是在組件的對應的生命周期方法中處理相關業務邏輯,這種方式會導致不良代碼的產生以及 bug 的增加,如果使用生命周期組件則可將依賴組件的代碼移除生命周期並移入組件本身。

  1. 生命周期
  2. 生命周期源碼分析
  3. ProcessLifecycleOwner 的初始化

生命周期#

Lifecycle 是一個持有組件生命周期狀態信息的抽象類,其直接子類是 LifecycleRegistry,Activity 和 Fragment 都間接實現了 LifecycleOwner 接口,且提供了對應的 getLifecycle 方法獲取 Lifecycle 對象,獲取到的也就是 LifecycleRegistry 對象,下面是 Lifecycle 的生命周期對應狀態圖:

image

圖示中主要有兩點:Event (事件) 和 Status (狀態)。

  • Event:如 ON_CREATE、ON_START 等對應 Activity 或 Fragment 對應的生命周期方法
  • Status:在 Lifecycle 中生命周期所處的狀態,如上圖中 ON_CREATE 和 ON_STOP 的下一個狀態是 CREATED 狀態,根據圖示可以將具體的生命周期事件與狀態對應起來。

如果開發環境是 Java1.7 ,可以使用注解的方式來監聽生命周期變化,參考如下:

/**
 * Powered by jzman.
 * Created on 2018/12/8 0008.
 */
public class LifeCycleListener implements LifecycleObserver {

    private static final String TAG = LifeCycleListener.class.getSimpleName();

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private void onCreate(LifecycleOwner owner) {
        Log.i(TAG,"--onCreate-->");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private void onStart(LifecycleOwner owner) {
        Log.i(TAG,"--onStart-->");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private void onResume(LifecycleOwner owner) {
        Log.i(TAG,"--onResume-->");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    private void onPause(LifecycleOwner owner) {
        Log.i(TAG,"--onPause-->");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private void onStop(LifecycleOwner owner) {
        Log.i(TAG,"--onStop-->");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private void onDestroy(LifecycleOwner owner) {
        Log.i(TAG,"--onDestroy-->");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    private void onAny(LifecycleOwner owner, Lifecycle.Event event) {
        //onAny方法可以添加第二個參數,用來獲取當前生命周期
        //任何生命周期狀態發生變化都會觸發
        Log.i(TAG,"--onAny-->"+event.name());
    }
}

如果開發環境是 Java1.8 ,推薦使用以實現 DefaultLifecycleObserver 接口的方式來監聽生命周期的變化,首先在對應 module 的 build.gradle 文件文件中引入:

implementation "android.arch.lifecycle:common-java8:1.1.1"

然後,創建生命周期監聽器如下:

/**
 * Powered by jzman.
 * Created on 2018/12/10 0010.
 */
public class LifeCycleListener1 implements DefaultLifecycleObserver {

    private static final String TAG = LifeCycleListener.class.getSimpleName();

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        Log.i(TAG,"--onCreate-->");
    }

    @Override
    public void onStart(@NonNull LifecycleOwner owner) {
        Log.i(TAG,"--onStart-->");
    }

    @Override
    public void onResume(@NonNull LifecycleOwner owner) {
        Log.i(TAG,"--onResume-->");
    }

    @Override
    public void onPause(@NonNull LifecycleOwner owner) {
        Log.i(TAG,"--onPause-->");
    }

    @Override
    public void onStop(@NonNull LifecycleOwner owner) {
        Log.i(TAG,"--onStop-->");
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        Log.i(TAG,"--onDestroy-->");
    }
}

最後,在對應的 Activity 或 Fragment 中註冊該監聽器,參考如下:

LifeCycleListener mLifeCycleListener = new LifeCycleListener();
getLifecycle().addObserver(mLifeCycleListener);

以 LifeCycleListener 為例 Lifecycle 監聽 Activity 生命周期運行日誌如下:

//打開Activity
 --onCreate-->
--onAny-->ON_CREATE
--onStart-->
--onAny-->ON_START
--onResume-->
--onAny-->ON_RESUME
//退出Activity
--onPause-->
--onAny-->ON_PAUSE
--onStop-->
--onAny-->ON_STOP
--onDestroy-->
--onAny-->ON_DESTROY

生命周期源碼分析#

LifecycleOwner 是一個接口,表示實現該接口的類具有生命周期,如所有繼承自 AppCompatActivity 的 Activity 都間接實現了 LifecycleOwner 接口,源碼中是 ComponentActivity 實現了該接口, 實際開發中可實現 LifecycleOwner 接口將原先 Activity 或 Fragment 生命周期中執行的業務移到組件本身。

從上文中可知使用 getLifecycle () 獲取到是 Lifecycle 的具體實現類 LifecycleRegistry 對象,然後使用 addObserver 添加 LifecycleObserver 對象,也就是添加要通知的觀察者,之後才能夠在 Activity 或 Fragment 生命周期發生變化時觀察者才會被通知,那麼 Activity 的生命周期是如何被感知呢。

在 ComponentActivity 中添加了一個無界面的 Fragment 用來感知 Activity 的生命周期,源碼如下:

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSavedStateRegistryController.performRestore(savedInstanceState);
    //在Activity中添加一個Fragment
    ReportFragment.injectIfNeededIn(this);
}

injectIfNeededIn 方法會創建一個名稱為 ReportFragment 的 Fragment,當每創建一個 Activity 的時候,該 Fragment 就會被添加到對應的 Activity 中,ReportFragment 源碼如下:

public class ReportFragment extends Fragment {
    
    // 創建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();
        }
    }

    //...

    // Activity 初始化監聽器,監聽Activity的生命周期狀態
    private ActivityInitializationListener mProcessListener;

    // Activity生命周期狀態分發
    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) {
       // 查案源碼LifecycleRegistryOwner已被廢棄,留著應該是為了兼容
        Activity activity = getActivity();
        if (activity instanceof LifecycleRegistryOwner) {
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
            return;
        }
        
        // 獲取Activity中的Lifecycle
        if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                // 分發Activity生命周期狀態
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }

    void setProcessListener(ActivityInitializationListener processListener) {
        mProcessListener = processListener;
    }
    
    // Activity初始化監聽器
    interface ActivityInitializationListener {
        void onCreate();

        void onStart();

        void onResume();
    }
}

可見在 ReportFragment 對應的生命周期方法裡面進行對應生命周期狀態的分發,分發過程對應 dispatch 方法,裡面調用了 handleLifecycleEvent 方法,該方法會在後文中介紹,其中對 Activity 對應的生命周期監聽是在 ActivityInitializationListener 中完成的,查看該接口的實現類是換一個匿名內部類,位於 ProcessLifecycleOwner 中,源碼如下:

public class ProcessLifecycleOwner implements LifecycleOwner {
    // ...
    
    private Handler mHandler;
    private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);

    private Runnable mDelayedPauseRunnable = new Runnable() {
        @Override
        public void run() {
            dispatchPauseIfNeeded();
            dispatchStopIfNeeded();
        }
    };

    // ActivityInitializationListener匿名實現類
    private ActivityInitializationListener mInitializationListener =
            new ActivityInitializationListener() {
                @Override
                public void onCreate() {
                    // what?
                    // 為什麼沒有處理,不影響閱讀源碼
                }

                @Override
                public void onStart() {
                    activityStarted();
                }

                @Override
                public void onResume() {
                    activityResumed();
                }
            };

    private static final ProcessLifecycleOwner sInstance = new ProcessLifecycleOwner();

    // 初始化,在哪初始化的?——>見後文
    static void init(Context context) {
        sInstance.attach(context);
    }

    void activityStarted() {
        mStartedCounter++;
        if (mStartedCounter == 1 && mStopSent) {
            // 無論ON_START還是ON_RESUME等,關鍵還是handleLifecycleEvent方法
            mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
            mStopSent = false;
        }
    }

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

    void activityStopped() {
        mStartedCounter--;
        dispatchStopIfNeeded();
    }
    private void dispatchPauseIfNeeded() {
        if (mResumedCounter == 0) {
            mPauseSent = true;
            mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
        }
    }
    private void dispatchStopIfNeeded() {
        if (mStartedCounter == 0 && mPauseSent) {
            mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
            mStopSent = true;
        }
    }
    
    void attach(Context context) {
        mHandler = new Handler();
        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        Application app = (Application) context.getApplicationContext();
        // 在沒有Lifecycle組件之前,使用ActivityLifecycleCallbacks監聽所有Activity的生命周期
        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();
            }
        });
    }
}

在沒有 Lifecycle 組件之前,使用 ActivityLifecycleCallbacks 在 Application 註冊來進行所有 Activity 生命周期的監聽,這裡同樣使用了 ActivityLifecycleCallbacks,但是監聽的對象變成了單個的 Activity,是不是感覺使用起來更靈活。

備註:上面有一個問題,ProcessLifecycleOwner 是如何初始化的?答案在後面的一小節。

通過上面分析,最終的生命周期狀態分發在 LifecycleRegistry 的 handleLifecycleEvent 方法中,其調用了 sync 方法,源碼如下:

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 = false;
        // no need to check eldest for nullability, because isSynced does it for us.
        if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
            backwardPass(lifecycleOwner);
        }
        Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
        if (!mNewEventOccurred && newest != null
                && mState.compareTo(newest.getValue().mState) > 0) {
            //關鍵方法
            forwardPass(lifecycleOwner);
        }
    }
    mNewEventOccurred = false;
}

繼續查看 forwardPass 方法,源碼如下:

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

繼續查看 dispatchEvent 方法

static class ObserverWithState {
        State mState;
        GenericLifecycleObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
            // 根據observer生成對應類型的GenericLifecycleObserver
            mLifecycleObserver = Lifecycling.getCallback(observer);
            mState = initialState;
        }

        void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            // 回調生命周期狀態
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }

按照慣例,查看 GenericLifecycleObserver 的實現類,就可以知道在 onStateChanged 方法中分發的生命周期狀態的流向,具體使用了哪個 GenericLifecycleObserver 的實現類取決於 getCallback 方法傳入的 observer,getCallback 方法源碼如下:

 @NonNull
static GenericLifecycleObserver getCallback(Object object) {
    // 直接繼承DefaultLifecycleObserver的方式
    if (object instanceof FullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
    }
    // 推測:如果在管理生命周期時,自定義的Observer繼承自GenericLifecycleObserver
    if (object instanceof GenericLifecycleObserver) {
        return (GenericLifecycleObserver) object;
    }

    // 使用了注解處理器(Annotation Processor)
    final Class<?> klass = object.getClass();
    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);
    }
    return new ReflectiveGenericLifecycleObserver(object);
}

如果是直接繼承 DefaultLifecycleObserver 的方式,則會生成 FullLifecycleObserverAdapter ,在其實現的 onStatChanged 回調方法中會將最終的生命周期狀態分發出去,也就回到了最初自己創建的 LifecycleListener1 中,看看 FullLifecycleObserverAdapter 源碼如下:

class FullLifecycleObserverAdapter implements GenericLifecycleObserver {

    private final FullLifecycleObserver mObserver;

    FullLifecycleObserverAdapter(FullLifecycleObserver observer) {
        mObserver = observer;
    }

    @Override
    public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        //根據具體的Event回調到對應的生命周期方法中
        switch (event) {
            case ON_CREATE:
                mObserver.onCreate(source);
                break;
            case ON_START:
                mObserver.onStart(source);
                break;
            case ON_RESUME:
                mObserver.onResume(source);
                break;
            case ON_PAUSE:
                mObserver.onPause(source);
                break;
            case ON_STOP:
                mObserver.onStop(source);
                break;
            case ON_DESTROY:
                mObserver.onDestroy(source);
                break;
            case ON_ANY:
                throw new IllegalArgumentException("ON_ANY must not been send by anybody");
        }
    }
}

ProcessLifecycleOwner 的初始化#

我們知道 Activity 中生命周期狀態的監聽使用到了 ActivityLifecycleCallbacks,而 ActivityLifecycleCallbacks 的註冊是在 Application 中註冊的,那麼它是如何註冊的,其註冊是在 ProcessLifecycleOwner 的初始化中完成的,找到 ProcessLifecycleOwner 的 init 的方法調用處是在 ProcessLifecycleOwnerInitializer 的 onCreate 方法中調用的,源碼如下:

public class ProcessLifecycleOwnerInitializer extends ContentProvider {
    @Override
    public boolean onCreate() {
        LifecycleDispatcher.init(getContext());
        // 初始化ProcessLifecycleOwner
        ProcessLifecycleOwner.init(getContext());
        return true;
    }

    // ...
}

顯然 ProcessLifecycleOwnerInitializer 是一個 ContentProvider,其 onCreate 方法中除了初始化 ProcessLifecycleOwner 之外,還先初始化了 LifecycleDispatcher,查看 LifecycleDispatcher 源碼如下:

class LifecycleDispatcher {

    private static AtomicBoolean sInitialized = new AtomicBoolean(false);
    // LifecycleDispatcher初始化
    static void init(Context context) {
        if (sInitialized.getAndSet(true)) {
            return;
        }
        // 註冊ActivityLifecycleCallbacks
        ((Application) context.getApplicationContext())
                .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
    }

    @SuppressWarnings("WeakerAccess")
    @VisibleForTesting
    static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            //在Activity中添加一個無界面的Fragment
            ReportFragment.injectIfNeededIn(activity);
        }

        @Override
        public void onActivityStopped(Activity activity) {
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }
    }

    private LifecycleDispatcher() {
    }
}

結合之前的分析,這裡註冊的 ActivityLifecycleCallbacks 和 上文中註冊的 ActivityLifecycleCallbacks 作用是完全不一樣的,這裡的是為了在 Activity 中添加一個無界面的 Fragment,而上文中的則是為了分發 Activity 的生命周期狀態,可見為了保證在 Activity 中添加無界面的 Fragment,也就是 ReportFragment,前後添加兩次,但是 injectIfNeededIn 方法只有在 ReportFragment 未添加的時候才會第二次添加。

前面知道 ProcessLifecycleOwnerInitializer 是一個 ContentProvider,當 ContentProvider 創建的時候也會隨著對應進程的創建而啟動,可以從 ActivityThread 的 main 方法開始查看 ContentProvider 的啟動流程,順便安利一個查看 Android 源碼的工具 AndroidXRef ,百度、Google 即可。

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。