2011-09-10 34 views
17

我想獲得設備的全部RAM大小。 memoryInfo.getTotalPss()返回0.在ActivityManager.MemoryInfo中沒有獲取總RAM大小的函數。如何獲得設備的總RAM大小?

如何做到這一點?

+1

'public static synchronized int readTotalRam(){ \t \t int tm = 1000; \t try { \t RandomAccessFile reader = new RandomAccessFile(「/ proc/meminfo」,「r」); \t String load = reader.readLine(); \t String [] totrm = load.split(「kB」); \t String [] trm = totrm [0] .split(「」); \t tm = Integer.parseInt(trm [trm.length-1]); \t tm = Math.round(tm/1024); (IOException,ex){ \t ex.printStackTrace(); \t} \t return tm; \t}' – BOOMik

+1

我爲此寫入了函數。 ^^^回答^^^ – BOOMik

回答

19

標準UNIX命令:$ cat /proc/meminfo

注意/proc/meminfo是一個文件。你實際上並不需要運行cat,你可以簡單地閱讀文件。

+0

我蘆葦/ proc/meminfo文件,並收到RAM的大小。 – BOOMik

+0

回到原答覆的答案。雖然Leon發佈了一些在後來的API級別中可用的東西,但這並不意味着這種方法不再適用。第三方編輯不應該用來評論答案 - 這是評論的角色,或者在這種情況下,Leon自己的答案。 –

+0

此外,我將添加從設備上運行的代碼,沒有理由運行'cat'進程 - 相反,只需從java或本機代碼讀取'/ proc/meminfo'就好像它是一個文本文件。只有當你在一個shell中工作時,纔會需要貓,或者訪問某些需要你在不同的用戶標識下使用被攻擊的'su'啓動一個進程的東西。 –

25

從API級別16開始,您現在可以使用MemoryInfo類的totalMem屬性。

像這樣:

ActivityManager actManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 
ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo(); 
actManager.getMemoryInfo(memInfo); 
long totalMemory = memInfo.totalMem; 

API級15和下仍然需要使用unix命令如圖cweiske's answer

15

我可以得到可用的RAM內存以這樣的方式

public String getTotalRAM() { 

    RandomAccessFile reader = null; 
    String load = null; 
    DecimalFormat twoDecimalForm = new DecimalFormat("#.##"); 
    double totRam = 0; 
    String lastValue = ""; 
    try { 
     reader = new RandomAccessFile("/proc/meminfo", "r"); 
     load = reader.readLine(); 

     // Get the Number value from the string 
     Pattern p = Pattern.compile("(\\d+)"); 
     Matcher m = p.matcher(load); 
     String value = ""; 
     while (m.find()) { 
      value = m.group(1); 
      // System.out.println("Ram : " + value); 
     } 
     reader.close(); 

     totRam = Double.parseDouble(value); 
     // totRam = totRam/1024; 

     double mb = totRam/1024.0; 
     double gb = totRam/1048576.0; 
     double tb = totRam/1073741824.0; 

     if (tb > 1) { 
      lastValue = twoDecimalForm.format(tb).concat(" TB"); 
     } else if (gb > 1) { 
      lastValue = twoDecimalForm.format(gb).concat(" GB"); 
     } else if (mb > 1) { 
      lastValue = twoDecimalForm.format(mb).concat(" MB"); 
     } else { 
      lastValue = twoDecimalForm.format(totRam).concat(" KB"); 
     } 



    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } finally { 
     // Streams.close(reader); 
    } 

    return lastValue; 
} 

經測試高達安卓4.3三星S3

2

您可以通過使用此代碼得到總RAM大小:

var activityManager = GetSystemService(Activity.ActivityService) as ActivityManager; 
var memoryInfo = new ActivityManager.MemoryInfo(); 
activityManager.GetMemoryInfo(memoryInfo); 

var totalRam = memoryInfo.TotalMem/(1024 * 1024);

如果設備有1GB RAM,totalRam將爲1000.

+0

您的語法代碼和方法在java中不是正確的。你的代碼是C#還是xamarin? – amin

+0

是的,我發佈它只是爲了有一個基地。 –