由于工作需要,研究了一下android上获取内存信息的方法,总结如下:
1.SDK获取
在Java层利用API获取很简单,直接使用ActivityManager.MemoryInfo类即可,代码如下:
ActivityManager activityManager=(ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); ActivityManager.MemoryInfo memInfo=new ActivityManager.MemoryInfo(); activityManager.getMemoryInfo(memInfo); Log.v("memInfo", "availMem:"+memInfo.availMem/1024+" kb"); Log.v("memInfo", "threshold:"+memInfo.threshold/1024+" kb");//low memory threshold Log.v("memInfo", "totalMem:"+memInfo.totalMem/1024+" kb"); Log.v("memInfo", "lowMemory:"+memInfo.lowMemory); //if current is in low memory
2.NDK获取
在native层获取内存信息Java层比较不同,android没有提供相应的API(我没有找到,如果有高手找到了,欢迎留言)。考虑到android系统是基于linux系统修改的,因此有一个/proc/meminfo文件用于存储当前的内存信息。这个文件里存储的内容很多,在PC上执行adb shell命令后,输入cat /proc/meminfo,会显示如下信息:
一般我们只对可用内存和总内存感兴趣,参考网上的代码自己封装了两个函数如下,如果要获取其他信息,以此类推即可,代码如下:
//get the available memory in kb, return -1 if get failed long getAvailMem() { signed long availMem=-1; int memInfoFile = open("/proc/meminfo", O_RDONLY); if (memInfoFile < 0) {return availMem;} char buffer[256]; const int len = read(memInfoFile, buffer, sizeof(buffer)-1); close(memInfoFile); if (len < 0) {return availMem;} buffer[len] = 0; int numFound = 0; static const char* const sums[] = { "MemFree:", "Cached:", NULL }; static const int sumsLen[] = { strlen("MemFree:"), strlen("Cached:"), 0 }; char* p = buffer; while (*p && numFound < 2) { int i = 0; while (sums[i]) { if (strncmp(p, sums[i], sumsLen[i]) == 0) { p += sumsLen[i]; while (*p == ‘ ‘) p++; char* num = p; while (*p >= ‘0‘ && *p <= ‘9‘) p++; if (*p != 0) { *p = 0; p++; if (*p == 0) p--; } availMem += atoll(num); numFound++; break; } i++; } p++; } return availMem; } //get the total memory in kb, return -1 if get failed long getTotalMem() { signed long totalMem=-1; int memInfoFile = open("/proc/meminfo", O_RDONLY); if (memInfoFile < 0) {return totalMem;} char buffer[256]; const int len = read(memInfoFile, buffer, sizeof(buffer)-1); close(memInfoFile); if (len < 0) {return totalMem;} buffer[len] = 0; static const char* const sums[] = { "MemTotal:", NULL }; static const int sumsLen[] = { strlen("MemTotal:"), 0 }; char* p = buffer; while (*p ) { int i = 0; while (sums[i]) { if (strncmp(p, sums[i], sumsLen[i]) == 0) { p += sumsLen[i]; while (*p == ‘ ‘) p++; char* num = p; while (*p >= ‘0‘ && *p <= ‘9‘) p++; if (*p != 0) { *p = 0; p++; if (*p == 0) p--; } totalMem += atoll(num); break; } i++; } p++; } return totalMem; }
解释一下可用内存availMem为什么是MemFree和Cached的总和,MemFree指的是完全未被使用的内存,Cached指的是,当你读写文件的时候,Linux内核为了提高读写性能与速度,会将文件在内存中进行缓存,也就是Cache Memory(缓存内存)。即使你的程序运行结束后,Cache Memory也不会自动释放。这就会导致你在Linux系统中程序频繁读写文件后,你会发现可用物理内存会很少。其实这缓存内存(Cache Memory)在你需要使用内存的时候会自动释放,所以你不必担心没有内存可用。因此可用内存availMem=MemFree+Cached
3.参考资料
http://blog.chinaunix.net/uid-9465077-id-270364.html
http://www.xuebuyuan.com/1878297.html
http://www.ha97.com/4337.html
http://developer.android.com/intl/zh-cn/reference/android/app/ActivityManager.MemoryInfo.html