Bootstrap

Android JecPack组件之LifeCycles 使用详解

一、背景

LifeCycle 是一个可以感知宿主生命周期变化的组件。常见的宿主包括 Activity/Fragment、Service 和 Application。LifeCycle 会持有宿主的生命周期状态的信息,当宿主生命周期发生变化时,会通知监听宿主的观察者。

LifeCycle 的出现主要是为了解决: 系统组件的生命周期与普通组件之间的耦合性。

  • 系统组件指:Activity/Fragment、Service 和 Application。

  • 普通组件指:将代码按照功能或者作用封装成的组件。

比如要想在某个Acvitity组件的不同生命周期执行不同的业务代码,现在有下面三种方式:

1.1 第一种:直接在Activity文件里去针对不同的生命周期函数里去写业务代码。

这样会造成Activity代码里充斥着大量的业务逻辑,而且不利于解耦,后期会所有的逻辑堆叠在Activity文件里。

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class LoginActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        Log.i(TAG, "onCreate")
    }
    
    override fun onStart() {
        Log.i(TAG, "onStart")
    }

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

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

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

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

1.2 第二种:通过生命周期的接口解耦

比如声明一个LifeListener的接口,暴露各个声明周期

interface LifeListener {

    fun onCreate()

    fun onStart()

    fun onResume()

    fun onPause()

    fun onStop()

    fun onDestroy()

}

接着在Activity文件的声明周期里,只需要在这个Activity里注册这个接口的实现类,然后在不同的生命周期函数里通过mLifeListener去分发不同生命周期时机,这样业务逻辑就可以在这个接口的实现类里去做,解耦了Activity和业务逻辑。

package com.example.databindingproject

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class LoginActivity : AppCompatActivity() {

    private lateinit var mLifeListener: LifeListener

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

        mLifeListener = ActivityLifeListener()
    }

    override fun onStart() {
        super.onStart()
        mLifeListener.onStart()
    }

    override fun onResume() {
        super.onResume()
        mLifeListener.onResume()
    }

    override fun onPause() {
        super.onPause()
        mLifeListener.onPause()
    }

    override fun onStop() {
        super.onStop()
        mLifeListener.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        mLifeListener.onDestroy()
    }
}

LifeListener的实现类,关于生命周期要执行的业务逻辑,可以放到这个实现类里。

class ActivityLifeListener : LifeListener {

    companion object {
        const val TAG = "ActivityLifeListener"
    }

    override fun onCreate() {
        Log.i(TAG, "onCreate")
    }

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

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

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

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

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

这种方式的优点就是原理简单,缺点是但仍然需要在Acvitity UI组件类的去显示的调用不同生命周期声明方法,比如仍然需要显示的在Activity的onStart方法里去通过 mLifeListener.onStart() 触发在onStart方法里执行的业务逻辑代码。

1.3 第三种:通过Jetpack 组件的LifeCycles解耦

比如需要感知Activity的声明周期,则可以通过实现DefaultLifecycleObserver接口或者LifecycleObserver接口,然后再在Activity的onCreate生命周期里绑定这个实现类实例,则可以在实现类里对不同生命周期实现自己独立的业务逻辑,并且还不会需要显示的在Activity的其他生命周期显示调用分发了,代码层面

class MainActivity : AppCompatActivity() {

   override fun onCreate(savedInstanceState: Bundle?) {
       // 绑定对应的Observer实现接口
       // DefaultLifecycleObserver实现类方式
       lifecycle.addObserver(LoginLifeCycleObserver())
       // LifecycleEventObserver的实现类 方式
       lifecycle.addObserver(CardLifeCycleObserver())
   }
}

DefaultLifecycleObserver实现类 方式

import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner

class LoginLifeCycleObserver : DefaultLifecycleObserver {

    companion object {
        const val TAG = "LifeCycleListener"
    }

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        Log.i(TAG, "==> onCreate")
    }

    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
        Log.i(TAG, "==> onStart")
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        Log.i(TAG, "==> onResume")
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        Log.i(TAG, "==> onPause")
    }

    override fun onStop(owner: LifecycleOwner) {
        super.onStop(owner)
        Log.i(TAG, "==> onStop")
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        Log.i(TAG, "==> onDestroy")
    }

}

