我尝试使用建议的here的dalvikPss值查找每个正在运行的应用程序和服务的相对内存使用情况

如此处所建议,我需要总结所有正在运行的进程的PSS值。我的问题是,如何获取所有正在运行的进程的pss值?

我的理解是,Android中的服务和任务与流程相关联。这种理解正确吗?

如果是这样,将来自ActivityManager.getRunningAppProcesses返回的所有进程的PSS值相加会得出所有正在运行的进程(包括服务和任务)的总PSS吗?

最佳答案

获取所有正在运行的进程的PSS值:
用这个:

ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
Map<Integer, String> pidMap = new TreeMap<Integer, String>();
for (RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses)
{
    pidMap.put(runningAppProcessInfo.pid, runningAppProcessInfo.processName);
}
Collection<Integer> keys = pidMap.keySet();
for(int key : keys)
{
    int pids[] = new int[1];
    pids[0] = key;
    android.os.Debug.MemoryInfo[] memoryInfoArray = activityManager.getProcessMemoryInfo(pids);
    for(android.os.Debug.MemoryInfo pidMemoryInfo: memoryInfoArray)
    {
        Log.i(TAG, String.format("** MEMINFO in pid %d [%s] **\n",pids[0],pidMap.get(pids[0])));
        Log.i(TAG, " pidMemoryInfo.getTotalPrivateDirty(): " + pidMemoryInfo.getTotalPrivateDirty() + "\n");
        Log.i(TAG, " pidMemoryInfo.getTotalPss(): " + pidMemoryInfo.getTotalPss() + "\n");
        Log.i(TAG, " pidMemoryInfo.getTotalSharedDirty(): " + pidMemoryInfo.getTotalSharedDirty() + "\n");
    }
}


或者,您也可以使用运行时获取PSS值:

    final Process m_process = Runtime.getRuntime().exec("/system/bin/top -n 1");
    final StringBuilder sbread = new StringBuilder();
    BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(m_process.getInputStream()), 8192);

10-08 17:06