Cannot get foreground activity name in Android Lollipop 5.0 only

前端 未结 7 2036
旧巷少年郎
旧巷少年郎 2020-12-02 16:02

I use the following code to get the activity name of the foreground app in the variable foregroundTaskPackageName. It works on all OS versions between 4.1 t

7条回答
  •  無奈伤痛
    2020-12-02 16:57

    Try this

    public static boolean isForeground(Context context) {
        ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List tasks = manager.getRunningAppProcesses();
        if(tasks.isEmpty())
            return false;
    
        for (ActivityManager.RunningAppProcessInfo task : tasks) {
            if(context.getPackageName().equalsIgnoreCase(task.processName)){
                return task.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
            }
        }
        return false;
    }
    

提交回复
热议问题