Checking if an Android application is running in the background

前端 未结 30 2791
无人共我
无人共我 2020-11-21 06:19

By background, I mean none of the application\'s activities are currently visible to the user?

30条回答
  •  走了就别回头了
    2020-11-21 07:06

    fun isAppInForeground(): Boolean {
        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager ?: return false
    
        val appProcesses = activityManager.runningAppProcesses ?: return false
    
        val packageName = packageName
        for (appProcess in appProcesses) {
            if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName == packageName) {
                return true
            }
        }
    
        return false
    }
    

提交回复
热议问题