如何判断APP在前台还是后台?

开发 前端
当我们不管是点击Back键还是Home键都会回调到onStop方法,我们在onStart和onStop中分别对mCount值做了加减,这样我们可以通过该数值来判断当前App是前台还是后台。

如何判断一个APP在前台还是后台?可以通过RunningTasks,RunningProcess 以及ActivityLifecycleCallback判定。

RunningTasks方式

注意:getRunningTask方法在5.0以上已经被废弃,只能返回自己和系统的一些不敏感的task,不再返回其他应用的task,用此方法来判断自身App是否处于后台是有效的,但是无法判断其他应用是否处于前台。

private fun getTopApplication() {

    //首先获取到ActivityManager
    val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager

    if (activityManager.getRunningTasks(1) == null){
        Log.e(TAG, "getForegroundActivity: ")
        return
    }

    var runningTaskInfo = activityManager.getRunningTasks(1)[0]
    if (runningTaskInfo == null) {
        Log.e(TAG, "runningTaskInfo is null")
        return
    }

    runningTaskInfo.topActivity?.let {
        Log.e(TAG, "top application is ${it.packageName}")
    }
}

RunningProcess方式

注意:RunningProcess方法在5.0以上已经被废弃,例如,在聊天类型的App中,大部分时间需要常驻后台来不间断地获取服务器的消息,就必须把Service设置成START_STICKY,kill后会被重启(等待5s左右)来保证Service常驻后台。如果Service设置了这个属性,这个App的进程就可以判断为前台。

appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
private fun isAppForeground(): Boolean {
    val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    var runningAppProcesses = activityManager.runningAppProcesses

    if (runningAppProcesses == null) {
        Log.e(TAG, "runningAppProcesses is null")
        return false
    }

    runningAppProcesses.forEach {
        if (it.processName == packageName && (it.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)) {
            return true
        }
    }
    return false
}

ActivityLifecycleCallbacks方式

class MyActivityLifecycleCallbacks(
    var onActivityCreatedAction: ((Activity, Bundle?) -> Unit)? = null,
    var onActivityStartedAction: ((Activity) -> Unit)? = null,
    var onActivityResumedAction: ((Activity) -> Unit)? = null,
    var onActivityPausedAction: ((Activity) -> Unit)? = null,
    var onActivityStoppedAction: ((Activity) -> Unit)? = null,
    var onActivitySaveInstanceStateAction: ((Activity, Bundle) -> Unit)? = null,
    var onActivityDestroyedAction: ((Activity) -> Unit)? = null

) : Application.ActivityLifecycleCallbacks {

    private var mCount=0
    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        onActivityCreatedAction?.invoke(activity, savedInstanceState)
    }

    override fun onActivityStarted(activity: Activity) {
        mCount++
        onActivityStartedAction?.invoke(activity)
    }

    override fun onActivityResumed(activity: Activity) {
        onActivityResumedAction?.invoke(activity)
    }

    override fun onActivityPaused(activity: Activity) {
        onActivityPausedAction?.invoke(activity)
    }

    override fun onActivityStopped(activity: Activity) {
        mCount--
        onActivityStoppedAction?.invoke(activity)
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
        onActivitySaveInstanceStateAction?.invoke(activity, outState)
    }

    override fun onActivityDestroyed(activity: Activity) {
        onActivityDestroyedAction?.invoke(activity)
    }

    /**
     * 这里我们把mCount的实际数值返回回去
     */
    fun getCount():Int = mCount
}

这里我们对ActivityLifecycleCallbacks的实现类做了一层封装,利用Kotlin的高阶函数,当我们需要去实现那个声明周期的回调的时候,就通过高阶函数来提供回调处理,否则默认不做任何处理。然后我们在Application的onCreate中进行注册:

class LifeApplication : Application() {

    private val TAG = "LifeApplication"

    private val mActivityLifecycleCallbacks by lazy {
        MyActivityLifecycleCallbacks(
            onActivityCreatedAction = { activit, bundle ->
            Log.e(TAG, "onCreate: ")
        },
        onActivityStoppedAction = { activity ->
            Log.e(TAG, "onStop ")
        },
        onActivityDestroyedAction = { activity ->
            Log.e(TAG, "onDestroy")
        })
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        //注册生命周期回调事件
        registerActivityLifecycleCallbacks(mActivityLifecycleCallbacks)
    }

    /**
     * 用于判断当前进程是否处于前台
     */
    fun isForegroundMethod(): Boolean = mActivityLifecycleCallbacks.getCount() > 0

    companion object{
        private var instance :LifeApplication?= null
        fun getInstance () = instance!!
    }

当我们不管是点击Back键还是Home键都会回调到onStop方法,我们在onStart和onStop中分别对mCount值做了加减,这样我们可以通过该数值来判断当前App是前台还是后台。

责任编辑:武晓燕 来源: 沐雨花飞蝶
相关推荐

2009-08-26 18:11:52

前台与后台方法互调

2018-01-16 16:32:12

架构前台后台

2014-07-31 12:07:15

Linux

2015-06-24 10:06:09

iOS 9适配后台

2019-06-14 15:48:39

Windows 10硬盘SSD

2020-11-19 10:03:37

前台中台后台

2014-07-11 11:09:10

App应用程序生命周期

2009-08-21 09:09:05

C#字符串

2021-02-04 11:59:10

硬盘SSD数据

2018-09-12 21:25:15

iOSAppcrash

2017-01-15 20:58:04

Linux进程作业管理

2014-06-26 14:10:44

2012-12-24 13:25:59

微信App

2023-10-30 07:13:56

2022-09-19 13:21:15

Linux进程

2015-10-12 16:37:39

前端编码双向编译

2011-06-14 09:37:52

AppiCloud苹果

2017-10-24 13:42:55

流氓App安卓Google

2010-04-16 18:23:43

Unix操作系统
点赞
收藏

51CTO技术栈公众号