Stack Overflow archive
3 scoreaccepted

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

score
3
question views
6.2K
license
CC BY-SA 3.0

You can use ActivityManager.getRunningServices(int maxNum):

java
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);
}

The documentation states that this is not intended for production. I haven't done much testing with it either. If it doesn't meet your requirements leave a comment. The only other thing I can think of is parsing the output of running ps in a shell.

UPDATE

Parsing the output of ps in a shell we can get the current running apps. Example:

java
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 */
}

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.