我想獲得設備的全部RAM大小。 memoryInfo.getTotalPss()
返回0.在ActivityManager.MemoryInfo
中沒有獲取總RAM大小的函數。如何獲得設備的總RAM大小?
如何做到這一點?
我想獲得設備的全部RAM大小。 memoryInfo.getTotalPss()
返回0.在ActivityManager.MemoryInfo
中沒有獲取總RAM大小的函數。如何獲得設備的總RAM大小?
如何做到這一點?
標準UNIX命令:$ cat /proc/meminfo
注意/proc/meminfo
是一個文件。你實際上並不需要運行cat
,你可以簡單地閱讀文件。
我蘆葦/ proc/meminfo文件,並收到RAM的大小。 – BOOMik
回到原答覆的答案。雖然Leon發佈了一些在後來的API級別中可用的東西,但這並不意味着這種方法不再適用。第三方編輯不應該用來評論答案 - 這是評論的角色,或者在這種情況下,Leon自己的答案。 –
此外,我將添加從設備上運行的代碼,沒有理由運行'cat'進程 - 相反,只需從java或本機代碼讀取'/ proc/meminfo'就好像它是一個文本文件。只有當你在一個shell中工作時,纔會需要貓,或者訪問某些需要你在不同的用戶標識下使用被攻擊的'su'啓動一個進程的東西。 –
從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。
我可以得到可用的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
您可以通過使用此代碼得到總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.
您的語法代碼和方法在java中不是正確的。你的代碼是C#還是xamarin? – amin
是的,我發佈它只是爲了有一個基地。 –
'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
我爲此寫入了函數。 ^^^回答^^^ – BOOMik