lifeCycle如何使用?
-
自定义一个类实现LifecycleObserver,在方法添加注解来监控组件的生命周期状态
public class MyLifeListener implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) void create(){ Log.e("air", "create "); } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) void stop() { Log.e("air", "destory "); } }
2.以activity为例,只需要getLifecycle().addObserver(new MyObserver())这么简单的一句代码,便可以完整的感知页面的生命周期。emmm,我当前的support lib 26.1.0
public class TestActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
getLifecycle().addObserver(new MyLifeListener());
}
}
求大佬轻喷,我只是来打酱油的原理分析
-
support包26以上的SupportActivity和Fragment都默认实现了LifeCycleOwner接口。
实现大体如以下代码。26以下自定义的fragment和activity可以如此实现。public class MyFragment extends Fragment implements LifecycleOwner { LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this); @Override public LifecycleRegistry getLifecycle() { return lifecycleRegistry; } }
-
LifecycleRegistry实现了LifecycleOwner
-
在其内部的addObServer方法中创建了ObserverWithState的实例statefulObserver,判断如果状态改变,调用dispatchEvent方法。;
@Override public void addObserver(LifecycleObserver observer) { State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED; ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); .... boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent; State targetState = calculateTargetState(observer); mAddingObserverCounter++; //如果状态发生改变 while ((statefulObserver.mState.compareTo(targetState) < 0 && mObserverMap.contains(observer))) { pushParentState(statefulObserver.mState); //发送事件 statefulObserver.dispatchEvent(mLifecycleOwner, 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继承LifecycleObserver的接口,内部提供了onStateChanged(LifecycleOwner source, Lifecycle.Event event)的抽象方法。 GenericLifecycleObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { //通过Lifecycling最终获得ReflectiveGenericLifecycleObserver的实例。这个类实现了GenericLifecycleObserver接口。 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; } }
-
Lifecycling如何创建的ReflectiveGenericLifecycleObserver?通过反射获取该类的构造方法, 在getCallback的方法中传入前面添加的LifeCycleObserver对象通过构造方法创建该类的实例对象。
sREFLECTIVE = ReflectiveGenericLifecycleObserver.class.getDeclaredConstructor(Object.class);
-
-
ReflectiveGenericLifecycleObserver的构造方法中。
ReflectiveGenericLifecycleObserver(Object wrapped) { //该对象为LifeCycleObserver的实例 mWrapped = wrapped; mInfo = getInfo(mWrapped.getClass()); }
-
在getInfo中最终调用了
private static CallbackInfo getInfo(Class klass) { CallbackInfo existing = sInfoCache.get(klass); if (existing != null) { return existing; } //调用了createInfo方法 existing = createInfo(klass); return existing; }
-
creatInfo方法可以看出会一一遍历对LifecycleObserver的实现类中加上@OnLifeCycleEvent的注解的方法,添加到CallbackInfo回调信息中
private static CallbackInfo createInfo(Class klass) { Class superclass = klass.getSuperclass(); ... Method[] methods = klass.getDeclaredMethods(); ... for (Method method : methods) { OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class); if (annotation == null) { continue; } .... Event event = annotation.value(); MethodReference methodReference = new MethodReference(callType, method); verifyAndPutHandler(handlerToEvent, methodReference, event, klass); } CallbackInfo info = new CallbackInfo(handlerToEvent); sInfoCache.put(klass, info); return info; }
-
在onStateChanged方法中最终根据回调信息执行添加注解的方法。
@Override public void onStateChanged(LifecycleOwner source, Event event) { invokeCallbacks(mInfo, source, event); }
-
-
完结撒花~