日志打印,业务执行

LifecycleEventObserver的实现类 方式

import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner

class CardLifeCycleObserver : LifecycleEventObserver {

    companion object {
        const val TAG = "CardLifeCycleObserver"
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when(event) {
            Lifecycle.Event.ON_CREATE -> Log.i(TAG, "onStateChanged==> onCreate")
            Lifecycle.Event.ON_START -> Log.i(TAG, "onStateChanged==> onStart")
            Lifecycle.Event.ON_RESUME -> Log.i(TAG, "onStateChanged==> onResume")
            Lifecycle.Event.ON_PAUSE -> Log.i(TAG, "onStateChanged==> onPause")
            Lifecycle.Event.ON_STOP -> Log.i(TAG, "onStateChanged==> onStop")
            Lifecycle.Event.ON_DESTROY -> Log.i(TAG, "onStateChanged==> onDestroy")
            Lifecycle.Event.ON_ANY -> Log.i(TAG, "onStateChanged==> onAny")
        }
    }
}

综上,可以看到第三种会解耦程度最大

二、LifeCycles优点

一句话简述成:Android Lifecycles 的优点是简化了生命周期管理,通过 LifecycleObserver 使生命周期相关的逻辑从 ActivityFragment 中解耦,提高了代码的可维护性和可复用性。

三、LifeCycles使用

Jetpack 为我们提供了两个接口:

  • 被观察者:​​LifecycleOwner​

  • 观察者:​​LifecycleObserver​

被监听的系统组件需要去实现 LifecycleOwner 接口,观察者需要实现 LifecycleObserver 接口。

使用被观察者接口LifecycleOwner

在 AndroidX 里面 ComponentActivity 已经默认实现了 LifecycleOwner 接口。如果项目没有迁移到 AndroidX,还是用的 Support 库,新版本的 SDK 也通过 SupportActivity 实现了 LifecycleOwner 接口。因此我们默认在Activity或者Fragement里是不需要额外去实现LifecycleOwner接口,只需要去实现LifecycleObserver接口即可。

使用观察者接口LifecycleObserver

class LoginLifeCycleObserver : DefaultLifecycleObserver {

    companion object {
        const val TAG = "LifeCycleListener"
    }

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        Log.i(TAG, "==> onCreate")
    }

    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
        Log.i(TAG, "==> onStart")
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        Log.i(TAG, "==> onResume")
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        Log.i(TAG, "==> onPause")
    }

    override fun onStop(owner: LifecycleOwner) {
        super.onStop(owner)
        Log.i(TAG, "==> onStop")
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        Log.i(TAG, "==> onDestroy")
    }

}

然后在需要的Activity里添加这个观察者实现的实例对象

class MainActivity : AppCompatActivity() {

   override fun onCreate(savedInstanceState: Bundle?) {
       // 绑定对应的Observer实现接口
       // DefaultLifecycleObserver实现类方式
       lifecycle.addObserver(LoginLifeCycleObserver())
   }
}

或者在需要的Fragment里添加

class LoginFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val binding = inflater.inflate(R.layout.fragment_login, container, false)

        // 创建生命周期观察者实例
        val lifecycleObserver = LoginLifeCycleObserver()

        // 注册生命周期观察者
        lifecycle.addObserver(lifecycleObserver)

        return binding
    }
}

四、原理

LifeCycles核心思想

本质上是围绕着这两个设计模式进行的:

  • 模板模式 → 定义算法骨架,对外开放扩展点,基于 继承 关系实现,子类重写父类抽象方法;

  • 观察者模式 → 对象间定义一对多的依赖,当一个对象状态发生改变,依赖对象都会自动收到通知;

在探究原理的时候,可以思考下面四个问题:

  • Lifecycle是怎样感知生命周期的?

  • Lifecycle是如何处理生命周期的?

  • LifecycleObserver的方法是怎么回调的呢?

  • 为什么LifecycleObserver可以感知到Activity的生命周期

LifecycleOwner.kt

