在Android中获取物理内存信息?

时间:2012-12-06 12:12:55

标签: android memory-management

我正在尝试获取有关物理内存的信息,例如总内存,已用内存和可用内存,而不仅仅是堆。

我在这里搜索过这些问题,但没有找到正确的答案。

我试过这种方式:

long freeSize = 0L;
    long totalSize = 0L;
    long usedSize = 0L;


    try {
        Runtime info = Runtime.getRuntime();
        freeSize = info.freeMemory();
        totalSize = info.totalMemory();
        usedSize = totalSize - freeSize;
    } catch (Exception e) {
        e.printStackTrace();
    }

但是没有获得正确的信息。

我也尝试使用MemoryInfo类。

谢谢!

3 个答案:

答案 0 :(得分:0)

获取当前的RAM:

MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L;

答案 1 :(得分:0)

计算当前正在运行的应用程序的内存使用情况的另一种方法。

public static long getUsedMemorySize() {

    long freeSize = 0L;
    long totalSize = 0L;
    long usedSize = -1L;
    try {
        Runtime info = Runtime.getRuntime();
        freeSize = info.freeMemory();
        totalSize = info.totalMemory();
        usedSize = totalSize - freeSize;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return usedSize;

}

答案 2 :(得分:0)

ActivityManager activityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
            MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
            activityManager.getMemoryInfo(memoryInfo);

            String TAG = "a";
            Log.i(TAG, " memoryInfo.availMem " + memoryInfo.availMem + "\n" );
            Log.i(TAG, " memoryInfo.lowMemory " + memoryInfo.lowMemory + "\n" );
            Log.i(TAG, " memoryInfo.threshold " + memoryInfo.threshold + "\n" );

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