app一旦退出了,从新进入,缓存就没了。这里缓存只用于app不退出,多次加载时,只需加载一次。
逻辑类:
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* 核心:LruCache图片缓存
* Created by liuyan on 2018/9/10.
* 该类用来加载网络图片,并缓存到本地和内存
*/
//单例模式
public class SimpleImageLoader {
private Handler handler = new Handler(Looper.getMainLooper());
private static SimpleImageLoader mLoader;
private LruCache<String,Bitmap> mLrucache;
public static SimpleImageLoader getInstance(){
if (mLoader == null){
synchronized(SimpleImageLoader.class){
if (mLoader == null){
mLoader = new SimpleImageLoader();
}
}
}
return mLoader;
}
//用来初始化缓存对象
private SimpleImageLoader(){
int maxSize = (int) (Runtime.getRuntime().maxMemory() / 8); //把应用最大内存除以8大小用于缓存
mLrucache = new LruCache<String ,Bitmap>(maxSize){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
};
}
//用来加载网络图片
public void displayImage(ImageView view , String url){
Bitmap bitmap = getBitmapFromCatch(url);
if (bitmap != null && view != null){
Log.i("TAG" , "从内存获取");
view.setImageBitmap(bitmap);
Log.i("TAG" , "结束1");
}else {
downloadImage(view , url);
}
}
//从缓存中读取图片
private Bitmap getBitmapFromCatch(String url){
return mLrucache.get(url);
}
//将下载的图片保存到缓存中
private void putBitmapToCache(Bitmap bitmap , String url){
if (bitmap != null) {
mLrucache.put(url, bitmap);
}
}
//下载图片,并添加到缓存中去
private void downloadImage(final ImageView imageView , final String url){
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG" ,"加载图片失败 " + "所在线程:" + Thread.currentThread().getName());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i("TAG" , "下载图片所在线程:" + Thread.currentThread().getName());
Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream());
if (bitmap != null){
putBitmapToCache(bitmap , url);
if (getBitmapFromCatch(url) != null){
if (imageView != null){
handler.post(new Runnable() {
@Override
public void run() {
Log.i("TAG" , "run所在线程:" + Thread.currentThread().getName());
imageView.setImageBitmap(getBitmapFromCatch(url));
Log.i("TAG" , "结束2");
}
});
}
}
}
}
});
}
}