转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/117988239
本文出自【赵彦军的博客】
方案一:利用ActivityLifecycleCallbacks监听所有activity的生命周期
import android.app.Activity
import android.app.Application
import android.os.Bundle
/**
* @author : zhaoyanjun
* @time : 2021/6/16
* @desc : APP前后台监听
*/
class ForegroundCallbacks(val mOnAppStatusListener: OnAppStatusListener?) :
Application.ActivityLifecycleCallbacks {
private var activityStartCount = 0
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
}
override fun onActivityStarted(activity: Activity) {
activityStartCount++
//数值从0变到1说明是从后台切到前台
if (activityStartCount == 1) {
//从后台切到前台
mOnAppStatusListener?.onBecameForeground()
}
}
override fun onActivityResumed(activity: Activity) {
}
override fun onActivityPaused(activity: Activity) {
}
override fun onActivityStopped(activity: Activity) {
activityStartCount--;
//数值从1到0说明是从前台切到后台
if (activityStartCount == 0) {
//从前台切到后台
mOnAppStatusListener?.onBecameBackground()
}
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
}
override fun onActivityDestroyed(activity: Activity) {
}
interface OnAppStatusListener {
fun onBecameForeground()
fun onBecameBackground()
}
}
使用
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(ForegroundCallbacks(object :
ForegroundCallbacks.OnAppStatusListener {
override fun onBecameForeground() {
//进入前台
}
override fun onBecameBackground() {
//进入后台
}
}))
}
}
方案二:ProcessLifecycleOwner
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get().lifecycle.addObserver(object : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
private fun onAppBackground() {
// 应用进入后台
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
private fun onAppForeground() {
// 应用进入前台
}
})
}
}