如何检测一个Android应用程序的堆大小使用应用程序、大小、Android

2023-09-12 07:09:02 作者:十里故清欢

我想知道两种方式使用我的Andr​​oid应用程序堆栈空间的大小: - 编程   - 通过DDMS

I would like to know the amount of heap space used by my android application in two ways: - programmatically - through DDMS.

我已经提到这个的帖子,张贴在这里之前。在该职位中,提及的是, Debug.getNativeHeapSize()返回堆大小。这是我应该使用,以编程方式检测堆大小确切的方法?如果是这样,我应该在哪里才能得到我的应用程序的正确HEAPSIZE使用日志呢?

I have referred to this post, prior to posting here. In that post, it is mentioned that, Debug.getNativeHeapSize() returns the heapsize. Is this the exact method I should use, in order to programmatically detect the heap size? If so, where should I log it in order to get the correct heapsize usage of my application?

推荐答案

下面是我使用的:

public static void logHeap() {
        Double allocated = new Double(Debug.getNativeHeapAllocatedSize())/new Double((1048576));
        Double available = new Double(Debug.getNativeHeapSize())/1048576.0;
        Double free = new Double(Debug.getNativeHeapFreeSize())/1048576.0;
        DecimalFormat df = new DecimalFormat();
        df.setMaximumFractionDigits(2);
        df.setMinimumFractionDigits(2);

        Log.d("tag", "debug. =================================");
        Log.d("tag", "debug.heap native: allocated " + df.format(allocated) + "MB of " + df.format(available) + "MB (" + df.format(free) + "MB free)");
        Log.d("tag", "debug.memory: allocated: " + df.format(new Double(Runtime.getRuntime().totalMemory()/1048576)) + "MB of " + df.format(new Double(Runtime.getRuntime().maxMemory()/1048576))+ "MB (" + df.format(new Double(Runtime.getRuntime().freeMemory()/1048576)) +"MB free)");
    }