Android 缓存机制(二)

外部文件缓存

[html] view plaincopy

private File mCacheDir = context.getCacheDir();

private static final int MAX_CACHE_SIZE = 20 * 1024 * 1024; //20M

private final LruCache sFileCache = new LruCache(MAX_CACHE_SIZE){

@Override

public int sizeOf(String key, Long value){

return value.intValue();

}

@Override

protected void entryRemoved(boolean evicted, String key, Long oldValue, Long newValue){

File file = getFile(key);

if(file != null)

file.delete();

}

}

private File getFile(String fileName) throws FileNotFoundException {

File file = new File(mCacheDir, fileName);

if(!file.exists() || !file.isFile())

throw new FileNotFoundException("文件不存在或有同名文件夹");

return file;

}

//缓存bitmap到外部存储

public boolean putBitmap(String key, Bitmap bitmap){

File file = getFile(key);

if(file != null){

Log.v("tag", "文件已经存在");

return true;

}

FileOutputStream fos = getOutputStream(key);

boolean saved = bitmap.compress(CompressFormat.JPEG, 100, fos);

fos.flush();

fos.close();

if(saved){

synchronized(sFileCache){

sFileCache.put(key, getFile(key).length());

}

return true;

}

return false;

}

//根据key获取OutputStream

private FileOutputStream getOutputStream(String key){

if(mCacheDir == null)

return null;

FileOutputStream fos = new FileOutputStream(mCacheDir.getAbsolutePath() + File.separator + key);

return fos;

}

//获取bitmap

private static BitmapFactory.Options sBitmapOptions;

static {

sBitmapOptions = new BitmapFactory.Options();

sBitmapOptions.inPurgeable=true; //bitmap can be purged to disk

}

public Bitmap getBitmap(String key){

File bitmapFile = getFile(key);

if(bitmapFile != null){

Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(bitmapFile), null, sBitmapOptions);

if(bitmap != null){

//重新将其缓存至硬引用中

...

}

}

}

你可能感兴趣的:(Android 缓存机制(二))