1

我是 Android 新手,我正在尝试制作一个允许用户查看正在运行的应用程序的项目。我使用此代码在顶部获取正在运行的任务的包名:

           if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                List<ActivityManager.RunningAppProcessInfo> runningappInfo = activityManager.getRunningAppProcesses();
                for (ActivityManager.RunningAppProcessInfo app : runningappInfo) {
                    if (app.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && app.importanceReasonCode == 0) {
                        Integer state = null;
                        try {
                            state = field.getInt(app);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                        if (state != null && state == PROCESS_STATE_TOP) {
                            currentInfo = app;
                            break;
                        }
                    }
                }
               if (currentInfo != null) {
                    current = currentInfo.processName.split(":")[0];
                }
           }else{
                List<ActivityManager.RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(1);
                ComponentName componentInfo = runningTaskInfos.get(0).topActivity;
                current = componentInfo.getPackageName();
           }

current这是运行任务的包名。但是在 Google 更新了新的 android 版本 Lollipop5.1.1 之后,这段代码就不再起作用了。方法“getRunningAppProcesses”现在返回一个空列表。我现在卡住了,因为我的项目中的所有其他功能只有在我可以获得 runningtask 的包名时才能工作。如果有人解决了这种问题,你能帮帮我吗?非常感谢,

4

1 回答 1

1

https://code.google.com/p/android-developer-preview/issues/detail?id=2347

Android 建议使用它来查找顶级应用程序。 https://developer.android.com/reference/android/app/usage/UsageStatsManager.html

于 2015-09-03T09:49:29.020 回答