Activity提供了getCacheDir()和getFilesDir()方法:
getCacheDir()方法用于获取/data/data//cache目录
getFilesDir()方法用于获取/data/data//files目录
获取缓存或者文件
Bitmap bitmap= LocalMemoryCache.getInstance().get(iconName);
Bitmap bitmap= BitmapFactory.decodeFile(iconPath);
刷新文件
File file=new File(iconPath);
Log.e("photo","flush file:"+iconPath);
file.delete();
file.createNewFile();
FileOutputStream outputStream=new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();//刷新缓冲
outputStream.close();
刷新缓存LocalMemoryCache.getInstance().put(iconName, bitmap);
LocalMemoryCache.java
package com.ykh.utils;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* 内存管理,主要用来缓存图片 单例实现
* @author ykh
* @creation 2016-01-20
*/
public class LocalMemoryCache {
private static LocalMemoryCache instance;
private final int CACHESIZE=1024*1024*100;//缓存大小 10M
private LruCache<String, Bitmap> lruCache;
private List<String> keys;//记录key值
private LocalMemoryCache(){
lruCache=new LruCache<String, Bitmap>(CACHESIZE){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes()*value.getHeight();
}
};
keys=new ArrayList<String>();
}
public static LocalMemoryCache getInstance(){
return instance==null?instance=new LocalMemoryCache():instance;
}
public void put(String key,Bitmap bitmap){
if(bitmap!=null){
lruCache.put(key, bitmap);
keys.add(key);
}
}
public Bitmap get(String key){
return lruCache.get(key);
}
public void remove(String key){
lruCache.remove(key);
}
public void removeAll(){
for(String k:keys){
lruCache.remove(k);
}
keys.clear();
Log.d("LocalMemoryCache", "清除图片缓存");
}
}