is Enough Memory Left - Android Hardware

Android examples for Hardware:Memory

Description

is Enough Memory Left

Demo Code


//package com.java2s;
import android.os.Build;
import android.os.Debug;
import android.util.Log;

public class Main {
    private static final String TAG = "MemoryHelper";
    private static final int MAGIC_VM_HEAP_FREE_SIZE = 5000;
    private static final int MAGIC_NATIVE_HEAP_CONSTANT = 200;

    public static boolean _isEnoughMemoryLeft() {
        long maxVmHeap = Runtime.getRuntime().totalMemory();
        long minNativeFree = maxVmHeap / MAGIC_NATIVE_HEAP_CONSTANT; // it's an estimate.
        long freeMemory = Runtime.getRuntime().freeMemory();

        Log.d(TAG, String.format(
                "maxVmHeap=%d minNativeFree=%d totalFree=%d", maxVmHeap,
                minNativeFree, freeMemory));

        // whether we're using the native or VM heap for bitmaps
        boolean isNativeHeap = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB;

        if (isNativeHeap) {
            long allocatedSize = Debug.getNativeHeapAllocatedSize();
            long freeSize = Debug.getNativeHeapFreeSize();

            String msg = String.format(
                    "Native heap: max=%d allocated=%d free=%d",
                    minNativeFree, allocatedSize, freeSize);

            Log.d(TAG, msg);//  ww w .  j  a va2  s.c  om

            return freeSize > minNativeFree;
        } else {
            long freeSize = Runtime.getRuntime().freeMemory();

            String msg = String.format("VM heap: max=%d free=%d",
                    maxVmHeap, freeSize);
            Log.w(TAG, msg);
            return freeSize >= MAGIC_VM_HEAP_FREE_SIZE;
        }
    }
}

Related Tutorials