Lifecycle的基本使用和原理

Lifecycle是用来观察和监听Activity、Fragment生命周期的组件。

一、Lifecycle的基本使用

Lifecycle有两个核心类,一个是LifecycleOwner接口,该接口有一个getLifecycle()方法,实现这个接口的类就可以作为一个被观察者,AppCompatActivity和Fragment就实现了这个接口,所以它们的 生命周期可以被观察和监听。另一个是LifecycleObserver接口,实现了这个接口可以作为一个观察者。

1、自定义一个观察者类

class MyLifecycleObserver : LifecycleObserver {

    //监听onCreate
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStart(){
        Log.w("bestchangge", "LifecycleObserver_onStart")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume() {
        Log.w("bestchangge", "LifecycleObserver_onResume")
    }
    //...
}

2、创建一个AppCompatActivity作为被观察者

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //将观察者和被观察者关联起来
        lifecycle.addObserver(MyLifecycleObserver())
    }

    override fun onStart() {
        super.onStart()
        Log.w("bestchangge","onStart...")
    }

    override fun onResume() {
        super.onResume()
        Log.w("bestchangge","onResume...")
    }
}

3、打开MainActivity观察生命周期方法日志

2021-02-24 15:29:50.297 10988-10988/com.sun.jetpack W/bestchangge: onStart...
2021-02-24 15:29:50.297 10988-10988/com.sun.jetpack W/bestchangge: LifecycleObserver_onStart
2021-02-24 15:29:50.299 10988-10988/com.sun.jetpack W/bestchangge: onResume...
2021-02-24 15:29:50.300 10988-10988/com.sun.jetpack W/bestchangge: LifecycleObserver_onResume

可以看出,当Activity中的生命周期方法回调时,都会回调LifecycleObserver中对应的监听方法。

二、Lifecycle的原理

从使用的地方addObserver入手

//将观察者和被观察者关联起来
lifecycle.addObserver(MyLifecycleObserver())
//LifecycleRegistry.java
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
    //关键代码1 new ObserverWithState(observer, initialState)
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
    //...
}
//最终追溯到ClassesInfoCache  会通过反射将带有@OnLifecycleEvent注解的方法信息缓存起来
//ClassesInfoCache.java
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
    //...
    Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
    boolean hasLifecycleMethods = false;
    for (Method method : methods) {
        OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
        if (annotation == null) {
            continue;
        }
       //...
        Lifecycle.Event event = annotation.value();
             //...
        verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
    }
    CallbackInfo info = new CallbackInfo(handlerToEvent);
    mCallbackMap.put(klass, info);
    mHasLifecycleMethods.put(klass, hasLifecycleMethods);
    return info;
}

至于什么时候触发生命周期回调,我们回到ComponentActivity的onCreate方法中。

//ComponentActivity.java
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   //...
   //通过一个没有UI的ReportFragment绑定到Activity上来实现触发
    ReportFragment.injectIfNeededIn(this);
   //...
}
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();
    }
}

在ReportFragment中的生命周期方法中,会去分发生命周期事件,以onResume为例:

@Override
public void onResume() {
    super.onResume();
    dispatchResume(mProcessListener);
    dispatch(Lifecycle.Event.ON_RESUME);
}
private void dispatch(Lifecycle.Event event) {
    Activity activity = getActivity();
    //...
    if (activity instanceof LifecycleOwner) {
        Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
        if (lifecycle instanceof LifecycleRegistry) {
      //关键代码handleLifecycleEvent
            ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
        }
    }
}
//设置当前状态并通知观察者
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    State next = getStateAfter(event);
    moveToState(next);
}
//getStateAfter方法,会根据生命周期事件获取当前生命周期状态
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;
    }
    throw new IllegalArgumentException("Unexpected event value " + event);
}

  private void moveToState(State next) {
       //...
        sync();
       //...
    }

private void sync() {
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
       //...
        while (!isSynced()) {
               //...
               //关键代码forwardPass:sync中会调用backwardPass或forwardPass去同步生命周期并将当前生命周期   Event事件回调给观察者,这里以forwardPass为例
                forwardPass(lifecycleOwner);
               //...
            }
        }
    }

 private void forwardPass(LifecycleOwner lifecycleOwner) {
        Iterator> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
            Entry entry = ascendingIterator.next();
           //ObserverWithState在addObserver时记录了反射方法
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                pushParentState(observer.mState);
                //分发事件
                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
                popParentState();
            }
        }
    }
static class ObserverWithState {
    State mState;
    LifecycleEventObserver mLifecycleObserver;

    ObserverWithState(LifecycleObserver observer, State initialState) {
        mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
        mState = initialState;
    }

    void dispatchEvent(LifecycleOwner owner, Event event) {
        State newState = getStateAfter(event);
        mState = min(mState, newState);
        //关键代码 找到实现类ReflectiveGenericLifecycleObserver
        mLifecycleObserver.onStateChanged(owner, event);
        mState = newState;
    }
}
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;![lifecycle.png](https://upload-images.jianshu.io/upload_images/6345209-5bf15047edb37b0a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

    private final CallbackInfo mInfo;

    ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }

    @Override
    public void onStateChanged(LifecycleOwner source, Event event) {
        //根据Activity生命周期状态反射对应的方法,这样就完成了整个流程
        mInfo.invokeCallbacks(source, event, mWrapped);
    }
}
一、小结
lifecycle.png

你可能感兴趣的:(Lifecycle的基本使用和原理)