Checking if an Android application is running in the background

前端 未结 30 2896
无人共我
无人共我 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 06:59

    This code will check foreground and background in any condition:

    Java Code:

    private static boolean isApplicationForeground(Context context) {
        KeyguardManager keyguardManager =
                (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
    
        if (keyguardManager.isKeyguardLocked()) {
            return false;
        }
        int myPid = Process.myPid();
    
        ActivityManager activityManager =
                (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    
        List list;
    
        if ((list = activityManager.getRunningAppProcesses()) != null) {
            for (ActivityManager.RunningAppProcessInfo aList : list) {
                ActivityManager.RunningAppProcessInfo info;
                if ((info = aList).pid == myPid) {
                    return info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
                }
            }
        }
        return false;
    }
    

    Kotlin Code:

    private fun isApplicationForeground(context: Context): Boolean {
            val keyguardManager = context.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
            if (keyguardManager.isKeyguardLocked) {
                return false
            }
            val myPid = Process.myPid()
            val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            var list: List
            if (activityManager.runningAppProcesses.also { list = it } != null) {
                for (aList in list) {
                    var info: ActivityManager.RunningAppProcessInfo
                    if (aList.also { info = it }.pid == myPid) {
                        return info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                    }
                }
            }
            return false
        }
    

提交回复
热议问题