* 三级缓存:
* 一级缓存:内存缓存
* 二级缓存:硬盘缓存
* 三级缓存:网络缓存
*
* @author 43497
* @date 2018/3/15
*/
public class LruCacheUtil {
private static LruCache<String, Bitmap> mLruCache = new LruCache<String, Bitmap>((int) (Runtime.getRuntime().maxMemory() / 8)) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getRowBytes() * bitmap.getHeight();
}
};
public static void putCache(String url, Bitmap bitmap) {
mLruCache.put(url, bitmap);
}
public static Bitmap getCache(String url) {
return mLruCache.get(url);
}
public static void removeCache(String url) {
if (getCache(url) != null) {
mLruCache.remove(url);
}
}
public static void clearCache() {
if (mLruCache.size() > 0) {
mLruCache.evictAll();
}
}
}
public class DiskLruCacheUtil {
public static DiskLruCache mDiskLruCache;
private static int maxSize = 1024 * 1024 * 10;
public static void init(Context context) {
if (mDiskLruCache != null) {
try {
mDiskLruCache = DiskLruCache.open(getCacheFile(context, "bitmap"), getAppVersion(context), 1, maxSize);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static boolean writeCache(String url, Bitmap bitmap) {
if (url != null && bitmap != null) {
DiskLruCache.Editor editor = null;
try {
editor = mDiskLruCache.edit(url);
OutputStream outputStream = editor.newOutputStream(0);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
editor.commit();
return true;
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
public static Bitmap getCache(String url) {
if (url != null){
DiskLruCache.Snapshot snapshot = null;
try {
snapshot = mDiskLruCache.get(url);
if (snapshot != null){
InputStream inputStream = snapshot.getInputStream(0);
return BitmapFactory.decodeStream(inputStream);
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static void clearCache(){
try {
mDiskLruCache.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void flushLog(){
try {
mDiskLruCache.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void close(){
try {
mDiskLruCache.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static File getCacheFile(Context context, String endPath) {
String cachePath;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
cachePath = context.getExternalCacheDir().getAbsolutePath();
} else {
cachePath = context.getCacheDir().getAbsolutePath();
}
File cacheFile = new File(cachePath, endPath);
if (!cacheFile.exists()) {
cacheFile.mkdirs();
}
return cacheFile;
}
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return 1;
}
}