您好,登錄后才能下訂單哦!
Android中Lifecycle的作用是什么?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
Lifecycle的簡單介紹
Lifecycle的介紹,我們還是拿Google的官方文檔作為參考吧。
Lifecycle主要解決的是業務和Activity/Fragment生命周期相關的問題。例如:我們在onResume()/onStart()中請求定位,在onPause()/onStop()中停止定位。那么我們一般的做法:
class MyLocationListener { public MyLocationListener(Context context, Callback callback) { // ... } void start() { // connect to system location service } void stop() { // disconnect from system location service } } class MyActivity extends AppCompatActivity { private MyLocationListener myLocationListener; @Override public void onCreate(...) { myLocationListener = new MyLocationListener(this, (location) -> { // update UI }); } @Override public void onStart() { super.onStart(); myLocationListener.start(); // manage other components that need to respond // to the activity lifecycle } @Override public void onStop() { super.onStop(); myLocationListener.stop(); // manage other components that need to respond // to the activity lifecycle } }
上面的代碼雖然看起來還可以,但在真實的應用程序中,可能會有很多的方法都需要根據當前Activity/Fragment的生命周期來進行不同的操作。因此其生命周期方法中可能會被放置大量代碼,例如onStart()和 onStop()中,這使得它們難以維護。因此Lifecycle應運而生!
3. Lifecycle的使用
Lifecycle已經發布了release版,所以其中的一些默認支持已經包含到了support-v7:26.1.0以及更高。
添加依賴:
implementation "android.arch.lifecycle:extensions:1.1.1" annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
使用方式1:實現LifecycleObserver接口,使用@OnLifecycleEvent注解,通過編譯時注解生成代碼:
public class MyLifecycleObserver implements LifecycleObserver { private static final String TAG = MyLifecycleObserver.class.getSimpleName(); @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public void start(LifecycleOwner lifecycleOwner) { Lifecycle.State currentState = lifecycleOwner.getLifecycle().getCurrentState(); Log.d(TAG, "start: " + currentState); } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void stop(LifecycleOwner lifecycleOwner) { Log.d(TAG, "stop: " + lifecycleOwner.getLifecycle().getCurrentState()); } }
APT生成的代碼
使用方式2:實現GenericLifecycleObserver接口,實現其onStateChanged方法:
public class MyLifecycleObserver implements GenericLifecycleObserver { private static final String TAG = MyLifecycleObserver.class.getSimpleName(); @Override public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) { Log.d(TAG, event.name()); } }
創建完成后,我們需要將其添加:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getLifecycle().addObserver(new MyLifecycleObserver()); } }
結果圖:
方法1
方法2
4. 源碼分析
1.Lifecycle的獲取
根據源碼追蹤我們可以看到Lifecycle是在SupportActivity中:
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); @Override public Lifecycle getLifecycle() { return mLifecycleRegistry; }
這里還有個挺重要的代碼:
SupportActivity.java
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this); }
ReportFragment.java
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中添加了一個Fragment,至于作用,留到后面在講。
2.addObserver
addObserver方法的話,還是簡單來看吧:
LifecycleRegistry.java
@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); ...... // 對狀態的修正,這里會對已經過去的狀態進行分發。也就是說如果添加observer時狀態已經改變,那么也會被通知到! } // 有狀態的Observer 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; } }
我們將實現的接口通過裝飾者(我認為是這樣)模式轉成ObserverWithState對象,并將該對象添加到mObserverMap中。
在ObserverWithState的構造方法中,有對我們傳入的LifecycleObserver進行包裝:
Lifecycling.java
@NonNull static GenericLifecycleObserver getCallback(Object object) { // 這里應該算第三種實現方式,然而FullLifecycleObserver不是public,所以不能使用 if (object instanceof FullLifecycleObserver) { return new FullLifecycleObserverAdapter((FullLifecycleObserver) object); } // 我們的第一種方式 if (object instanceof GenericLifecycleObserver) { return (GenericLifecycleObserver) object; } // 通過注解生成的 final Class<?> klass = object.getClass(); // 將生成的MyLifecycleObserver_LifecycleAdapter放到Map中 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); }
根據我們傳入的對象進行解析,最終返回結果為:GenericLifecycleObserver或者GenericLifecycleObserver的實現類。附獲取生成MyLifecycleObserver_LifecycleAdapter代碼:
// 通過名稱獲取 public static String getAdapterName(String className) { return className.replace(".", "_") + "_LifecycleAdapter"; }
最終通過Class.forName方式獲得Class。
3.事件分發
Lifecycle的事件分發在ObserverWithState類中:
// 事件分發 void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; }
看下哪里調用了dispatchEvent方法:
調用
我們看這個方法,其中一個在addObserver中調用,另外的兩個都會通過sync()方法調用:
// happens only on the top of stack (never in reentrance), // so it doesn't have to take in account parents 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; } // 是否狀態同步的 private boolean isSynced() { if (mObserverMap.size() == 0) { return true; } // 最新的和最后添加的Observer狀態一致,并且當前的狀態和最新狀態一致,則已經同步了 State eldestObserverState = mObserverMap.eldest().getValue().mState; State newestObserverState = mObserverMap.newest().getValue().mState; return eldestObserverState == newestObserverState && mState == newestObserverState; }
這里的同步方法用于同步當前Observer的狀態,如果最新的和最老的Observer的狀態不一致或者當前的狀態和最新的狀態不一致時,那么需要進行狀態同步。同步包括了向前同步和向后同步。
調用sync()方法一共就兩處,一處在addObserver方法,另一處是moveToState方法,而調用moveToState方法也有兩處:
@SuppressWarnings("WeakerAccess") @MainThread public void markState(@NonNull State state) { moveToState(state); } public void handleLifecycleEvent(@NonNull Lifecycle.Event event) { State next = getStateAfter(event); moveToState(next); }
handleLifecycleEvent方法有很多處調用:
handleLifecycleEvent調用
看圖的話,就可以知道Fragment在不同的生命周期調用了handleLifecycleEvent方法,隨便看一個吧:
ON_CREATE
還記得上面說的ReportFragment嗎?這里也出現了,我們看下ReportFragment到底做什么的:
// 調用Activity的 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); } } } // 生命周期 @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; }
可以看到,ReportFragment只是作為一個中間層,通過它來分發各種事件!
由于篇幅原因(已經啰嗦了很多了),這里就不寫LifecycleDispatcher和ProcessLifecycleOwner了,這兩個通過自定義的內容提供者ProcessLifecycleOwnerInitializer進行初始化,并且通過registerActivityLifecycleCallbacks和registerFragmentLifecycleCallbacks注冊統一的觀察回調。
看完上述內容,你們掌握Android中Lifecycle的作用是什么的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。