2012-12-06 19 views
0

我試圖獲取有關物理內存的信息,如總內存,已用內存和可用內存,而不僅僅是堆。在Android中獲取物理內存信息?

我在這裏搜索了這樣的問題,但沒有找到正確的答案。

我已經試過這樣:

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類。

謝謝!

+0

@Have你答? –

回答

0

獲得當前RAM:

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

是的,我用這種方式,但它只給我可用的內存。我也想找出總內存。 – Seishin

+0

看到我的新答案 –

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; 

} 
+0

是的,它與上面提供的示例幾乎相同。但問題不在於當前正在運行的應用程序的使用情況。我想知道手機RAM的總大小以及當前使用的和可用的RAM的大小。 謝謝你的樣品! :) – Seishin

+0

以上代碼無法正常工作? –

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