package com.weikou.beibeivideo.util.cache;
|
|
import android.content.Context;
|
import android.content.pm.PackageInfo;
|
import android.content.pm.PackageManager;
|
|
import com.lcjian.library.util.cache.DiskLruCache;
|
import com.lcjian.library.util.common.StorageUtils;
|
|
import java.io.File;
|
import java.io.IOException;
|
|
public class DiskLruCacheManager {
|
|
private static DiskLruCacheManager instance;
|
private DiskLruCache cache;
|
|
private static int getVersionNum(Context context) {
|
try {
|
PackageInfo pi = context.getPackageManager().getPackageInfo(
|
context.getPackageName(), 0);
|
return pi.versionCode;
|
} catch (PackageManager.NameNotFoundException e) {
|
e.printStackTrace();
|
return 1;
|
}
|
}
|
|
public DiskLruCacheManager(Context context) {
|
try {
|
cache = DiskLruCache.open(
|
new File(StorageUtils.getCacheDirectory(context)
|
.toString(), "http"), getVersionNum(context),
|
1, 1024 * 1024);
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
|
}
|
|
public static DiskLruCacheManager getInstance(Context context) {
|
if (instance == null)
|
instance = new DiskLruCacheManager(context);
|
return instance;
|
}
|
|
|
public void cache(String key, String value) {
|
if (cache == null)
|
return;
|
DiskLruCache.Editor editor = null;
|
try {
|
editor = cache
|
.edit(key);
|
editor.set(0, value);
|
editor.commit();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
|
/**
|
* 取缓存
|
*
|
* @param key
|
* @return
|
*/
|
public String getCache(String key) {
|
if (cache == null)
|
return null;
|
DiskLruCache.Snapshot snapshot = null;
|
try {
|
if (cache != null) {
|
snapshot = cache.get(key);
|
if (snapshot != null) {
|
return snapshot.getString(0);
|
}
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
} finally {
|
if (snapshot != null) {
|
snapshot.close();
|
}
|
}
|
return null;
|
}
|
|
|
}
|