Android 监听APP进入前台、后台

转载请标明出处: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() {
                // 应用进入前台
            }
        })
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值