1. 程式人生 > >Android Jetpack 組建介紹(二)——Lifecycler

Android Jetpack 組建介紹(二)——Lifecycler

參考Android Jetpack架構元件之 Lifecycle(原始碼篇)

原始碼分析

關於Lifecycle的使用考上一篇文章Android Jetpack框架之 Lifecycles(使用篇),從使用的方法中我們知道Lifecycle的實現主要依賴:LifecycleObserver、LifecycleOwner;通過像Owner註冊Observer實現感知Owner的生命週期,下面一起看看原始碼是如何巧妙設計的;

生命週期觀察者:LifecycleObserver

// 實現LifecycleObserver
class MyObserver(var lifecycle: Lifecycle, var callback: CallBack) : LifecycleObserver {
 
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public fun connectOnCreate() {
        p("connectOnCreate")
    }
 
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public fun connectOnResume() {
        p("connectOnResume")
 
    }
}
 
// LifecycleObserver 是一個空介面
public interface LifecycleObserver {
 
}

上面過程做了三件事情:

  • 實現LifecycleObserver的介面
  • 編寫要執行的方法
  • 為每個方法添加註解,表示其執行的時機

@OnLifecycleEvent:執行註解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnLifecycleEvent {
    Lifecycle.Event value();
}

生命週期:Lifecycle.Event & State

// 生命週期Event
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
    }
 
//5個對應的生命週期狀態
 public enum State {
 
        DESTROYED,
 
        INITIALIZED,
 
        CREATED,
 
        STARTED,
 
        RESUMED;
 
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }

通過Lifecycle.Event和State的檢視,系統提供了Activity每個生命週期對應的Event,而Event有會有對應的State,此時 以大致猜想到上面的執行過程:

  • 使用LifeEvent標記每個執行方法的Event
  • 當活動狀態改變時,系統會判斷即將要改變成的狀態
  • 根據狀態獲取要執行的Event
  • 從註冊的Observer中獲取標註為對應的Event,執行邏輯

生命週期的感知

LifecycleOwner

class LifeCyclerActivity : AppCompatActivity() {
  ...
 var myObserver = MyObserver(lifecycle, object : CallBack { // 建立LifecyclerObserver
            override fun update() {
          ...
            }
        })
        lifecycle.addObserver(myObserver) // 新增觀察者
    }
}

從上面的使用情況看出,使用的活動需要呼叫getLifecycle()方法,返回LifecycleRegistry,這裡的getLifecycle()方法其實是介面LifecycleOwner介面中的方法,

@SuppressWarnings({"WeakerAccess", "unused"})
public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();
}

此時LifecycleActivity雖然沒有實現介面,因為他繼承的AppCompatActivity繼承了SupportActivity,而SupportActivity實現了介面

@RestrictTo(LIBRARY_GROUP)
public class SupportActivity extends Activity implements LifecycleOwner {
 
 private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); //建立
 
 @Override
    public Lifecycle getLifecycle() { // 重寫方法返回LifecycleRegistry 
        return mLifecycleRegistry;
    }
 
}

SupportActivity除了執行上述操作外,在onCrate的方法中還有一句重要的程式碼,初始化了一個ReportFragment

protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
    }
ReportFragment
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) { //初始化Fragment
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            manager.executePendingTransactions();
        }
    }
 
  @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);
        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);
            }
        }
    }
}

上面程式碼中做了兩件事:

  • 新增一個ReportFragment的例項
  • 根據Fragment的每個生命週期的回撥,呼叫dispatch()處理回撥事件

在dispatch()方法中根據LifecyclerOwner和LifecyclerRegistryOwner例項分別處理,因為LifecyclerRegistryOwner也是繼承LifecyclerOwner,而在我們SupportActivity中的getLifecycler()中返回的是LifecycleRegistry,所以此處回撥的都是LifecycleRegistry的handleLifecycleEvent;