Android O 8.0 以上 bitmap内存分配

2018-09-19  本文已影响0人  卜卜Bruce

From Android 3.0 (API level 11) through Android 7.1 (API level 25),the pixel data is stored on the Dalvik heap along with the associated bitmap. In Android 8.0 (API level 26), and higher, the bitmap pixel data is stored in the native heap.
官方原文说道 android 3.0 到7.1 bitmap是放在dalvik heap中, 8.0 以后放在native heap中, 具体参见源码也可以看到。
如下代码,会分配差不多2G的空间(53000100004字节)

        logMem();
        Bitmap bitmap = Bitmap.createBitmap(53000,10000, Bitmap.Config.ARGB_8888);
//        Canvas canvas = new Canvas(bitmap);
//        canvas.drawColor(Color.RED);
        logMem();

通过

    private void logMem(){
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(memoryInfo);
        Log.d("Bruce","memoryInfo.availMem :" + memoryInfo.availMem/1024/1024);
        Log.d("Bruce","NativeHeapAllocatedSize :" + Debug.getNativeHeapAllocatedSize()/1024/1024);

    }

打印如下:
memoryInfo.availMem :2393
NativeHeapAllocatedSize :16
memoryInfo.availMem :2349
NativeHeapAllocatedSize :2065

发现android的可用内存基本没变化,但是nativeHeap已经分配了bitmap所需要的空间。


native内存占用

但是实际内存并没有占用。
以下代码效果同上。

        logMem();
        Bitmap bitmap = Bitmap.createBitmap(53000,10000, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
//        canvas.drawColor(Color.RED);
        logMem();

重点

下面代码将会出现不同

        logMem();
        Bitmap bitmap = Bitmap.createBitmap(53000,10000, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.RED);
        logMem();

log如下:
memoryInfo.availMem :2394
NativeHeapAllocatedSize :9
memoryInfo.availMem :369
NativeHeapAllocatedSize :2057
发现当在bitmap上绘画的时候 才开始正真占用内存。


native内存占用

可以看到native这个时候占用了2G的内存。

上一篇下一篇

猜你喜欢

热点阅读