有没有人知道如何使用C ++找到Android应用程序的内存使用情况,因为我无法使用Java获得正确的结果。我知道如何找到总内部存储器的两种方法。 首先是:
//Total Memory
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return formatSize(totalBlocks * blockSize);
public static String formatSize(long size) {
String suffix = null;
Long l = new Long(size);
double sizeD = l.doubleValue();
if (sizeD >= 1024) {
suffix = "KB";
sizeD /= 1024;
if (sizeD >= 1024) {
suffix = "MB";
sizeD /= 1024;
if (sizeD > 1024){
sizeD /= 1024;
suffix = "GB";
}
}
}
//size = (long)sizeD;
//return roundDouble(sizeD, 10) + suffix;
StringBuilder resultBuffer = new StringBuilder(Long.toString(size));
int commaOffset = resultBuffer.length() - 3;
while (commaOffset > 0) {
resultBuffer.insert(commaOffset, ',');
commaOffset -= 3;
}
if (suffix != null) resultBuffer.append(suffix);
return resultBuffer.toString();
}
第二是:
public long InternalTotalMemory(){
StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());
long blockCount = statFs.getBlockCountLong();
long blockSize = statFs.getBlockSizeLong();
long total = blockCount * blockSize;
return total;
}
public static String BytesLongToString(long size){
double KB = 1 * 1024;
double MB = KB * 1024;
double GB = MB * 1024;
double TB = GB * 1024;
String memorySize = "";
if (size < KB){
memorySize = floatForm(size) + " byte";
} else if (size >= KB && size < MB){
memorySize = floatForm((double)size / KB) + " KB";
} else if (size >= MB && size < GB){
memorySize = floatForm((double)size / MB) + " MB";
} else if (size >= GB && size < TB){
memorySize = floatForm((double)size / GB) + " GB";
}
return memorySize;
}
public static String floatForm (double d)
{
return new DecimalFormat("#.###").format(d);
}
我不明白为什么两个函数结果不同或格式错误之一?
答案 0 :(得分:0)
Android是Linux,因此您可以使用/proc/$PID/maps
(see here)之类的内容。
来自here的示例:
void show_mappings(void)
{
DLOG("-----------------------------------------------\n");
int a;
FILE *f = fopen("/proc/self/maps", "r");
struct buffer* b = _new_buffer(1024);
while ((a = fgetc(f)) >= 0) {
if (_buf_putchar(b,a) || a == '\n') {
DLOG("/proc/self/maps: %s",_buf_reset(b));
}
}
if (b->pos) {
DLOG("/proc/self/maps: %s",_buf_reset(b));
}
free(b);
fclose(f);
DLOG("-----------------------------------------------\n");
}
(该文件的目的是知道内存地址,找出内存保护属性,在同一file中查看read_mprotection(void* addr)
。)