前端之家收集整理的这篇文章主要介绍了
单一职责之ImageLoader(二),
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
public class ImageCache {
LruCache<String,Bitmap> mImageCache;
public ImageCache(){
}
private void initImageCache(){
final int maxMemory = (int)(Runtime.getRuntime().maxMemory()/1024);
final int cacheSize = maxMemory/4;
mImageCache = new LruCache<String,Bitmap>(cacheSize){
@Override
protected int sizeOf(String key,Bitmap value) {
return value.getRowBytes()*value.getHeight()/1024;
}
};
}
public void put(String url,Bitmap bitmap){
mImageCache.put(url,bitmap);
}
public Bitmap get(String url){
return mImageCache.get(url);
}
}
package gac.com.chapter1.version2;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.LruCache;
import android.widget.ImageView;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/** * Created by gacmy on 2016/9/10. */
public class ImageLoader {
ImageCache mImageCache = new ImageCache();
ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().
availableProcessors());
public void displayImage(final String url,final ImageView imageView){
imageView.setTag(url);
mExecutorService.submit(new Runnable() {
@Override
public void run() {
Bitmap bitmap = downloadImage(url);
if(bitmap == null){
return ;
}
if(imageView.getTag().equals(url)){
imageView.setImageBitmap(bitmap);
}
mImageCache.put(url,bitmap);
}
});
}
public Bitmap downloadImage(String imageUrl){
Bitmap bitmap = null;
try {
URL url = new URL(imageUrl);
final HttpURLConnection conn = (HttpURLConnection)url.openConnection();
bitmap = BitmapFactory.decodeStream(conn.getInputStream());
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
}
现在代码一分为二清晰了,但是Android内存有限,每次重新启动后原来加载的图片就会丢失,所以需要改进 缓存到本地