当前位置: 移动技术网 > 移动技术>移动开发>Android > Android中的Bitmap缓存池使用详解

Android中的Bitmap缓存池使用详解

2019年07月24日  | 移动技术网移动技术  | 我要评论

本文介绍了如何使用缓存来提高ui的载入输入和滑动的流畅性。使用内存缓存、使用磁盘缓存、处理配置改变事件等方法将会有效的解决这个问题。

在您的ui中显示单个图片是非常简单的,如果您需要一次显示很多图片就有点复杂了。在很多情况下(例如使用 listview, gridview 或者 viewpager控件),显示在屏幕上的图片以及即将显示在屏幕上的图片数量是非常大的(例如在图库中浏览大量图片)。

在这些控件中,当一个子控件不显示的时候,系统会重用该控件来循环显示 以便减少对内存的消耗。同时垃圾回收机制还会释放那些已经载入内存中的bitmap资源(假设您没有强引用这些bitmap)。一般来说这样都是不错的,但是在用户来回滑动屏幕的时候,为了保证ui的流畅性和载入图片的效率,您需要避免重复的处理这些需要显示的图片。 使用内存缓存和磁盘缓存可以解决这个问题,使用缓存可以让控件快速的加载已经处理过的图片。

本文介绍如何使用缓存来提高ui的载入输入和滑动的流畅性。

使用内存缓存

内存缓存提高了访问图片的速度,但是要占用不少内存。 lrucache
类(在api 4之前可以使用support library 中的类 )特别适合缓存bitmap, 把最近使用到的
bitmap对象用强引用保存起来(保存到linkedhashmap中),当缓存数量达到预定的值的时候,把
不经常使用的对象删除。

注意: 过去,实现内存缓存的常用做法是使用
softreference 或者
weakreference bitmap 缓存,
但是不推荐使用这种方式。从android 2.3 (api level 9) 开始,垃圾回收开始强制的回收掉 soft/weak 引用 从而导致这些缓存没有任何效率的提升。
另外,在 android 3.0 (api level 11)之前,这些缓存的bitmap数据保存在底层内存(native memory)中,并且达到预定条件后也不会释放这些对象,从而可能导致
程序超过内存限制并崩溃。

在使用 lrucache 的时候,需要考虑如下一些因素来选择一个合适的缓存数量参数:

1.程序中还有多少内存可用
2.同时在屏幕上显示多少图片?要先缓存多少图片用来显示到即将看到的屏幕上?
3.设备的屏幕尺寸和屏幕密度是多少?超高的屏幕密度(xhdpi 例如 galaxy nexus)
4.设备显示同样的图片要比低屏幕密度(hdpi 例如 nexus s)设备需要更多的内存。
5.图片的尺寸和格式决定了每个图片需要占用多少内存
6.图片访问的频率如何?一些图片的访问频率要比其他图片高很多?如果是这样的话,您可能需要把这些经常访问的图片放到内存中。
7.在质量和数量上如何平衡?有些情况下保存大量的低质量的图片是非常有用的,当需要的情况下使用后台线程来加入一个高质量版本的图片。

这里没有万能配方可以适合所有的程序,您需要分析您的使用情况并在指定自己的缓存策略。使用太小的缓存并不能起到应有的效果,而使用太大的缓存会消耗更多
的内存从而有可能导致 java.lang.outofmemory 异常或者留下很少的内存供您的程序其他功能使用。

下面是一个使用 lrucache 缓存的示例:

复制代码 代码如下:

private lrucache<string, bitmap=""> mmemorycache;

@override
protected void oncreate(bundle savedinstancestate) {
    ...
    // get memory class of this device, exceeding this amount will throw an
    // outofmemory exception.
    final int memclass = ((activitymanager) context.getsystemservice(
            context.activity_service)).getmemoryclass();

    // use 1/8th of the available memory for this memory cache.
    final int cachesize = 1024 * 1024 * memclass / 8;

    mmemorycache = new lrucache<string, bitmap="">(cachesize) {
        @override
        protected int sizeof(string key, bitmap bitmap) {
            // the cache size will be measured in bytes rather than number of items.
            return bitmap.getbytecount();
        }
    };
    ...
}                                                              
public void addbitmaptomemorycache(string key, bitmap bitmap) {
    if (getbitmapfrommemcache(key) == null) {
        mmemorycache.put(key, bitmap);
    }
}                                                              
public bitmap getbitmapfrommemcache(string key) {
    return mmemorycache.get(key);
}


注意: 在这个示例中,该程序的1/8内存都用来做缓存用了。在一个normal/hdpi设备中,这至少有4mb(32/8)内存。
在一个分辨率为 800×480的设备中,满屏的gridview全部填充上图片将会使用差不多1.5mb(800*480*4 bytes)
的内存,所以这样差不多在内存中缓存了2.5页的图片。

当在 imageview 中显示图片的时候,
先检查lrucache 中是否存在。如果存在就使用缓存后的图片,如果不存在就启动后台线程去载入图片并缓存:

复制代码 代码如下:

public void loadbitmap(int resid, imageview imageview) {
    final string imagekey = string.valueof(resid);
    final bitmap bitmap = getbitmapfrommemcache(imagekey);
    if (bitmap != null) {
        mimageview.setimagebitmap(bitmap);
    } else {
        mimageview.setimageresource(r.drawable.image_placeholder);
        bitmapworkertask task = new bitmapworkertask(mimageview);
        task.execute(resid);
    }
}

bitmapworkertask 需要把新的图片添加到缓存中:
复制代码 代码如下:

class bitmapworkertask extends asynctask<integer, void,="" bitmap=""> {
    ...
    // decode image in background.
    @override
    protected bitmap doinbackground(integer... params) {
        final bitmap bitmap = decodesampledbitmapfromresource(
                getresources(), params[0], 100, 100));
        addbitmaptomemorycache(string.valueof(params[0]), bitmap);
        return bitmap;
    }
    ...
}

