网络下载,实在LruCache机制
public class HttpManager {
private static final HttpManager sManager = new HttpManager();
public static final int NETWORK_ERROR_CODE = 1;
public static final int CONTENT_LENGTH_ERROR_CODE = 2;
public static final int TASK_RUNNING_ERROR_CODE = 3;
private Context mContext;
private OkHttpClient mClient;
private LruCache<String, Bitmap> mMemoryCache;
public static HttpManager getInstance() {
return sManager;
}
private HttpManager() {
//该缓存占用的空间不超过24MB
int mCacheSize = 24 * 1024 * 1024;
mMemoryCache = new LruCache<String, Bitmap>(mCacheSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
};
mClient = new OkHttpClient();
}
public void init(Context context) {
this.mContext = context;
};
public void asyncRequest(final String url, final DownloadCallback callback) {
//如果缓存已经存在,立即返回
if (mMemoryCache.get(url)!= null) {
Bitmap bitmap = mMemoryCache.get(url);
callback.success(bitmap);
} else {
// 如果缓存不存在,则在后台下载和解码,然后解码成功后通过回调接口通知调用者
Request request = new Request.Builder().url(url).build();
mClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful() && callback != null) {
callback.fail(NETWORK_ERROR_CODE, "请求失败");
}
File file = FileStorageManager.getInstance().getFileByName(url);
byte[] buffer = new byte[1024 * 500];
int len;
FileOutputStream fileOut = new FileOutputStream(file);
InputStream inStream = response.body().byteStream();
while ((len = inStream.read(buffer, 0, buffer.length)) != -1) {
fileOut.write(buffer, 0, len);
fileOut.flush();
}
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//单张位图大小超过6MB则不缓存
int bitmapSize=bitmap.getRowBytes()*bitmap.getHeight();
int limit=6*1024*1024;
if(bitmapSize<limit){
mMemoryCache.put(url, bitmap);
}
callback.success(bitmap);
}
});
}
}
/**
* 清除缓存
*/
public void clearLruCache(){
mMemoryCache.evictAll();
}
}