Jetpack之Lifecycle

255 阅读3分钟

作用

lifecycle是一个生命周期感知型组件可执行操作来响应另一个组件(如 Activity 和 Fragment)的生命周期状态的变化。可以让将一部分Activity的业务逻辑放到Lifecycle中让代码看起来更条理和简洁。

基本使用

MainActivity.kt

class MainActivity : AppCompatActivity() {
    private val TAG:String = "MainLifecycle"
    private val life:MainLifecycle = MainLifecycle()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Log.d(TAG,"onCreate")
        lifecycle.addObserver(life)
    }

    override fun onStart() {
        super.onStart()
        Log.d(TAG,"onStart")
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG,"onResume")
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG,"onPause")
    }

    override fun onStop() {
        super.onStop()
        Log.d(TAG,"onStop")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG,"onDestroy")
    }
}

MainLifecycle.kt

class MainLifecycle : LifecycleObserver{
    private val TAG:String = "MainLifecycle"

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private fun create(){
        Log.i(TAG,"create")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private fun start(){
        Log.i(TAG,"start")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private fun resume(){
        Log.i(TAG,"resume")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    private fun pause(){
        Log.i(TAG,"pause")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private fun stop(){
        Log.i(TAG,"stop")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private fun destroy(){
        Log.i(TAG,"destroy")
    }
}

Log输出

2021-07-20 10:29:52.046 15488-15488/com.example.jetpacklearn D/MainLifecycle: onCreate
2021-07-20 10:29:52.049 15488-15488/com.example.jetpacklearn I/MainLifecycle: create
2021-07-20 10:29:52.062 15488-15488/com.example.jetpacklearn D/MainLifecycle: onStart
2021-07-20 10:29:52.063 15488-15488/com.example.jetpacklearn I/MainLifecycle: start
2021-07-20 10:29:52.064 15488-15488/com.example.jetpacklearn D/MainLifecycle: onResume
2021-07-20 10:29:52.067 15488-15488/com.example.jetpacklearn I/MainLifecycle: resume
2021-07-20 10:29:55.947 15488-15488/com.example.jetpacklearn I/MainLifecycle: pause
2021-07-20 10:29:55.948 15488-15488/com.example.jetpacklearn D/MainLifecycle: onPause
2021-07-20 10:29:56.366 15488-15488/com.example.jetpacklearn I/MainLifecycle: stop
2021-07-20 10:29:56.370 15488-15488/com.example.jetpacklearn D/MainLifecycle: onStop

需要注意一点,Resume之前都是先执行Activity的,Resume之后都是先执行Lifecycle的生命周期。

将自定义的Class继承LifecycleObserver,将要关联生命周期的方法前加上注解

@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)

在Activity中调用

getLifecycle.addObserver(lifecycle)

与之关联就可以了

原理解析

从getLifecycle.addObserver(lifecycle)方法进入到Activity继承自ComponentActivity

private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

public Lifecycle getLifecycle() {
    return mLifecycleRegistry;
}

LifecycleRegistry这个类负责LifecycleOwner和LifecycleObserver之间时间的传递

在它的OnCreate方法中

protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSavedStateRegistryController.performRestore(savedInstanceState);
    ReportFragment.injectIfNeededIn(this);
    if (mContentLayoutId != 0) {
        setContentView(mContentLayoutId);
    }
}

ReportFragment.injectIfNeededIn(this)

public static void injectIfNeededIn(Activity activity) {
    if (Build.VERSION.SDK_INT >= 29) {
        activity.registerActivityLifecycleCallbacks(
                new LifecycleCallbacks());
    }

    android.app.FragmentManager manager = activity.getFragmentManager();
    if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
        manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
        manager.executePendingTransactions();
    }
}

API大于29会注册LifecycleCallbacks。点进去这个方法看一下

public void registerActivityLifecycleCallbacks(
        @NonNull Application.ActivityLifecycleCallbacks callback) {
    synchronized (mActivityLifecycleCallbacks) {
        mActivityLifecycleCallbacks.add(callback);
    }
}

查看mActivityLifecycleCallbacks这个变量会发现

private void dispatchActivityPreCreated(@Nullable Bundle savedInstanceState) {
    getApplication().dispatchActivityPreCreated(this, savedInstanceState);
    Object[] callbacks = collectActivityLifecycleCallbacks();
    if (callbacks != null) {
        for (int i = 0; i < callbacks.length; i++) {
            ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPreCreated(this,
                    savedInstanceState);
        }
    }
}
private void dispatchActivityPreStarted() {
    getApplication().dispatchActivityPreStarted(this);
    Object[] callbacks = collectActivityLifecycleCallbacks();
    if (callbacks != null) {
        for (int i = 0; i < callbacks.length; i++) {
            ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPreStarted(this);
        }
    }
}

有很多类似生命周期的方法会循环调用存入的callback来通知生命周期的改变。collectActivityLifecycleCallbacks这个方法只是将mActivityLifecycleCallbacks变量从List变成Array方便循环调用。

再回过头去看ReportFragment

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    dispatchCreate(mProcessListener);
    dispatch(Lifecycle.Event.ON_CREATE);
}

@Override
public void onStart() {
    super.onStart();
    dispatchStart(mProcessListener);
    dispatch(Lifecycle.Event.ON_START);
}

@Override
public void onResume() {
    super.onResume();
    dispatchResume(mProcessListener);
    dispatch(Lifecycle.Event.ON_RESUME);
}

@Override
public void onPause() {
    super.onPause();
    dispatch(Lifecycle.Event.ON_PAUSE);
}

@Override
public void onStop() {
    super.onStop();
    dispatch(Lifecycle.Event.ON_STOP);
}

都是通过dispatch()方法将生命周期传递出去。

static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
    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);
        }
    }
}

将Activity强制转换为LifecycleRegistryOwner后通过调用getLifecycle()来获取LifecycleRegistry去调用它的 handleLifecycleEvent。

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 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.");
    }
    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;
}

判断状态后会分别调用backwardPass(lifecycleOwner),forwardPass(lifecycleOwner)。

private void backwardPass(LifecycleOwner lifecycleOwner) {
    Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
            mObserverMap.descendingIterator();
    while (descendingIterator.hasNext() && !mNewEventOccurred) {
        Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
        ObserverWithState observer = entry.getValue();
        while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                && mObserverMap.contains(entry.getKey()))) {
            Event event = downEvent(observer.mState);
            pushParentState(getStateAfter(event));
            observer.dispatchEvent(lifecycleOwner, event);
            popParentState();
        }
    }
}
private void forwardPass(LifecycleOwner lifecycleOwner) {
    Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
            mObserverMap.iteratorWithAdditions();
    while (ascendingIterator.hasNext() && !mNewEventOccurred) {
        Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
        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();
        }
    }
}

先看一下ObserverWithState,忘了说addObserver方法了,顺便看一下

public void addObserver(@NonNull LifecycleObserver observer) {
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    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与ObserverWithState存入mObserverMap,经过判断后最后调用了ObserverWithState的dispatchEvent方法。这下来看ObserverWithState

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);
        mLifecycleObserver.onStateChanged(owner, event);
        mState = newState;
    }
}

它的构造方法将LifecycleObserver包装成LifecycleEventObserver,通过LifecycleEventObserver.onStateChanged来发送生命周期的变化。 上面的backwardPass(lifecycleOwner),forwardPass(lifecycleOwner)。最后也会调用dispatchEvent方法来完成事件的发送。