Android新元件架構——Lifecylce

天星技術團隊發表於2018-06-09

作者: Insane (Insane_胖子), 時間: 2018.6 .10

Android新元件架構——Lifecylce

在過去和今年的谷歌IO大會上,Google推出了許多新的元件架構,個人也在慢慢接觸學習這些新的元件架構。今天給大家介紹的一個能處理 Activity 和 Fragment 生命週期的元件 —— Lifecycle. 官網(科學上網):https://developer.android.com/topic/libraries/architecture/lifecycle

簡單案例

class MainActivity : AppCompatActivity() {
    private var lifeListenter:LifeListenter?=null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        lifeListenter= LifeListenter()
        lifecycle.addObserver(lifeListenter!!)
    }
}
複製程式碼
open class LifeListenter : LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate(owner: LifecycleOwner) {
        Log.e("TAG-----CREATE", "CREATE")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStart(owner: LifecycleOwner) {
        Log.e("TAG-----START", "START")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume(owner: LifecycleOwner) {
        Log.e("TAG-----RESUME", "RESUME")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy(owner: LifecycleOwner) {
        Log.e("TAG-----DESTROY", "DESTROY")
    }
}
複製程式碼

列印的Log:

06-03 22:20:00.242 20096-20096/com.lifecycle.lifecycle E/TAG-----CREATE: CREATE
06-03 22:20:00.242 20096-20096/com.lifecycle.lifecycle E/TAG-----START: START
06-03 22:20:00.252 20096-20096/com.lifecycle.lifecycle E/TAG-----RESUME: RESUME
//關掉APP
06-03 22:21:29.822 20723-20723/com.lifecycle.lifecycle E/TAG-----DESTROY: DESTROY
複製程式碼

可以看出來,我們可以清楚的知道 actvity 的生命週期,並且只寫了 一行程式碼 lifecycle.addObserver(lifeListenter!!)。

那麼有人要就會問,這個元件能幹嘛?

學會了這個之後,就不需要再去寫那些類似呼叫並且會導致 onCreate() 和 onDestroy() 臃腫的方法。 例如:那些需要在 onCreate 方法中初始化,在 onStop 進行一些處理,onDestoty 進行釋放的操作。(MVP 中的 Presenter,MediaPlayerd等)。

使用:

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

1.LifecycleOwner

生命週期的事件分發者,在 Activity/Fragment 他們的生命週期發生變化的時候 發出相應的 Event 給LifecycleRegistry。

2.LifecycleObserver

生命週期的觀察者,通過註解將處理函式與希望監聽的Event繫結,當相應的Event發生時,LifecycleRegistry會通知相應的函式進行處理。

3.LifecycleRegistry

控制中心。它負責控制state的轉換、接受分發event事件

通過上面的案例就可以知道,在我們需要對 生命週期進行監聽的類中

1.繼承自 LifecycleObserver
2.在類的方法上 加上註解 @OnLifecycleEvent(Lifecycle.Event.XXXX)
3.在類的方法加上  LifecycleOwner 作為引數
4.在 Activity/Fragment 中 例項化類後 加上  getLifecycle().addObserver(xxx)/Kotlin是(  lifecycle.addObserver(xxxx));
複製程式碼

其中類的註解方法有如下:

  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
    }
複製程式碼

原理分析:

既然他這麼方便就能處理 Activity/Fragment 的生命週期,我們肯定要去知道為什麼他可以這樣的。

//入口:
lifecycle.addObserver(lifeListenter!!)
點選 addObserver 發現他是 Lifecycle 一個抽象方法。
點選 lifecycle 。
複製程式碼
//跟進
   @Override
    public Lifecycle getLifecycle() {
        return super.getLifecycle();
    }
//繼續跟進....
在 SupportActivity 中
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
由:  LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
可以知道  mLifecycleRegistry 是 LifecycleRegistry 的物件
複製程式碼

跟進 LifecycleRegistry :

//在這個類中他繼承自 Lifecycle ,所以 Activirty 的addObserver 實際是 LifecycleRegistry 的
  @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        //把帶著狀態的 observer 封裝成 ObserverWithState
        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

    static class ObserverWithState {
        State mState;
        GenericLifecycleObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
            //getCallback() 通過不同的 observer 放回不同的 mLifecycleObserver
            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;
        }
    }
複製程式碼

跟進 getCallbak()