下页将为您介绍其它两种方法使用磁盘缓存和处理配置改变事件

使用磁盘缓存

在访问最近使用过的图片中,内存缓存速度很快,但是您无法确定图片是否在缓存中存在。像
gridview 这种控件可能具有很多图片需要显示,很快图片数据就填满了缓存容量。
同时您的程序还可能被其他任务打断,比如打进的电话 — 当您的程序位于后台的时候,系统可能会清楚到这些图片缓存。一旦用户恢复使用您的程序,您还需要重新处理这些图片。

在这种情况下,可以使用磁盘缓存来保存这些已经处理过的图片,当这些图片在内存缓存中不可用的时候,可以从磁盘缓存中加载从而省略了图片处理过程。
当然, 从磁盘载入图片要比从内存读取慢很多,并且应该在非ui线程中载入磁盘图片。

注意: 如果缓存的图片经常被使用的话,可以考虑使用
contentprovider ,例如在图库程序中就是这样干滴。

在示例代码中有个简单的 disklrucache 实现。然后,在android 4.0中包含了一个更加可靠和推荐使用的disklrucache(libcore/luni/src/main/java/libcore/io/disklrucache.java)
。您可以很容易的把这个实现移植到4.0之前的版本中使用(来 href=”http://www.google.com/search?q=disklrucache”>google一下 看看其他人是否已经这样干了!)。

这里是一个更新版本的 disklrucache :

复制代码 代码如下:

private disklrucache mdiskcache;
private static final int disk_cache_size = 1024 * 1024 * 10; // 10mb
private static final string disk_cache_subdir = "thumbnails";

@override
protected void oncreate(bundle savedinstancestate) {
    ...
    // initialize memory cache
    ...
    file cachedir = getcachedir(this, disk_cache_subdir);
    mdiskcache = disklrucache.opencache(this, cachedir, disk_cache_size);
    ...
}                               
class bitmapworkertask extends asynctask<integer, void,="" bitmap=""> {
    ...
    // decode image in background.
    @override
    protected bitmap doinbackground(integer... params) {
        final string imagekey = string.valueof(params[0]);

        // check disk cache in background thread
        bitmap bitmap = getbitmapfromdiskcache(imagekey);

        if (bitmap == null) { // not found in disk cache
            // process as normal
            final bitmap bitmap = decodesampledbitmapfromresource(
                    getresources(), params[0], 100, 100));
        }                              
        // add final bitmap to caches
        addbitmaptocache(string.valueof(imagekey, bitmap);

        return bitmap;
    }
    ...
}                               
public void addbitmaptocache(string key, bitmap bitmap) {
    // add to memory cache as before
    if (getbitmapfrommemcache(key) == null) {
        mmemorycache.put(key, bitmap);
    }                               
    // also add to disk cache
    if (!mdiskcache.containskey(key)) {
        mdiskcache.put(key, bitmap);
    }
}                               
public bitmap getbitmapfromdiskcache(string key) {
    return mdiskcache.get(key);
}                               
// creates a unique subdirectory of the designated app cache directory. tries to use external
// but if not mounted, falls back on internal storage.
public static file getcachedir(context context, string uniquename) {
    // check if media is mounted or storage is built-in, if so, try and use external cache dir
    // otherwise use internal cache dir
    final string cachepath = environment.getexternalstoragestate() == environment.media_mounted
            || !environment.isexternalstorageremovable() ?
                    context.getexternalcachedir().getpath() : context.getcachedir().getpath();
    return new file(cachepath + file.separator + uniquename);
}


在ui线程中检测内存缓存,在后台线程中检测磁盘缓存。磁盘操作从来不应该在ui线程中实现。当图片处理完毕后,最终的结果会同时添加到
内存缓存和磁盘缓存中以便将来使用。

处理配置改变事件

运行时的配置变更 — 例如 屏幕方向改变 — 导致android摧毁正在运行的activity,然后使用
新的配置从新启动该activity (详情,参考这里 handling runtime changes)。
您需要注意避免在配置改变的时候导致重新处理所有的图片,从而提高用户体验。

幸运的是,您在 使用内存缓存 部分已经有一个很好的图片缓存了。该缓存可以通过
fragment (fragment会通过setretaininstance(true)函数保存起来)来传递给新的activity
当activity重新启动 后,fragment 被重新附加到activity中,您可以通过该fragment来获取缓存对象。

下面是一个在 fragment中保存缓存的示例:

复制代码 代码如下:

private lrucache<string, bitmap=""> mmemorycache;                 
@override
protected void oncreate(bundle savedinstancestate) {
    ...
    retainfragment mretainfragment =            retainfragment.findorcreateretainfragment(getfragmentmanager());
    mmemorycache = retainfragment.mretainedcache;
    if (mmemorycache == null) {
        mmemorycache = new lrucache<string, bitmap="">(cachesize) {
            ... // initialize cache here as usual
        }
        mretainfragment.mretainedcache = mmemorycache;
    }
    ...
}                 
class retainfragment extends fragment {
    private static final string tag = "retainfragment";
    public lrucache<string, bitmap=""> mretainedcache;

    public retainfragment() {}                 
    public static retainfragment findorcreateretainfragment(fragmentmanager fm) {
        retainfragment fragment = (retainfragment) fm.findfragmentbytag(tag);
        if (fragment == null) {
            fragment = new retainfragment();
        }
        return fragment;
    }                 
    @override
    public void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        <strong>setretaininstance(true);</strong>
    }
}


此外您可以尝试分别使用和不使用fragment来旋转设备的屏幕方向来查看具体的图片载入情况。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网