Bitmaps加载之介绍

介绍

Android开发应用过程中加载bitmap是很tricky的,如果你稍微不注意,bitmaps就会快速消耗光应用的可用内存,导致应用奔溃,抛出OutofMemoryError异常,俗称OOM:

java.lang.OutofMemoryError: bitmap size exceeds VM budget.

而这主要有几个原因:

  1. Android设备给每个应用分配的可用内存为16M,但是这个值因机型而异(下面有获取分配内存大小的方法),现在的很多机子分配的limit都高出很多了,对于应用来说,要将使用的内存控制在这个limit以内.
  2. Bitmap会占用大量内存尤其是照片,比如5百万像素的摄像头拍的照片大小为2592x1936 pixels, 如果bitmap的配置使用ARGB_8888(Android 2.3以后的默认值),那么加载一张照片就占用了将近19M的内存(2592*1936*4 bytes),瞬间就将应用的内存limit消耗光了,特别是内存limit较小的设备.
  3. Android应用的一些UI组件经常需要一次性加载多张bitmaps,比如ListView,GridView和ViewPager.

官网提供的五个教学课程来加载Bitmap

  1. Loading Large Bitmaps Efficiently
  2. Processing Bitmaps Off the UI Thread
  3. Caching Bitmaps
  4. Managing Bitmap Memory
  5. Displaying Bitmaps in Your UI

Bitmap.Config的具体配置如下表:

Bitmap.Config Description
ALPHA_8 Each pixel is stored as a single translucency (alpha) channel
ARGB_4444 This field was deprecated in API level 13. Because of the poor quality of this configuration, it is advised to use ARGB_8888 instead.
ARGB_8888 Each pixel is stored on 4 bytes.
RGB_565 Each pixel is stored on 2 bytes and only the RGB channels are encoded: red is stored with 5 bits of precision (32 possible values), green is stored with 6 bits of precision (64 possible values) and blue is stored with 5 bits of precision.

获取应用分配的最大内存大小的方法:

  1. Runtime的maxMemory()方法返回bytes
  2. ActivityManager的getMemoryClass()方法返回megabytes
    例:
// get max memory by runtime
long maxBytes=Runtime.getRuntime().maxMemory();
Log.i("Log","maxMemory: "+maxBytes/1024/1024+" M");
// get max memory by activity manager
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
int maxMemory = activityManager.getMemoryClass();
Log.i("Log","memClass: "+maxMemory+" M");

结果输出:

Log: maxMemory: 256 M
Log: memClass: 256 M

Reference

  1. Displaying Bitmaps Efficiently
  2. Bitmap.Config

你可能感兴趣的:(Bitmaps加载之介绍)