Android 判断应用是否处于后台
以前的方案
通过lifecycle监控,每次打开一个Activity则加1,每次关闭一个Activity则减1
根据统计的数值是否为0,判断当前App是否处于前台/后台
更简洁的方案
ProcessLifecycleOwner.get().lifecycle.addObserver(object : LifecycleEventObserver { override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { when (event) { Lifecycle.Event.ON_START -> _isForeground = true // 处于前台 Lifecycle.Event.ON_STOP -> _isForeground = false // 处于后台 else -> Unit } } })
来自:androidx.lifecycle:lifecycle-process:xxx
参考资料
- https://blog.csdn.net/awy1988/article/details/99431616
- 遇到的实例