public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    public val lifecycle: Lifecycle
}

生命周期持有者,返回一个Lifecycle对象,如果你使用的是 AndroidX(也属于 Jetpack 一部分)在这Activity 、Fragment 两个类中,默认实现了 LifecycleOwner 接口

Lifecycle.kt

public abstract class Lifecycle {

    @MainThread
    public abstract fun addObserver(observer: LifecycleObserver)

    @MainThread
    public abstract fun removeObserver(observer: LifecycleObserver)
    
    @get:MainThread
    public abstract val currentState: State

    public enum class Event {
        ON_CREATE,
        ON_START,
        ON_RESUME,
        ON_PAUSE,
        ON_STOP,
        ON_DESTROY,
        ON_ANY;
        public val targetState: State
            get() {
                when (this) {
                    ON_CREATE, ON_STOP -> return State.CREATED
                    ON_START, ON_PAUSE -> return State.STARTED
                    ON_RESUME -> return State.RESUMED
                    ON_DESTROY -> return State.DESTROYED
                    ON_ANY -> {}
                }
                throw IllegalArgumentException("$this has no target state")
            }

        public companion object {
            @JvmStatic
            public fun downFrom(state: State): Event? {
                return when (state) {
                    State.CREATED -> ON_DESTROY
                    State.STARTED -> ON_STOP
                    State.RESUMED -> ON_PAUSE
                    else -> null
                }
            }

            @JvmStatic
            public fun downTo(state: State): Event? {
                return when (state) {
                    State.DESTROYED -> ON_DESTROY
                    State.CREATED -> ON_STOP
                    State.STARTED -> ON_PAUSE
                    else -> null
                }
            }

            @JvmStatic
            public fun upFrom(state: State): Event? {
                return when (state) {
                    State.INITIALIZED -> ON_CREATE
                    State.CREATED -> ON_START
                    State.STARTED -> ON_RESUME
                    else -> null
                }
            }

            @JvmStatic
            public fun upTo(state: State): Event? {
                return when (state) {
                    State.CREATED -> ON_CREATE
                    State.STARTED -> ON_START
                    State.RESUMED -> ON_RESUME
                    else -> null
                }
            }
        }
    }

   
    public enum class State {
        DESTROYED,
        INITIALIZED,
        CREATED,
        STARTED,
        RESUMED;
        public fun isAtLeast(state: State): Boolean {
            return compareTo(state) >= 0
        }
    }
}

在Lifecycle类中定义了添加观察者移除观察者的方法,并定义了两个枚举类Event、State

Event:定一个一些枚举常量,和 Activity、Fragment 的生命周期是一一对应的,可以响应其生命周期,其中多了一个ON_ANY,它是可以匹配任何事件的,Event 的使用是和 LifecycleObserver 配合使用的,

State:当前Lifecycle的自己的目前的状态,它是和Event配合使用的

Event和State之间的关系

如下图

LifecycleRegistry类是对Lifecycle这个抽象类的具体实现,可以处理多个观察者,如果你自定义 LifecycleOwner可以直接使用它。

LifecycleRegistry.kt

open class LifecycleRegistry private constructor(
    provider: LifecycleOwner,
    private val enforceMainThread: Boolean
) : Lifecycle() {

    override fun addObserver(observer: LifecycleObserver) {
        enforceMainThreadIfNeeded("addObserver")
        val initialState = if (state == State.DESTROYED) State.DESTROYED else State.INITIALIZED
        val statefulObserver = ObserverWithState(observer, initialState)
        val previous = observerMap.putIfAbsent(observer, statefulObserver)
        if (previous != null) {
            return
        }
        val lifecycleOwner = lifecycleOwner.get()
            ?: // it is null we should be destroyed. Fallback quickly
            return
        val isReentrance = addingObserverCounter != 0 || handlingEvent
        var targetState = calculateTargetState(observer)
        addingObserverCounter++
        while (statefulObserver.state < targetState && observerMap.contains(observer)
        ) {
            pushParentState(statefulObserver.state)
            val event = Event.upFrom(statefulObserver.state)
                ?: throw IllegalStateException("no event up from ${statefulObserver.state}")
            statefulObserver.dispatchEvent(lifecycleOwner, event)
            popParentState()
            // mState / subling may have been changed recalculate
            targetState = calculateTargetState(observer)
        }
        if (!isReentrance) {
            // we do sync only on the top level.
            sync()
        }
        addingObserverCounter--
    }
    
    override fun removeObserver(observer: LifecycleObserver) {
        enforceMainThreadIfNeeded("removeObserver")
        observerMap.remove(observer)
    }
}

