我正在开发一个应用程序,我需要在其中显示总内存和可用内存。我正在使用以下代码段;但是,它仅适用于API 16或更高版本。我需要适用于所有Android版本的东西。
我的问题不同于可能的重复"我的问题是在所有API级别上获得的内存使用率。
private void getAvailableRam() {
MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L;
ttvv.setText(availableMegs + " MB");
}
private void getTotalRamSize() {
MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long totalMemory = mi.totalMem / 1048576L;
ttvv2.setText(totalMemory + " MB");
}
答案 0 :(得分:1)
文件“/ proc / meminfo”是实时内存信息。 你可以在你的代码中阅读它
adb shell cat /proc/meminfo
MemTotal: 1900556 kB
MemFree: 343468 kB
Buffers: 97708 kB
Cached: 659364 kB
SwapCached: 0 kB
Active: 784552 kB
Inactive: 358336 kB
Active(anon): 394596 kB
Inactive(anon): 364 kB
Active(file): 389956 kB
Inactive(file): 357972 kB
Unevictable: 1396 kB
Mlocked: 0 kB
HighTotal: 1158144 kB
HighFree: 52088 kB
LowTotal: 742412 kB
LowFree: 291380 kB
SwapTotal: 0 kB
SwapFree: 0 kB
Dirty: 0 kB
Writeback: 0 kB
AnonPages: 394552 kB
Mapped: 176752 kB
Shmem: 452 kB
Slab: 48296 kB
SReclaimable: 21808 kB
SUnreclaim: 26488 kB
KernelStack: 9632 kB
PageTables: 19276 kB
NFS_Unstable: 0 kB
Bounce: 0 kB
WritebackTmp: 0 kB
CommitLimit: 950276 kB
Committed_AS: 47222076 kB
VmallocTotal: 245760 kB
VmallocUsed: 79036 kB
VmallocChunk: 75648 kB
答案 1 :(得分:1)
获取可用内存
您可以使用相同的mi.availMem,因为min API级别为1
使总内存低于API级别16
试试这个
public class MainActivity extends AppCompatActivity {
TextView ttvv2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ttvv2 = (TextView) findViewById(R.id.ttvv2);
ttvv2.setText(getTotalRAM());
}
private String getTotalRAM() {
RandomAccessFile reader = null;
String load = null;
long total = 0;
try {
reader = new RandomAccessFile("/proc/meminfo", "r");
load = reader.readLine().replaceAll("\\D+","");;
total = Integer.parseInt(load)/1024;
}catch (IOException ex) {
ex.printStackTrace();
}
return total+" MB";
}
}
希望这会有所帮助。问候。
来源:
1)http://developer.android.com/reference/android/app/ActivityManager.MemoryInfo.html