*lifecycle介绍:*lifecycle是jetpack 库中的组件之一,它可以感知所依赖的activity与fragment的生命周期。 jetpack 的出现,可以让程序更好的实现mvvm架构模式,而在mvvm 的架构模式中,view 视图层只做与视图相关的操作,业务逻辑不应该写在其中,在android 中继承于fragment与activity的子类通常作为视图层来看待。lifecycle可以将依赖于fragment与activity的生命周期的代码进行分离,使得更好的实现MVVM架构模式,降低了程序的耦合,逻辑更加清晰。 使用环境:Java7、Android Support Library 28 然后在我们的组件中通过 getLifecycle().addObserver()方法将该类的实例作为参数传入即可。 getLifecycle()是LifecycleOwner接口中的方法,LifecycleOwner在ComponentActivity 中被实现 ComponentActivity ()会将自身进行传入并构建一个LifecycleRegistry 对象 查看该构造方法,可以看出将传递进来的LifecycleOwner 封装成一个WeakReference弱引用对象并保存(使用弱引用的目的是防止内存泄露的发生),并将mState状态位置为INITIALIZED,这个mLifecycleOwner 会在组件进行生命周期方法时,在通知观察者对象的流程中会被使用到,使用弱引用的对象会存活到下一次垃圾回收时。 getLifecycle()会将这个构建好的LifecycleRegistry 进行返回 当我们调用getLifecycle().addObserver();方法时其实调用的是LifecycleRegistry 内部的addObserver() 这里调用了ObserverWithState()方法 继续进入Lifecycling.lifecycleEventObserver(observer), 这一步主要的作用是判断是否需要通过FullLifecycleObserverAdapter()对观察者进行封装,实现FullLifecycleObserver表示能对组件完整的生命周期进行监听,实现LifecycleEventObserver表示能监听onStateChanged()的变化 通过注释可看出当所依赖的组件的状态发生改变时会进行调用 如果该观察者实现了FullLifecycleObserver 接口,则必须调用FullLifecycleObserverAdapter()通过适配器模式进行适配,进入 可以发现当调用该方法的onStateChanged()方法时会根据传入的event调用观察者的相关方法。 继续回到addObserver() 调用完ObserverWithState之后会通过map将我们的观察者存储起来,而map的value 就是ObserverWithState返回的实例。到此处为止整个注册流程结束。 当我们注册流程走完之后,如果所依赖的组件发出生命周期回调时 进入到handleLifecycleEvent方法 getStateAfter会根据传入的event 进行判断返回state 并传入到moveToState方法中去,在该方法内会将state 值赋给mState进行保存,并在最后调用到了 sync()方法。 在该方法内,会从mLifecycleOwner中获取当前组件的引用,如果为null,则表示垃圾回收器已将该弱引用的对象进行了回收所以直接抛出异常下面的流程将不会继续走,而之所以要加这个操作的目的主要就是为了,当所依赖的组件对象销毁后防止内存泄露的发生。 在这个方法内有2个比较重要的方法forwardPass,backwardPass,进入到这2个方法内,会发现会对map进行遍历切最终都会调用到 observer.dispatchEvent方法,也就是保存在map集合中的观察者的dispatchEvent方法会被调用 进入到该方法会发现调用到了观察者的onStateChanged方法,该方法在LifecycleEventObserver接口中会进行实现,而在FullLifecycleObserver接口中没有,但是会通过适配器模式进行适配从而能正确根据传入的状态码调用到观察者的相应方法(上面有提过)。 整个lifecycle的调用流程结束。简单使用:
从使用步骤上来说,我们首先需要定义一个类实现LifecycleObserver 接口,在这个类中定义方法并实现使用@OnLifecycleEvent注解,这个注解实现了与方法的映射关系,当所关联的组件的生命周期调用时会回调到注解所映射的对应方法。class TestLifecycleObserver implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_START) public void testOnStart(){ } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) public void testOnDestroy(){ } }
public class TestActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getLifecycle().addObserver(new TestLifecycleObserver()); } }
源码分析:
@SuppressWarnings({"WeakerAccess", "unused"}) public interface LifecycleOwner { @NonNull Lifecycle getLifecycle(); }
public class ComponentActivity extends androidx.core.app.ComponentActivity implements LifecycleOwner, ViewModelStoreOwner, SavedStateRegistryOwner, OnBackPressedDispatcherOwner
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
public LifecycleRegistry(@NonNull LifecycleOwner provider) { mLifecycleOwner = new WeakReference<>(provider); mState = INITIALIZED; }
public Lifecycle getLifecycle() { return mLifecycleRegistry; }
public void addObserver(@NonNull LifecycleObserver observer) { 设置初始化状态 State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED; //调用该方法,判断是否使用适配器模式对传递进来的观察者进行封装 ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); //通过map将传递进来的观察者进行保存 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(LifecycleObserver observer, State initialState) { mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer); mState = initialState; }
static LifecycleEventObserver lifecycleEventObserver(Object object) { //对观察者的类型进行判断, boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver; boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver; //如果该观察者同时实现了LifecycleEventObserver与FullLifecycleObserver接口则使用FullLifecycleObserverAdapter进行适配封装 if (isLifecycleEventObserver && isFullLifecycleObserver) { return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, (LifecycleEventObserver) object); } //如果该观察者实现了FullLifecycleObserver if (isFullLifecycleObserver) { return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null); } //如果该观察者只实现了LifecycleEventObserver接口 if (isLifecycleEventObserver) { return (LifecycleEventObserver) object; }
public interface LifecycleEventObserver extends LifecycleObserver { /** * Called when a state transition event happens. * * @param source The source of the event * @param event The event */ void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event); }
interface FullLifecycleObserver extends LifecycleObserver { void onCreate(LifecycleOwner owner); void onStart(LifecycleOwner owner); void onResume(LifecycleOwner owner); void onPause(LifecycleOwner owner); void onStop(LifecycleOwner owner); void onDestroy(LifecycleOwner owner); }
FullLifecycleObserverAdapter()class FullLifecycleObserverAdapter implements LifecycleEventObserver { private final FullLifecycleObserver mFullLifecycleObserver; private final LifecycleEventObserver mLifecycleEventObserver; FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver, LifecycleEventObserver lifecycleEventObserver) { mFullLifecycleObserver = fullLifecycleObserver; mLifecycleEventObserver = lifecycleEventObserver; } @Override public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) { switch (event) { case ON_CREATE: mFullLifecycleObserver.onCreate(source); break; case ON_START: mFullLifecycleObserver.onStart(source); break; case ON_RESUME: mFullLifecycleObserver.onResume(source); break; case ON_PAUSE: mFullLifecycleObserver.onPause(source); break; case ON_STOP: mFullLifecycleObserver.onStop(source); break; case ON_DESTROY: mFullLifecycleObserver.onDestroy(source); break; case ON_ANY: throw new IllegalArgumentException("ON_ANY must not been send by anybody"); } if (mLifecycleEventObserver != null) { mLifecycleEventObserver.onStateChanged(source, event); } } }
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
会调用到LifecycleRegistry实例的handleLifecycleEvent方法并根据调用的位置传入不同的event枚举类型 public void handleLifecycleEvent(@NonNull Lifecycle.Event event) { State next = getStateAfter(event); moveToState(next); } 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; }
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; }
private void sync() { LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); if (lifecycleOwner == null) { throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already" + "garbage collected. It is too late to change lifecycle state."); } //对map中存储的观察者的状态位进行比对,查看是否一致,若不相等则进入到循环体内 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; }
void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; }
本网页所有视频内容由 imoviebox边看边下-网页视频下载, iurlBox网页地址收藏管理器 下载并得到。
ImovieBox网页视频下载器 下载地址: ImovieBox网页视频下载器-最新版本下载
本文章由: imapbox邮箱云存储,邮箱网盘,ImageBox 图片批量下载器,网页图片批量下载专家,网页图片批量下载器,获取到文章图片,imoviebox网页视频批量下载器,下载视频内容,为您提供.
阅读和此文章类似的: 全球云计算