一种方式是把Bitmap 缓存到内存,但是我们需要使用弱引用来缓存这个Bitmap: Memory Cache
另一种方式是我们的内存即使弱引用了这个还是不够用,或者频繁访问网络造成流量消耗太多我们可以把这个bitmap先保存在本地sd卡中,避免过多的流量消耗。File Cache
1. Memory Cache
publicclassMemoryCache{
privatestaticfinalString TAG ="MemoryCache";
//WeakReference Map: key=string, value=Bitmap
privateWeakHashMap<String,Bitmap> cache =newWeakHashMap<String,Bitmap>();
/**
* Search the memory cache by a unique key.
* @param key Should be unique.
* @return The Bitmap object in memory cache corresponding to specific key.
* */
publicBitmap get(String key){
if(key !=null)
return cache.get(key);
returnnull;
}
/**
* Put a bitmap into cache with a unique key.
* @param key Should be unique.
* @param value A bitmap.
* */
publicvoid put(String key,Bitmap value){
if(key !=null&&!"".equals(key)&& value !=null){
cache.put(key, value);
//Log.i(TAG, "cache bitmap: " + key);
Log.d(TAG,"size of memory cache: "+ cache.size());
}
}
/**
* clear the memory cache.
* */
publicvoid clear(){
cache.clear();
}
}
2. File Cache
publicclassFileCache{
privatestaticfinalString TAG ="MemoryCache";
privateFile cacheDir;//the directory to save images
/**
* Constructor
* @param context The context related to this cache.
* */
publicFileCache(Context context){
// Find the directory to save cached images
if(android.os.Environment.getExternalStorageState()
.equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir =newFile(
android.os.Environment.getExternalStorageDirectory(),
Config.CACHE_DIR);
else
cacheDir = context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
Log.d(TAG,"cache dir: "+ cacheDir.getAbsolutePath());
}
/**
* Search the specific image file with a unique key.
* @param key Should be unique.
* @return Returns the image file corresponding to the key.
* */
publicFile getFile(String key){
File f =newFile(cacheDir, key);
if(f.exists()){
Log.i(TAG,"the file you wanted exists "+ f.getAbsolutePath());
return f;
}else{
Log.w(TAG,"the file you wanted does not exists: "+ f.getAbsolutePath());
}
returnnull;
}
/**
* Put a bitmap into cache with a unique key.
* @param key Should be unique.
* @param value A bitmap.
* */
publicvoid put(String key,Bitmap value){
File f =newFile(cacheDir, key);
if(!f.exists())
try{
f.createNewFile();
}catch(IOException e){
e.printStackTrace();
}
//Use the util's function to save the bitmap.
if(BitmapHelper.saveBitmap(f, value))
Log.d(TAG,"Save file to sdcard successfully!");
else
Log.w(TAG,"Save file to sdcard failed!");
}
/**
* Clear the cache directory on sdcard.
* */
publicvoid clear(){
File[] files = cacheDir.listFiles();
for(File f : files)
f.delete();
}
}
3. 关于上面的如何把BitMap 保存到文件中,这里有个工具方法:BitmapHelper 这个类中我们写保存bitmap的代码
publicstaticboolean saveBitmap(File file,Bitmap bitmap){
if(file ==null|| bitmap ==null)
returnfalse;
try{
BufferedOutputStream out =newBufferedOutputStream(newFileOutputStream(file));
return bitmap.compress(CompressFormat.JPEG,100, out);
}catch(FileNotFoundException e){
e.printStackTrace();
returnfalse;
}
}