LifecycleObserver

就是一个简单的接口,这个接口只是来标志这个是对Lifecycle的观察者,内部没有任何方法,全部都依赖于DefaultLifecycleObserver

总结:

  • LifecycleOwner:可获取Lifecycle的接口,可以再 Activity、Fragment生命周期改变时,通过LifecycleRegistry类处理对应的生命周期事件,并通知 LifecycleObserver这个观察者

  • Lifecycle:是被观察者,用于存储有关组件(如 Activity 或 Fragment)的生命周期状态的信息,并允许其他对象观察此状态。

  • LifecycleObserver:观察者,可以通过被LifecycleRegistry类通过 addObserver(LifecycleObserver o)方法注册,被注册后,LifecycleObserver便可以观察到LifecycleOwner对应的生命周期事件

  • Lifecycle.Event:分派的生命周期事件。这些事件映射到 Activity 和 Fragment 中的回调事件。

  • Lifecycle.State:Lifecycle组件的当前状态。

4.Lifecycle的源码解析

4.1 分析的入口BaseActivity

在基类BaseActivity中的一行代码就能实现对应生命周期的回调

openclassBaseActivity : AppCompatActivity() {
    overridefunonCreate(savedInstanceState:Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(ActivityLifecycleObserver())//1
    }
}

我们先看下getLifecycle() 方法,然后在看addObserver(ActivityLifecycleObserver())的内容,注意这时候分成两步了,我们先看getLifecycle()

我们点进去这个getLifecycle()方法。

4.2 ComponentActivity 类

然后我们来到了ComponentActivity中,代码如下

public class ComponentActivity extends xxx implements LifecycleOwner,xxx {//1

	private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);//2

	@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ...
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);//4
        ...
        
    }

    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;//3
    }

}

在onCreate方法中有一行代码ReportFragment.injectIfNeededIn(this);

在onCreate方法中,看到初始化了一个ReportFragment,接下来看一下ReportFragment的源码

public class ReportFragment extends Fragment {
	
    @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);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dispatch(Lifecycle.Event.ON_DESTROY);
        // just want to be sure that we won't leak reference to an activity
        mProcessListener = null;
    }

    private void dispatch(Lifecycle.Event event) {
        Activity activity = getActivity();
      	//1
        if (activity instanceof LifecycleRegistryOwner) {
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
            return;
        }
				//2
        if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }
}

可以看到在 ReportFragment 中的各个生命周期都调用了dispatch(Lifecycle.Event event)方法,传递了不同的Event的值,这个就是在Activity、Fragment的各个生命周期回调时,Lifecycle 所要处理的生命周期方法。

