user264953
user264953

Reputation: 1967

How do I detect the heap size usage of an android application

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

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?

Upvotes: 22

Views: 16765

Answers (2)

zrgiu
zrgiu

Reputation: 6342

here's what I use:

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)");
    }

Upvotes: 55

Boris Daich
Boris Daich

Reputation: 2461

Yes. Please note that also there are heap view in DDMS and you can use MAT Eclipse which is more than helpful especially in memory leaks tracking BUT and this is a huge but the numbers you see are reference only memory that is managed by VM. There are a lot of subsystems in android that are implemented underneath VM - native. The simplest example Bitmap class. You will not see the whole memory allocated to a Bitmap in DDMS and garbage collector is not very good/fast at recovering this memory. so be careful.

Upvotes: 3

Related Questions