1. 程式人生 > >Android Architecture Component之Lifecycle-Aware Components

Android Architecture Component之Lifecycle-Aware Components

  • 官方原始碼分析

    我們主要從三點進行分析

    • addObserver 新增觀察者
    • handleLifecycleEvent(Event event) 通知觀察者
    • 怎麼獲取Event從而呼叫handleLifecycleEvent。

    • 首先看下被觀察者LifecycleRegistry,我們看下他的addObserver

      @Override
      public void addObserver(@NonNull LifecycleObserver observer) {
          State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
          ObserverWithState statefulObserver = new
      ObserverWithState(observer, initialState); 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--; }

    我們的被觀察著傳入進來之後,首先被封裝成ObserverWithState,意思是帶狀態的Observer,初始化的是INITIALIZED或者DESTROYED,然後放入我們的mObserverMap,管理起來。我們看下ObserverWithState原始碼

    static class ObserverWithState {
        State mState;
        GenericLifecycleObserver mLifecycleObserver;
    
        ObserverWithState(LifecycleObserver observer, State initialState) {
            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;
        }
    }

    裡面有兩個變數,mState存放的是這個observer的狀態,傳入進來的observer通過Lifecycling.getCallback(observer)返回了一個GenericLifecycleObserver物件,我們先看下getCallback方法做了什麼

        @NonNull
    static GenericLifecycleObserver getCallback(Object object) {
        if (object instanceof FullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
        }
    
        if (object instanceof GenericLifecycleObserver) {
            return (GenericLifecycleObserver) object;
        }
    
        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);
    }

    當呼叫 getCallback 時,Lifecycling 會根據傳入的 Object(LifecycleObserver)呼叫 getGeneratedAdapterConstructor。接著看原始碼

            @Nullable
        private static Constructor<? extends GenericLifecycleObserver> getGeneratedAdapterConstructor(
               Class<?> klass) {
           final String fullPackage = klass.getPackage().getName();
           String name = klass.getCanonicalName();
           // anonymous class bug:35073837
           if (name == null) {
               return null;
           }
           final String adapterName = getAdapterName(fullPackage.isEmpty() ? name :
                   name.substring(fullPackage.length() + 1));
           try {
               @SuppressWarnings("unchecked")
               final Class<? extends GenericLifecycleObserver> aClass =
                       (Class<? extends GenericLifecycleObserver>) Class.forName(
                               fullPackage.isEmpty() ? adapterName : fullPackage + "." + adapterName);
               return aClass.getDeclaredConstructor(klass);
           } catch (ClassNotFoundException e) {
               final Class<?> superclass = klass.getSuperclass();
               if (superclass != null) {
                   // 找不到 LifecycleAdapter 時獲取父類的 LifecycleAdapter
                   return getGeneratedAdapterConstructor(superclass);
               }
           } catch (NoSuchMethodException e) {
               // this should not happen
               throw new RuntimeException(e);
           }
           return null;
        }
        static String getAdapterName(String className) {
           return className.replace(".", "_") + "_LifecycleAdapter";
        }

    不難看出,getGeneratedAdapterConstructor 主要是獲取 annotationProcessor 生成的 xxx_LifecycleAdapter(eg:我們定義了MyLifecycle,就會自動生成MyLifecycle_LifecycleAdapter,存放在build/generated/source/apt資料夾下,感興趣的同學請看怎麼編譯器生成註解的文章)的建構函式,並通過反射例項化返回到 getCallback 中。

    需注意的是,如果找不到 LifecycleAdapter 且 object(LifecycleObserver) 存在父類時會試圖獲取父類的LifecycleAdapter(估計是為了應對混淆時只混淆了子類的情況)。

    LifecycleAdapter的主要作用就是把我們寫的MyLifecycle轉化為我們的GenericLifecycleObserver。

    apt(編譯期)自動生成的MyLifecycle_LifecycleAdapter原始碼如下:

         public class MyLifecycle_LifecycleAdapter implements GeneratedAdapter {
          final MyLifecycle mReceiver;
    
          MyLifecycle_LifecycleAdapter(MyLifecycle receiver) {
            this.mReceiver = receiver;
          }
    
          @Override
          public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny,
              MethodCallsLogger logger) {
            boolean hasLogger = logger != null;
            if (onAny) {
              if (!hasLogger || logger.approveCall("onAny", 4)) {
                mReceiver.onAny(owner,event);
              }
              return;
            }
            if (event == Lifecycle.Event.ON_CREATE) {
              if (!hasLogger || logger.approveCall("onCreate", 1)) {
                mReceiver.onCreate();
              }
              return;
            }
            if (event == Lifecycle.Event.ON_DESTROY) {
              if (!hasLogger || logger.approveCall("onDestroy", 1)) {
                mReceiver.onDestroy();
              }
              return;
            }
          }
        }

    通過callMethods根據不同得到event執行不同的方法回撥,呼叫我們自己定義的MyLifecycle的各個方法。

    回到getCallback方法,首先我們獲取MyLifecycle_LifecycleAdapter構造方法方法,然後反射生產GeneratedAdapter物件.

    如果只有一個構造的話返回SingleGeneratedAdapterObserver,多個的話返回CompositeGeneratedAdaptersObserver都失敗的話返回ReflectiveGenericLifecycleObserver,估計是為了應對程式碼混淆的情況。這裡我們只有一個這樣的構造方法,所以
    我們看下SingleGeneratedAdapterObserver的原始碼

    public class SingleGeneratedAdapterObserver implements 
            GenericLifecycleObserver {
    private final GeneratedAdapter mGeneratedAdapter;
    SingleGeneratedAdapterObserver(GeneratedAdapter
               generatedAdapter) {
                mGeneratedAdapter = generatedAdapter;
           }
    
    @Override
    public void onStateChanged(LifecycleOwner source, Lifecycle.Event 
     event) {
    mGeneratedAdapter.callMethods(source, event, false, null);
    mGeneratedAdapter.callMethods(source, event, true, null);
            }
        }

    GeneratedAdapter就是MyLifecycle_LifecycleAdapter,我們在SingleGeneratedAdapterObserver的原始碼中看到有個onStateChanged方法,在呼叫onStateChanged的時候會呼叫GeneratedAdapter的callMethods,從而會呼叫MyLifecycle的方法。那麼onStateChanged是誰呼叫的?

    我們回到ObserverWithState,發現了它的dispatchEvent方法裡面有個onStateChanged,而這個mLifecycleObserver就是我們上面講的SingleGeneratedAdapterObserver,它是通過我們上面講的Lifecycling.getCallback(observer)生成的。

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

    後面會講到怎麼通知所有的觀察者處理事件,我們先總結下新增及呼叫的過程。

    image

    • acitivty中呼叫LifecycleRegistry的ddObserver(LifecycleObserver observer)
    • LifecycleObserver 被封裝成了ObserverWithState並存入我們集合中
    • ObserverWithState 在構造的時候,呼叫了Lifecycling.getCallback(observer)
      • getCallback(observer)呼叫了createGeneratedAdapter()
      • createGeneratedAdapter通過反射生了MyLifecycle_LifecycleAdapter物件
      • MyLifecycle_LifecycleAdapter是在編譯器有apt幫我們生成的
      • 最後返回一個SingleGeneratedAdapterObserver物件
    • 在ObserverWithState的dispatchEvent()方法呼叫了SingleGeneratedAdapterObserver物件的onStateChanged方法,
      • 它又呼叫了MyLifecycle_LifecycleAdapter的callMethods,然後再呼叫了我們自定義的MyLifecycle方法
    • 被觀察者LifecycleRegister的handleLifecycleEvent(),原始碼分析
      public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
          State next = getStateAfter(event);
          moveToState(next);
      }

    其中有個event和state是我們需要關注的,看下原始碼

     @SuppressWarnings("WeakerAccess")
    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
    }
    
    /**
     * Lifecycle states. You can consider the states as the nodes in a graph and
     * {@link Event}s as the edges between these nodes.
     */
    @SuppressWarnings("WeakerAccess")
    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;
    
        /**
         * Compares if this State is greater or equal to the given {@code state}.
         *
         * @param state State to compare with
         * @return true if this State is greater or equal to the given {@code state}
         */
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }

    他們是怎樣的一個對應關係呢,我們看下官方圖解

    image

    舉個列子,假如傳入的event是onstart那麼我們就可以知道它現在的狀態是create,經過onstart他要去Started狀態.我們再回到handleLifecycleEvent
    其中getStateAfter方法就是獲得的是next狀態就是Started.那麼MovetoNext方法是幹啥的呢?
    看下原始碼

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

    裡面有個mstate變數這個變數存放的是LifecycleRegister的當前的state,以上面例子,假如我們當前的是Started,那麼我們就不需要sync()了;如果不是Started,我們先當前的mState狀態重新賦值,然後同步,怎麼同步策略呢?看 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;
    }

    它是比較當前的狀態和我們存我們存放觀察者的集合最早或最新放入的觀察者的狀態,我們知道集合存放的是ObserverWithState裡面有我們註冊觀察者的狀態,假如mState是STARTED,如果觀察者的狀態是CREATED,那麼我們需要通過forwardPass()告訴觀察者狀態變了你要到STARTED,看官方圖就可以知道這個event就為ON_START,看下forwardPass()原始碼

    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
                    pushParentState(observer.mState);
                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
                popParentState();
            }
        }

    第一個while循壞遍歷我們儲存觀察者的集合,第二個是要處理各個狀態經過的event,eg:msate是RESUMED而ObserverWithState中的state是INITIALIZED,那麼他要分發ON_CREATE,ON_RESUME,呼叫ObserverWithState的dispatchEvent方法,其中upEvent就是返回所要經歷的event,那麼dispatchEvent什麼時候呼叫的?

    • 被觀察者LifecycleRegister的handleLifecycleEvent()呼叫

    我們先猜測一下,引文這個方法需要傳入一個event事件,那麼這個event肯定和生命週期關聯起來,那怎麼關聯的呢?還有這個官方的框架怎麼沒有看到初始化的地方?

    其實官方用了一個很好的方法,它是在provider中進行初始化的,我們找到xml檔案,在as3.0中在xml中我們能找到merge的manifest檔案看下

     <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="android.arch.lifecycle.extensions" >
    
    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="26" />
    
    <application>
        <provider
            android:name="android.arch.lifecycle.ProcessLifecycleOwnerInitializer"
            android:authorities="${applicationId}.lifecycle-trojan"
            android:exported="false"
            android:multiprocess="true" />
    </application>
    

    有個provider這個清單檔案是在lifecycle:extensions下的也就是說merge之後這個provider就加到我們的manifest,我們看下ProcessLifecycleOwnerInitializer,原始碼

     @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
        public class ProcessLifecycleOwnerInitializer extends ContentProvider {
        @Override
        public boolean onCreate() {
            LifecycleDispatcher.init(getContext());
            ProcessLifecycleOwner.init(getContext());
            return true;
        }
    
    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, String[] strings, String s, String[] strings1,
            String s1) {
        return null;
    }
    
    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }
    
    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, ContentValues contentValues) {
        return null;
    }
    
    @Override
    public int delete(@NonNull Uri uri, String s, String[] strings) {
        return 0;
    }
    
    @Override
    public int update(@NonNull Uri uri, ContentValues contentValues, String s, String[] strings) {
        return 0;
    }
    }
    

    我們可以看到onCreate()方法裡面有init方法,我們重點關注 LifecycleDispatcher.init(getContext());
    看下他的原始碼

     static void init(Context context) {
        if (sInitialized.getAndSet(true)) {
            return;
        }
        ((Application) context.getApplicationContext())
                .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
    }

    在這裡註冊了ActivityLifecycleCallbacks叫做new DispatcherActivityCallback(),看下他的原始碼

     static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
        private final FragmentCallback mFragmentCallback;
    
        DispatcherActivityCallback() {
            mFragmentCallback = new FragmentCallback();
        }
    
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            if (activity instanceof FragmentActivity) {
                ((FragmentActivity) activity).getSupportFragmentManager()
                        .registerFragmentLifecycleCallbacks(mFragmentCallback, true);
            }
            ReportFragment.injectIfNeededIn(activity);
        }
    
        @Override
        public void onActivityStopped(Activity activity) {
            if (activity instanceof FragmentActivity) {
                markState((FragmentActivity) activity, CREATED);
            }
        }
    
        @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            if (activity instanceof FragmentActivity) {
                markState((FragmentActivity) activity, CREATED);
            }
        }
    }

    我們看到onActivityCreated中註冊了一個FragmentLifecycleCallbacks,這個是監控fragment的生命週期回撥,我們看下面那句injectIfNeededIn,看下他的原始碼

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

    在injectIfNeededIn中我們把reportFragment加入到我們的activity中然後在其各個生命週期中都會呼叫dispatch(),最後呼叫了被觀察者的handleLifecycleEvent,這就回答了我們的問題,但是還有一個疑問,就是為什麼要用fragment而不用ActivityCallBack呢,其實很簡單,ActivityCallBacks生命週期比我們的activity的生命週期要早,也就是說ActivityCallBacks的oncreate比activity的要早,所以我們用了fragment的生命週期和我們handleLifecycleEvent相繫結。這設計的很巧妙。

    總結一下呼叫過程
    image

    • 清單檔案註冊的ProcessLifecycleOwnerInitializer這個provider在oncreate中呼叫了 LifecycleDispatcher.init(getContext());
    • LifecycleDispatcher中的init方法呼叫了((Application) context.getApplicationContext())
      .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
    • DispatcherActivityCallback中的onActivityCreated中呼叫了
      ReportFragment.injectIfNeededIn 把(activity);
    • injectIfNeededIn 把ReportFragment的各個生命週期中呼叫了加入到我們activity中
    • 在ReportFragment的各個生命週期中呼叫了它的dispatch()呼叫了。
    • dispatch()呼叫了LifecycleRegister的handleLifecycleEvent()。