publicinterfaceLifecycleOwner { /** * Returns the Lifecycle of the provider. * * @return The lifecycle of the provider. */ @NonNull Lifecycle getLifecycle(); }
publicstaticvoidinjectIfNeededIn(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.FragmentManagermanager= activity.getFragmentManager(); if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) { manager.beginTransaction().add(newReportFragment(), REPORT_FRAGMENT_TAG).commit(); // Hopefully, we are the first to make a transaction. manager.executePendingTransactions(); } }
这里会添加一个 ReportFragment 如果有阅读过 Glide 源码的同学,应该会看到类似的实现:通过添加一个透明的 Fragment 会监听 Activity 的生命周期。
// event 和 Sate 的对应关系 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; } thrownewIllegalArgumentException("Unexpected event value " + event); }
privatevoidmoveToState(State next) { if (mState == next) { return; } mState = next; if (mHandlingEvent || mAddingObserverCounter != 0) { // 正在处理事件中或者正在处理添加 Observer 中 mNewEventOccurred = true; // we will figure out what to do on upper level. return; } // 标记正在处理事件 mHandlingEvent = true; // 同步状态 sync(); mHandlingEvent = false; }
// happens only on the top of stack (never in reentrance), // so it doesn't have to take in account parents privatevoidsync() { // 使用弱应用持有 LifecycleOwner,也是为了防止 Activity/Fragment 内存泄漏 LifecycleOwnerlifecycleOwner= 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. // 使用 eldest(start) 判断是否需要回退 // 使用 newest(end) 判断是否需要前进,刚添加的 observer 一般为初始化状态 if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) { // 最先添加的 observer 的状态大于当前状态,回退 backwardPass(lifecycleOwner); } Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest(); if (!mNewEventOccurred && newest != null && mState.compareTo(newest.getValue().mState) > 0) { // 最新添加的 observer 如果状态一致,则可以乐观地表示在它之前添加的 observer 状态也是一致的 // mNewEventOccurred 表示有新的事件发生,则放弃这次同步,延迟到下一次 forwardPass(lifecycleOwner); } } mNewEventOccurred = false; }
privatestatic Event downEvent(State state) { switch (state) { case INITIALIZED: thrownewIllegalArgumentException(); case CREATED: return ON_DESTROY; case STARTED: return ON_STOP; case RESUMED: return ON_PAUSE; case DESTROYED: thrownewIllegalArgumentException(); } thrownewIllegalArgumentException("Unexpected state value " + state); }
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; } thrownewIllegalArgumentException("Unexpected event value " + event); }
@Override publicvoidaddObserver(@NonNull LifecycleObserver observer) { // 如果不是 DESTROYED,则从 INITIALIZED 开始分发 StateinitialState= mState == DESTROYED ? DESTROYED : INITIALIZED; // ObserverWithState 用于分发事件给 observer ObserverWithStatestatefulObserver=newObserverWithState(observer, initialState); ObserverWithStateprevious= mObserverMap.putIfAbsent(observer, statefulObserver); if (previous != null) { // 唯一性 return; } LifecycleOwnerlifecycleOwner= mLifecycleOwner.get(); if (lifecycleOwner == null) { // mLifecycleOwner 为弱引用 // it is null we should be destroyed. Fallback quickly return; } // isReentrance 表示是否在分发事件时新添加了 observer // 举个例子:在 observer 在 onStart() 中又调用了 addObserver() booleanisReentrance= mAddingObserverCounter != 0 || mHandlingEvent; // 计算需要分发的状态 StatetargetState= calculateTargetState(observer); mAddingObserverCounter++; // 将事件逐步分发到 targetState while ((statefulObserver.mState.compareTo(targetState) < 0 && mObserverMap.contains(observer))) { // 如果 statefulObserver.state 小于 targetState pushParentState(statefulObserver.mState); // 如果 state 为 STARTED,则 upEvent(state) 则为 ON_RESUME 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--; }
privatestatic Event upEvent(State state) { switch (state) { case INITIALIZED: case DESTROYED: return ON_CREATE; case CREATED: return ON_START; case STARTED: return ON_RESUME; case RESUMED: thrownewIllegalArgumentException(); } thrownewIllegalArgumentException("Unexpected state value " + state); }
Implement this to initialize your content provider on startup. This method is called for all registered content providers on the application main thread at application launch time. It must not perform lengthy operations, or application startup will be delayed.
// ReportFragment.java publicstaticvoidinjectIfNeededIn(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.FragmentManagermanager= activity.getFragmentManager(); if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) { // 重复添加判断 manager.beginTransaction().add(newReportFragment(), REPORT_FRAGMENT_TAG).commit(); // Hopefully, we are the first to make a transaction. manager.executePendingTransactions(); } }