@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();
       //跟進(1)這個方法,看下面的跟進
        int type = getObserverConstructorType(klass);
        if (type == GENERATED_CALLBACK) {
            List<Constructor<? extends GeneratedAdapter>> constructors =
                    sClassToAdapters.get(klass);
           //這裡是在獲取到構造方法後,根據數量建立不同的 GeneratedAdapteObserver
            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);
    }
  (1).一直跟進到這裡,可以發現上面我們跟進的方法就是通過反射,獲取構造方法

    @Nullable
    private static Constructor<? extends GeneratedAdapter> generatedConstructor(Class<?> klass) {
        try {
            Package aPackage = klass.getPackage();
            String name = klass.getCanonicalName();
            final String fullPackage = aPackage != null ? aPackage.getName() : "";
            final String adapterName = getAdapterName(fullPackage.isEmpty() ? name :
                    name.substring(fullPackage.length() + 1));

            @SuppressWarnings("unchecked") final Class<? extends GeneratedAdapter> aClass =
                    (Class<? extends GeneratedAdapter>) Class.forName(
                            fullPackage.isEmpty() ? adapterName : fullPackage + "." + adapterName);
            Constructor<? extends GeneratedAdapter> constructor =
                    aClass.getDeclaredConstructor(klass);
            if (!constructor.isAccessible()) {
                constructor.setAccessible(true);
            }
            return constructor;
        } catch (ClassNotFoundException e) {
            return null;
        } catch (NoSuchMethodException e) {
            // this should not happen
            throw new RuntimeException(e);
        }
    }
------------------------------------------------------
我們繼續跟進其中一個 GeneratedAdapte 以:SingleGeneratedAdapterObserver 為例
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class SingleGeneratedAdapterObserver implements GenericLifecycleObserver {

    private final GeneratedAdapter mGeneratedAdapter;

    SingleGeneratedAdapterObserver(GeneratedAdapter generatedAdapter) {
        mGeneratedAdapter = generatedAdapter;
    }
 //這裡有個 onStateChanged 方法,用於狀態改變
    @Override
    public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        mGeneratedAdapter.callMethods(source, event, false, null);
        mGeneratedAdapter.callMethods(source, event, true, null);
    }
}
//讓我們回到  ObserverWithState 中,可以知道 這裡的 onStateChanged 就是我們上面生成的   SingleGeneratedAdapterObserver 裡面的方法。
   void dispatchEvent(LifecycleOwner owner, Event event) {
            //得到 State
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
複製程式碼

總結一下: acitivty 中呼叫 LifecycleRegistry 的 ddObserver (實際是 LifecycleRegistry 的) LifecycleObserver 被封裝成了 ObserverWithState 並存入我們集合中, 在 ObserverWithState 中,呼叫了 Lifecycling.getCallback(observer) getCallback(observer) 呼叫了createGeneratedAdapter() createGeneratedAdapter通過構造方法的數量,反射生成了不同的 GenericLifecycleObserver 物件 在ObserverWithState的dispatchEvent()方法呼叫了GenericLifecycleObserver 物件的onStateChanged方法,

回到 SuppertActivity 中
    @Override
    @SuppressWarnings("RestrictedApi")
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
    }
//可以知道這裡建立了 ReportFragment
複製程式碼
//在 ReportFragment 中 可以發現他和我們的 Activity 關聯,並且在生命週期方法中都掉去分發一個 event,跟進一下
  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);
            }
        }
    }
//而 handleLifecycleEvent 方法是在 LifecycleRegistry 去呼叫並且會去執行   
 public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);//獲取下一個state
        moveToState(next);
    }
複製程式碼

分析之前 看一下官網的圖:

lifecycle-states.png

什麼意思呢 大概意思就是可以通過不同的 events 知道不同的 States 。例如:當你的 events 是 ON_RESUME 的時候就代表他當前的 State 是 STARTE 所以 next State 就是 RESUMED, 分析 getStateAfter:

//對照著表其實很簡單, events 是 ON_CREATE 和 ON_STOP 的下一個狀態指向都是 CREATED,所以返回 CREATED,其他的類似。
  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;
        }
複製程式碼

所以 getStateAfter 獲取的是下一個 State 也就是下一個生命週期。 那麼 moveToState(next); 呢?

rivate void moveToState(State next) {
      //判斷 當前 state 是不是 等於我們上面獲取的
        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;
    }
複製程式碼
 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;
        }
      // 當前的 State 和最早的 State  或最新的 State 進行比較。 
      // mObserverMap 這個集合存放的是 ObserverWithState ,而 ObserverWithState 有我們的狀態
        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;
    }
複製程式碼
//第一個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()))) {
                // downEvent 返回下一個 events
                Event event = downEvent(observer.mState);
                pushParentState(getStateAfter(event));
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }
複製程式碼

這兩個都會執行 observer.dispatchEvent (),而這個方法就會去改變 State ,從而我們就知道了生命週期的變化。附上一個簡單的流程圖:

LifecycleRegistry.png

相關文章