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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,005评论 25 708
  • HereAndroid的内存优化是性能优化中很重要的一部分,而避免OOM又是内存优化中比较核心的一点。这是一篇关于...
    HarryXR阅读 3,844评论 1 24
  • 本文转载来源 http://www.csdn.net/article/2015-09-18/2825737/1 (...
    yoosir阅读 1,126评论 0 5
  • 在我赖在被子里与床难舍难分的时候。妈妈的声音充斥着我的耳朵。可是,我却在呓语着说就一会时进入了另外一个世界里-...
    我是太阳何须畏惧光阅读 306评论 0 0
  • 在中国,农民是没有退休金的,现在虽说有了一点养老金,但那点微薄的养老金,和国家或地方编制内各种形形色色的工...
    芭蕉皇族阅读 499评论 0 0