当需要获取图片时,就先从sdcard上的目录中去找,如果找到的话,使用该图片,并更新图片最后被使用的时间。如果找不到,通过URL去download 去服务器端下载图片,如果下载成功了,放入到sdcard上,并使用,如果失败了,应该有重试机制。比如3次。
下载成功后保存到sdcard上,需要先判断10M空间是否已经用完,如果没有用完就保存,如果空间不足就根据LRU规则删除一些最近没有被用户的资源。
关键代码:
保存图片到SD卡上:
private void saveBmpToSd(Bitmap bm, Stringurl) {
if (bm == null) {
Log.w(TAG, " trying to savenull bitmap");
return;
}
//判断sdcard上的空间
if (FREE_SD_SPACE_NEEDED_TO_CACHE >freeSpaceOnSd()) {
Log.w(TAG, "Low free space onsd, do not cache");
return;
}
String filename =convertUrlToFileName(url);
String dir = getDirectory(filename);
File file = new File(dir +"/" + filename);
try {
file.createNewFile();
OutputStream outStream = newFileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Log.i(TAG, "Image saved tosd");
} catch (FileNotFoundException e) {
Log.w(TAG,"FileNotFoundException");
} catch (IOException e) {
Log.w(TAG,"IOException");
}
}
计算sdcard上的空间:
/**
* 计算sdcard上的剩余空间
* @return
*/
private int freeSpaceOnSd() {
StatFs stat = newStatFs(Environment.getExternalStorageDirectory() .getPath());
double sdFreeMB = ((double)stat.getAvailableBlocks() * (double) stat.getBlockSize()) / MB;
return (int) sdFreeMB;
}
修改文件的最后修改时间 :
/**
* 修改文件的最后修改时间
* @param dir
* @param fileName
*/
private void updateFileTime(String dir,String fileName) {
File file = new File(dir,fileName);
long newModifiedTime =System.currentTimeMillis();
file.setLastModified(newModifiedTime);
}










