Android M:如何获取所有进程的UID?

Android M: How to get all processes UID's?

我有一个应用程序使用 traffic stats API 查看哪些 运行 进程正在使用网络。

我以前是通过getRunningAppProcesses()方法得到uid来实现的。显然这已在 Android M 中更改为仅 return 您的应用程序包名称,如 here 所示。

我的问题是:是否有另一种方法可以获取 Android M 中每个 运行 进程的名称 UID?

这是我之前如何执行此操作的示例,我想在 Android M 上重新创建此功能。

List<RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();

PackageManager pm = context.getPackageManager();
for (int i = 0; i < procInfos.size(); i++) {
    try {
        String packageName = procInfos.get(i).processName;
        String appName = "";
        try {
            appName = pm.getApplicationLabel(
                    pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA))
                        .toString();
        } catch (NameNotFoundException e) {
            appName = "";
        }

        int uid = procInfos.get(i).uid;
        long ulBytes = TrafficStats.getUidTxBytes(uid);
        long dlBytes = TrafficStats.getUidRxBytes(uid);
        // Do other stuff.

非常感谢任何帮助。谢谢!

您可以使用 ActivityManager.getRunningServices(int maxNum):

PackageManager pm = context.getPackageManager();
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> runningServices = am.getRunningServices(Integer.MAX_VALUE);
for (ActivityManager.RunningServiceInfo service : runningServices) {
    String appName;
    try {
        appName = pm.getApplicationInfo(service.process, 0).loadLabel(pm).toString();
    } catch (PackageManager.NameNotFoundException e) {
        appName = null;
    }

    int uid = service.uid;

    long ulBytes = TrafficStats.getUidTxBytes(uid);
    long dlBytes = TrafficStats.getUidRxBytes(uid);
}

文档指出这不适用于生产。我也没有对它进行太多测试。如果它不符合您的要求,请发表评论。我唯一能想到的另一件事是在 shell.

中解析 运行 ps 的输出

更新

在 shell 中解析 ps 的输出,我们可以获得当前的 运行 个应用程序。示例:

PackageManager pm = context.getPackageManager();
// Get the output of running "ps" in a shell.
// This uses libsuperuser: https://github.com/Chainfire/libsuperuser
// To add this to your project: compile 'eu.chainfire:libsuperuser:1.0.0.+'
List<String> stdout = Shell.SH.run("ps");
List<String> packages = new ArrayList<>();
for (String line : stdout) {
    // Get the process-name. It is the last column.
    String[] arr = line.split("\s+");
    String processName = arr[arr.length - 1].split(":")[0];
    packages.add(processName);
}

// Get a list of all installed apps on the device.
List<ApplicationInfo> apps = pm.getInstalledApplications(0);

// Remove apps which are not running.
for (Iterator<ApplicationInfo> it = apps.iterator(); it.hasNext(); ) {
    if (!packages.contains(it.next().packageName)) {
        it.remove();
    }
}

for (ApplicationInfo app : apps) {
    String appName = app.loadLabel(pm).toString();
    int uid = app.uid;
    long ulBytes = TrafficStats.getUidTxBytes(uid);
    long dlBytes = TrafficStats.getUidRxBytes(uid);
    /* do your stuff */
}