Android ProcessLifecycleOwner

Android ProcessLifecycleOwner

  • 针对整个应用程序生命周期的监听,和activity数量没有关系
  • onCreate只会调用一次,onDestory不会调用

实现 DefaultLifecycleObserver

kotlin 复制代码
class ApplicationObserver : DefaultLifecycleObserver {

    companion object{
        const val TAG ="ApplicationObserver"
    }
    
    override fun onCreate(owner: LifecycleOwner) {
        Log.i(TAG,"onCreate")
    }

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

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

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

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

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

在Application中添加

kotlin 复制代码
class MyApplication : Application() {

    override fun onCreate() {
        super.onCreate()
        ProcessLifecycleOwner.get().lifecycle
            .addObserver(ApplicationObserver())
    }
}

通过日志观察,在应用启动会调用 onCreate 方法,退出后台或者kill进程,不会调用 onDestory 方法

相关推荐
2501_9400940219 小时前
NDS模拟器安卓版 melonDS模拟器 汉化中文版 NDS BIOS和固件+NDS游戏和详细的使用教程
android·游戏
枫子有风1 天前
Go语言流程控制
android·java·golang
杨筱毅1 天前
【底层机制】ART虚拟机深度解析:Android运行时的架构革命
android·架构·底层机制
某空m1 天前
【Android】活动的生命周期、启动模式及标记位
android
WAsbry1 天前
InputConnection机制与跨进程文本操作的工程实践
android·linux
WAsbry1 天前
Android输入法框架的Binder通信机制剖析
android
WAsbry1 天前
从一个Bug看Android文本编辑的设计缺陷
android·linux
沐怡旸1 天前
【底层机制】Android低内存管理机制深度解析
android
wuwu_q1 天前
用通俗易懂 + Android 开发实战的方式讲解 Kotlin Flow 中的 filter 操作符
android·开发语言·kotlin
stevenzqzq1 天前
Android Hilt 入门教程_注解汇总
android