Vlc在显示歌曲列表时会加载该歌曲的封面,对于图片采取了相应的缓存机制:
1. 内存缓存
2. 文件缓存
内存缓存:
采用的是LruCache,对于使用LruCache需要注意的是分配多少内存给它去存储图片。Vlc中使用了1/5的可用内存存储图片。
// 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/5th of the available memory for this cache.
final int cacheSize = 1024 * 1024 * memClass / 5;
Log.d(TAG, "LRUCache size sets to " + cacheSize);
mMemCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
};
对于图片缓存,注意点是计算图片的size,Vlc中采用的是
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
查询
stackoverflow后,发现
protected int sizeOf(Bitmap data) {
int size = 0;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) {
size = value.getRowBytes() * value.getHeight();
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
size = value.getByteCount();
} else {
size = value.getAllocationByteCount();
}
return size;
}
不清楚为什么老版本用 value.getRowBytes() * value.getHeight()计算图片的size。
文件缓存:
private static void writeBitmap(Bitmap bitmap, String path)
throws IOException {
OutputStream out = null;
try {
File file = new File(path);
if (file.exists() && file.length() > 0)
return;
out = new BufferedOutputStream(new FileOutputStream(file), 4096);
if (bitmap != null)
bitmap.compress(CompressFormat.JPEG, 90, out);
} catch (Exception e) {
Log.e(TAG, "writeBitmap failed : " + e.getMessage());
} finally {
if (out != null) {
out.close();
}
}
}