Caching Bitmaps [缓存位图]
- 加载单个Bitmap到UI是简单直接的,但是如果你需要一次加载大量的图片,事情则会变得复杂起来。在大多数情况下(例如在
ListView
,GridView
orViewPager
), 显示图片的数量通常是没有限制的。 - 通过循环利用子视图可以抑制内存的使用,GC(garbage collector)也会释放那些不再需要使用的bitmap。这些机制都非常好,但是为了保持一个流畅的用户体验,你想要在屏幕滑回来时避免每次重复处理那些图片。内存与磁盘缓存通常可以起到帮助的作用,允许组件快速的重新加载那些处理过的图片。
- 这一课会介绍在加载多张位图时使用内存Cache与磁盘Cache来提高反应速度与UI的流畅度
Use a Memory Cache [使用内存缓存]
异步加载图片的例子,网上也比较多,大部分用了HashMap<String, SoftReference<Drawable>> imageCache ,但是现在已经不再推荐使用这种方式了,因为从 Android 2.3 (API Level 9)开始,垃圾回收器会更倾向于回收持有软引用或弱引用(soft/weak references)的对象,这让软引用和弱引用变得不再可靠。另外,Android 3.0 (API Level 11)中,图片的数据会存储在本地的内存(native memory)当中,因而无法用一种可预见的方式将其释放,这就有潜在的风险造成应用程序的内存溢出并崩溃,所以我这里用得是LruCache来缓存图片,当存储Image的大小大于LruCache设定的值,系统自动释放内存,这个类是3.1版本中提供的,如果你是在更早的Android版本中开发,则需要导入android-support-v4的jar包(这里要注意咯)
- 为了给LruCache选择一个合适的大小,有下面一些因素需要考虑到:
-
- 你的程序剩下了多少可用的内存?
- 多少图片会被一次呈现到屏幕上?有多少图片需要准备好以便马上显示到屏幕?
- 设备的屏幕大小与密度是多少? 一个具有特别高密度屏幕(xhdpi)的设备,像 Galaxy Nexus 会比 Nexus S (hdpi)需要一个更大的Cache来hold住同样数量的图片.
- 位图的尺寸与配置是多少,会花费多少内存?
- 图片被访问的频率如何?是其中一些比另外的访问更加频繁吗?如果是,也许你想要保存那些最常访问的到内存中,或者为不同组别的位图(按访问频率分组)设置多个
LruCache
对象。 - 你可以平衡质量与数量吗? 某些时候保存大量低质量的位图会非常有用,在另外一个后台任务中加载更高质量的图片。
- 没有指定的大小与公式能够适用与所有的程序,那取决于分析你的使用情况后提出一个合适的解决方案。一个太小的Cache会导致额外的花销却没有明显的好处,一个太大的Cache同样会导致
java.lang.OutOfMemory的异常[Cache占用太多内存,其他活动则会因为内存不够而异常],并且使得你的程序只留下小部分的内存用来工作。
Android提供的LruCache类简介
<span style="color:#000000;">package android.util; import java.util.LinkedHashMap; import java.util.Map; /** * A cache that holds strong references to a limited number of values. Each time * a value is accessed, it is moved to the head of a queue. When a value is * added to a full cache, the value at the end of that queue is evicted and may * become eligible for garbage collection.</span>
<span style="color:#000000;"> * Cache保存一个强引用来限制内容数量,每当Item被访问的时候,此Item就会移动到队列的头部。 * 当cache已满的时候加入新的item时,在队列尾部的item会被回收。</span>
<span style="color:#000000;"> * <p>If your cached values hold resources that need to be explicitly released, * override {@link #entryRemoved}. * 如果你cache的某个值需要明确释放,重写entryRemoved() * <p>If a cache miss should be computed on demand for the corresponding keys, * override {@link #create}. This simplifies the calling code, allowing it to * assume a value will always be returned, even when there's a cache miss. * 如果key相对应的item丢掉啦,重写create().这简化了调用代码,即使丢失了也总会返回。 * <p>By default, the cache size is measured in the number of entries. Override * {@link #sizeOf} to size the cache in different units. For example, this cache * is limited to 4MiB of bitmaps: 默认cache大小是测量的item的数量,重写sizeof计算不同item的 * 大小。 * <pre> {@code * int cacheSize = 4 * 1024 * 1024; // 4MiB * LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) { * protected int sizeOf(String key, Bitmap value) { * return value.getByteCount(); * } * }}</pre> * * <p>This class is thread-safe. Perform multiple cache operations atomically by * synchronizing on the cache:</span>
- 线程安全的 有多种缓存操作 被自动用于异步缓存
<span style="color:#000000;"> <pre> {@code * synchronized (cache) { * if (cache.get(key) == null) { * cache.put(key, value); * } * }}</pre> * * <p>This class does not allow null to be used as a key or value. A return * value of null from {@link #get}, {@link #put} or {@link #remove} is * unambiguous: the key was not in the cache. * 不允许key或者value为null * 当get(),put(),remove()返回值为null时,key相应的项不在cache中 */ public class LruCache<K, V> { private final LinkedHashMap<K, V> map; /** Size of this cache in units. Not necessarily the number of elements. */ private int size; //已经存储的大小 private int maxSize; //规定的最大存储空间 private int putCount; //put的次数 private int createCount; //create的次数 private int evictionCount; //回收的次数 private int hitCount; //命中的次数 private int missCount; //丢失的次数 /** * @param maxSize for caches that do not override {@link #sizeOf}, this is * the maximum number of entries in the cache. For all other caches, * this is the maximum sum of the sizes of the entries in this cache. */ public LruCache(int maxSize) { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize <= 0"); } this.maxSize = maxSize; this.map = new LinkedHashMap<K, V>(0, 0.75f, true); } /** * Returns the value for {@code key} if it exists in the cache or can be * created by {@code #create}. If a value was returned, it is moved to the * head of the queue. This returns null if a value is not cached and cannot * be created. 通过key返回相应的item,或者创建返回相应的item。相应的item会移动到队列的头部, * 如果item的value没有被cache或者不能被创建,则返回null。 */ public final V get(K key) { if (key == null) { throw new NullPointerException("key == null"); } V mapValue; synchronized (this) { mapValue = map.get(key); if (mapValue != null) { hitCount++; //命中 return mapValue; } missCount++; //丢失 } /* * Attempt to create a value. This may take a long time, and the map * may be different when create() returns. If a conflicting value was * added to the map while create() was working, we leave that value in * the map and release the created value. * 如果丢失了就试图创建一个item */ V createdValue = create(key); if (createdValue == null) { return null; } synchronized (this) { createCount++;//创建++ mapValue = map.put(key, createdValue); if (mapValue != null) { // There was a conflict so undo that last put //如果前面存在oldValue,那么撤销put() map.put(key, mapValue); } else { size += safeSizeOf(key, createdValue); } } if (mapValue != null) { entryRemoved(false, key, createdValue, mapValue); return mapValue; } else { trimToSize(maxSize); return createdValue; } } /** * Caches {@code value} for {@code key}. The value is moved to the head of * the queue. * * @return the previous value mapped by {@code key}. */ public final V put(K key, V value) { if (key == null || value == null) { throw new NullPointerException("key == null || value == null"); } V previous; synchronized (this) { putCount++; size += safeSizeOf(key, value); previous = map.put(key, value); if (previous != null) { //返回的先前的value值 size -= safeSizeOf(key, previous); } } if (previous != null) { entryRemoved(false, key, previous, value); } trimToSize(maxSize); return previous; } /** * @param maxSize the maximum size of the cache before returning. May be -1 * to evict even 0-sized elements. * 清空cache空间 */ private void trimToSize(int maxSize) { while (true) { K key; V value; synchronized (this) { if (size < 0 || (map.isEmpty() && size != 0)) { throw new IllegalStateException(getClass().getName() + ".sizeOf() is reporting inconsistent results!"); } if (size <= maxSize) { break; } Map.Entry<K, V> toEvict = map.eldest(); if (toEvict == null) { break; } key = toEvict.getKey(); value = toEvict.getValue(); map.remove(key); size -= safeSizeOf(key, value); evictionCount++; } entryRemoved(true, key, value, null); } } /** * Removes the entry for {@code key} if it exists. * 删除key相应的cache项,返回相应的value * @return the previous value mapped by {@code key}. */ public final V remove(K key) { if (key == null) { throw new NullPointerException("key == null"); } V previous; synchronized (this) { previous = map.remove(key); if (previous != null) { size -= safeSizeOf(key, previous); } } if (previous != null) { entryRemoved(false, key, previous, null); } return previous; } /** * Called for entries that have been evicted or removed. This method is * invoked when a value is evicted to make space, removed by a call to * {@link #remove}, or replaced by a call to {@link #put}. The default * implementation does nothing. * 当item被回收或者删掉时调用。改方法当value被回收释放存储空间时被remove调用, * 或者替换item值时put调用,默认实现什么都没做。 * <p>The method is called without synchronization: other threads may * access the cache while this method is executing. * * @param evicted true if the entry is being removed to make space, false * if the removal was caused by a {@link #put} or {@link #remove}. * true---为释放空间被删除;false---put或remove导致 * @param newValue the new value for {@code key}, if it exists. If non-null, * this removal was caused by a {@link #put}. Otherwise it was caused by * an eviction or a {@link #remove}. */ protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) {} /** * Called after a cache miss to compute a value for the corresponding key. * Returns the computed value or null if no value can be computed. The * default implementation returns null. * 当某Item丢失时会调用到,返回计算的相应的value或者null * <p>The method is called without synchronization: other threads may * access the cache while this method is executing. * * <p>If a value for {@code key} exists in the cache when this method * returns, the created value will be released with {@link #entryRemoved} * and discarded. This can occur when multiple threads request the same key * at the same time (causing multiple values to be created), or when one * thread calls {@link #put} while another is creating a value for the same * key. */ protected V create(K key) { return null; } private int safeSizeOf(K key, V value) { int result = sizeOf(key, value); if (result < 0) { throw new IllegalStateException("Negative size: " + key + "=" + value); } return result; } /** * Returns the size of the entry for {@code key} and {@code value} in * user-defined units. The default implementation returns 1 so that size * is the number of entries and max size is the maximum number of entries. * 返回用户定义的item的大小,默认返回1代表item的数量,最大size就是最大item值 * <p>An entry's size must not change while it is in the cache. */ protected int sizeOf(K key, V value) { return 1; } /** * Clear the cache, calling {@link #entryRemoved} on each removed entry. * 清空cacke */ public final void evictAll() { trimToSize(-1); // -1 will evict 0-sized elements } /** * For caches that do not override {@link #sizeOf}, this returns the number * of entries in the cache. For all other caches, this returns the sum of * the sizes of the entries in this cache. */ public synchronized final int size() { return size; } /** * For caches that do not override {@link #sizeOf}, this returns the maximum * number of entries in the cache. For all other caches, this returns the * maximum sum of the sizes of the entries in this cache. */ public synchronized final int maxSize() { return maxSize; } /** * Returns the number of times {@link #get} returned a value that was * already present in the cache. */ public synchronized final int hitCount() { return hitCount; } /** * Returns the number of times {@link #get} returned null or required a new * value to be created. */ public synchronized final int missCount() { return missCount; } /** * Returns the number of times {@link #create(Object)} returned a value. */ public synchronized final int createCount() { return createCount; } /** * Returns the number of times {@link #put} was called. */ public synchronized final int putCount() { return putCount; } /** * Returns the number of values that have been evicted. * 返回被回收的数量 */ public synchronized final int evictionCount() { return evictionCount; } /** * Returns a copy of the current contents of the cache, ordered from least * recently accessed to most recently accessed. 返回当前cache的副本,从最近最少访问到最多访问 */ public synchronized final Map<K, V> snapshot() { return new LinkedHashMap<K, V>(map); } @Override public synchronized final String toString() { int accesses = hitCount + missCount; int hitPercent = accesses != 0 ? (100 * hitCount / accesses) : 0; return String.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]", maxSize, hitCount, missCount, hitPercent); } } </span>
- 下面是一个为bitmap建立
LruCache 的示例:
private LruCache 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(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);
}
- Note: 在上面的例子中, 有1/8的程序内存被作为Cache. 在一个常见的设备上(hdpi),最小大概有4MB (32/8). 一个全屏的
GridView
组件,如果被800x480像素的图片填满大概会花费1.5MB (800*480*4 bytes), 因此这大概最少可以缓存2.5张图片到内存中.
ImageView
时,LruCache
会先被检查是否存在这张图片。如果找到有,它会被用来立即更新 ImageView
组件,否则一个后台线程则被触发去处理这张图片
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 {
<span style="font-family:'Microsoft YaHei';"><span style="font-family:'Microsoft YaHei';"> //<span style="font-family:'Microsoft YaHei';">默认图片 并开启异步线程</span></span></span>
mImageView.setImageResource(R.drawable.image_placeholder);
BitmapWorkerTask task = new BitmapWorkerTask(mImageView);
task.execute(resId);
}
}
~上面的程序中 BitmapWorkerTask
也需要做添加到内存Cache中的动作:class BitmapWorkerTask extends AsyncTask { ... // 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);//<span style="font-family:'Microsoft YaHei';">添加到内存<span style="font-family:'Microsoft YaHei';">cache</span></span> return bitmap; } ... }
Use a Disk Cache [使用磁盘缓存]
- 内存缓存能够提高访问最近查看过的位图,但是你不能保证这个图片会在Cache中。像类似
GridView
等带有大量数据的组件很容易就填满内存Cache。你的程序可能会被类似Phone call等任务而中断,这样后台程序可能会被杀死,那么内存缓存就会被销毁。一旦用户恢复前面的状态,你的程序就又需要为每个图片重新处理。 - 磁盘缓存磁盘缓存可以用来保存那些已经处理好的位图,并且在那些图片在内存缓存中不可用时减少加载的次数。当然从磁盘读取图片会比从内存要慢,而且读取操作需要在后台线程中处理,因为磁盘读取操作是不可预期的。
- Note: 如果图片被更频繁的访问到,也许使用
ContentProvider
会更加的合适,比如在Gallery程序中。
- Note: 如果图片被更频繁的访问到,也许使用
- 在下面的sample code中实现了一个基本的
DiskLruCache
。然而,Android 4.0 的源代码提供了一个更加robust并且推荐使用的DiskLruCache
方案。(libcore/luni/src/main/java/libcore/io/DiskLruCache.java
). 因为向后兼容,所以在前面发布的Android版本中也可以直接使用。 (quick search 提供了一个实现这个解决方案的示例)。
Handle Configuration Changes [处理配置改变]
- 运行时配置改变,例如屏幕方向的改变会导致Android去destory并restart当前运行的Activity。(关于这一行为的更多信息,请参考 Handling Runtime Changes). 你想要在配置改变时避免重新处理所有的图片,这样才能提供给用户一个良好的平滑过度的体验。
- 幸运的是,在前面介绍 Use a Memory Cache 的部分,你已经知道如何建立一个内存缓存。这个缓存可以通过使用一个Fragment去调用
setRetainInstance(true)
传递到新的Activity中。在这个activity被recreate之后, 这个保留的Fragment
会白重新附着上。这样你就可以访问Cache对象,从中获取到图片信息并快速的重新添加到ImageView对象中。 - 下面配置改变时使用Fragment来重新获取
LruCache
的示例:
为了测试上面的效果,尝试对比retaining 这个private LruCache mMemoryCache; @Override protected void onCreate(Bundle savedInstanceState) { ... RetainFragment mRetainFragment = RetainFragment.findOrCreateRetainFragment(getFragmentManager()); mMemoryCache = RetainFragment.mRetainedCache; if (mMemoryCache == null) { mMemoryCache = new LruCache(cacheSize) { ... // Initialize cache here as usual } mRetainFragment.mRetainedCache = mMemoryCache; } ... } class RetainFragment extends Fragment { private static final String TAG = "RetainFragment"; public LruCache 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); setRetainInstance(true); } }
Fragment
.与没有这样做的时候去旋转屏幕。你会发现从内存缓存中重新绘制几乎没有卡的现象,而从磁盘缓存则显得稍慢,如果两个缓存中都没有,则处理速度像平时一样。
- 内存缓存能够提高访问最近查看过的位图,但是你不能保证这个图片会在Cache中。像类似