获取最上方应用包名

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/github_36617621/article/details/78961528
    /**
     * 获取在最上方的应用包名
     *
     * @param context
     * @return
     */
    public static String getPackageNameOnTop(Context context) {
        Log.i(TAG, "getPackageName()");
        String result;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            result = runningProcesses.get(0).processName;
            Log.i(TAG, "Build.VERSION.SDK_INT = " + Build.VERSION.SDK_INT + " runningProcesses.size() = " +
                    runningProcesses.size());
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                // 前台程序
//              if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        Log.e(TAG, "在前台的应用名 = " + activeProcess);
                    } else {
                        Log.w(TAG, "在后台的应用名 = " + activeProcess);
                    }
                }
//              }
            }
        } else {
            Log.i(TAG, "Build.VERSION.SDK_INT = " + Build.VERSION.SDK_INT);
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            result = componentInfo.getPackageName();
        }

        return result;
    }
展开阅读全文

没有更多推荐了,返回首页