在dispatch(Lifecycle.Event event)方法中最终调用了((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);方法

这里可以解答之前的两个问题

1.Lifecycle是怎样感知生命周期的?

就是在ReportFragment中的各个生命周期都调用了dispatch(Lifecycle.Event event)方法,传递了不同的Event的值

2.Lifecycle是如何处理生命周期的?

通过调用了((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);方法,也就是LifecycleRegistry 类来处理这些生命周期。

此时,就应该看 LifecycleRegistry 的handleLifecycleEvent方法中的代码了

查看handleLifecycleEvent方法的实现,根据当前Lifecycle.Event的值,其实也就是 Activity、Fragment 生命周期回调的值,来获取下一个Lifecycle.State的状态,也就是 Lifecycle 将要到什么状态

open fun handleLifecycleEvent(event: Event) {
    enforceMainThreadIfNeeded("handleLifecycleEvent")
    moveToState(event.targetState)
}

private fun moveToState(next: State) {
    // 如果之前的状态和下一个相同,则直接返回
    if (state == next) {
        return
    }
    // 检查状态
    check(!(state == State.INITIALIZED && next == State.DESTROYED)) {
        "no event down from $state in component ${lifecycleOwner.get()}"
    }
    // 当前状态变量被赋值为next的值
    state = next
    // 如果正在处理事件或者已经添加的观察器数量不为0,则标记一下直接返回
    if (handlingEvent || addingObserverCounter != 0) {
        newEventOccurred = true
        // we will figure out what to do on upper level.
        return
    }
    handlingEvent = true
    sync()
    handlingEvent = false
    if (state == State.DESTROYED) {
        observerMap = FastSafeIterableMap()
    }
}

然后看 LifecycleRegistry 的sync方法

LifecycleRegistry.java

private void sync() {
    LifecycleOwnerlifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        thrownewIllegalStateException("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);//1
        }
        Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
        if (!mNewEventOccurred && newest != null
                && mState.compareTo(newest.getValue().mState) > 0) {
            forwardPass(lifecycleOwner);//2
        }
    }
    mNewEventOccurred = false;
}

如果没有同步过,会比较mState当前的状态和mObserverMap中的eldest和newest的状态做对比,看是往前还是往后;比如mState由STARTED到RESUMED是状态向前,反过来就是状态向后。这个是和 Lifecycle 生命周期有关系,但不是一个东西,具体的看上面贴的图,一目了然!

我们发现,无论如何,最终都会走到(ObserverWithState)observer.dispatchEvent(lifecycleOwner, event), 即最终调用LifecycleObserver.onStateChanged(owner, event)

public interface LifecycleEventObserver extends LifecycleObserver {
    void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}

生命周期变化时

  • ActivityThread通知Activity,Activity(无论何种方式)通知 ReportFragment

  • ReportFragment调用 LifecycleRegistry.handleLifecycleEvent(event)

  • LifecycleRegistry经过 moveToState() -> sync() -> backwardPass()/forwardPass() 最终调用ObserverWithState.dispatchEvent()

  • ObserverWithState.dispatchEvent() 调用LifecycleObserver.onStateChanged() 通知 CallbackInfo 通过反射执行对应方法

  • CallbackInfo.invokeCallbacks()查找到对应生命周期的 MethodReference 缓存,通过Method.invoke()调用,最终执行LifecycleObserver中关注对应生命周期的方法。

在来回顾当初抛出的问题

1.Lifecycle是怎样感知生命周期的?

就是在ReportFragment中的各个生命周期都调用了dispatch(Lifecycle.Event event) 方法,传递了不同的Event的值

2.Lifecycle是如何处理生命周期的?

通过调用了((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);方法,也就是LifecycleRegistry 类来处理这些生命周期。

3.LifecycleObserver的方法是怎么回调是的呢?

LifecycleRegistry 的 handleLifecycleEvent方法,然后会通过层层调用最后通过反射到LifecycleObserver方法上的@OnLifecycleEvent(Lifecycle.Event.XXX)注解值,来调用对应的方法

4.为什么LifecycleObserver可以感知到Activity的生命周期
  • ActivityThread产生生命周期事件并通过Instrumentation和Activity传递或调用 Activity.onXXX()

  • Activity创建时(onCreate)会被注入ReportFragment,而ReportFragment负责将生命周期事件分发给对应的Lifecycle

  • API29及以上时,Activity在处理生命周期时会通知 Application 处理生命周期回调且自身也同样处理生命周期回调,API29以上这些回调将会被ReportFragment接收,而API29以下则由FragmentController直接分发给ReportFragment。

五、拓展

比如现在需要实现监听所有Activity的生命周期变化过程的功能,那么如何利用LifeCycles最小改动就能实现这个功能呢?

5.1 创建LifeCycles接口

首先,创建一个 LifeCycles 接口,用于定义需要的生命周期事件方法。

interface LifeCycles {
    fun onActivityCreated(activity: Activity)
    fun onActivityStarted(activity: Activity)
    fun onActivityResumed(activity: Activity)
    fun onActivityPaused(activity: Activity)
    fun onActivityStopped(activity: Activity)
    fun onActivityDestroyed(activity: Activity)
    fun onActivitySaveInstanceState(activity: Activity, outState: Bundle)
}

5.2 创建 LifeCycleObserver 实现 ActivityLifecycleCallbacks

然后,创建一个 LifeCycleObserver 类,它会实现 Application.ActivityLifecycleCallbacks,并调用 LifeCycles 接口的方法。

import android.app.Activity
import android.app.Application
import android.os.Bundle

class LifeCycleObserver(private val lifeCycles: LifeCycles) : Application.ActivityLifecycleCallbacks {

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        lifeCycles.onActivityCreated(activity)
    }

    override fun onActivityResumed(activity: Activity) {
        lifeCycles.onActivityResumed(activity)
    }

    override fun onActivityPaused(activity: Activity) {
        lifeCycles.onActivityPaused(activity)
    }

    override fun onActivityStopped(activity: Activity) {
        lifeCycles.onActivityStopped(activity)
    }

    override fun onActivityDestroyed(activity: Activity) {
        lifeCycles.onActivityDestroyed(activity)
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
        // 可选实现
        lifeCycles.onActivitySaveInstanceState(activity, outState)
    }

    override fun onActivityStarted(activity: Activity) {
        // 可选实现
        lifeCycles.onActivityStarted(activity)
    }
}

5.3 在 Application 类中注册 LifeCycleObserver

Application 类中注册 ActivityLifecycleCallbacks,并传递 LifeCycles 接口的实现。

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.util.Log

class MyApplication : Application() {

    companion object {
        const val TAG = "MyApplication"
    }

    override fun onCreate() {
        super.onCreate()

        // 实现 LifeCycles 接口,处理所有 Activity 生命周期事件
        val lifeCycles = object : LifeCycles {
            override fun onActivityCreated(activity: Activity) {
                // 这里可以监听到 Activity 的 onCreate 事件
                Log.i(TAG, "Activity Created: ${activity.localClassName}")
            }

            override fun onActivityStarted(activity: Activity) {
                // 这里可以监听到 Activity 的 onStart 事件
                Log.i(TAG, "Activity Started: ${activity.localClassName}")
            }

            override fun onActivityResumed(activity: Activity) {
                // 这里可以监听到 Activity 的 onResume 事件
                Log.i(TAG, "Activity Resumed: ${activity.localClassName}")
            }

            override fun onActivityPaused(activity: Activity) {
                // 这里可以监听到 Activity 的 onPause 事件
                Log.i(TAG, "Activity Paused: ${activity.localClassName}")
            }

            override fun onActivityStopped(activity: Activity) {
                // 这里可以监听到 Activity 的 onStop 事件
                Log.i(TAG, "Activity Stopped: ${activity.localClassName}")
            }

            override fun onActivityDestroyed(activity: Activity) {
                // 这里可以监听到 Activity 的 onDestroy 事件
                Log.i(TAG, "Activity Destroyed: ${activity.localClassName}")
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
                Log.i(TAG, "Activity onActivitySaveInstanceState: ${activity.localClassName}")
            }
        }

        // 注册 ActivityLifecycleCallbacks
        val lifeCycleObserver = LifeCycleObserver(lifeCycles)
        registerActivityLifecycleCallbacks(lifeCycleObserver)
    }
}

5.4 在 AndroidManifest.xml 中配置 Application

确保在 AndroidManifest.xml 文件中正确声明了自定义的 Application 类:

 
<application
    android:name=".MyApplication"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.AppCompat.Light">
    <!-- 其他配置 -->
</application>

最后看一下从MainActivity点击一个按钮跳转去LoginAcitivty,这样能够监听到任何Activity的生命周期变化。

参考:

  1. 【掘金】Jetpack 之 LifeCycle 组件使用详解 https://juejin.cn/post/7086763634864422920

  2. 【掘金】【Jetpack】学穿:Lifecycle → 生命周期 (原理篇) https://juejin.cn/post/7071144317636575262

  3. 【Github】Lifecycle基本使用和原理分析

  4. Jetpack之生命周期感知组件-Lifecycle原理篇

;