1.创建图片工具类ImageUtil
public class ImageUtil {
/*
*
* 使用Lru算法来将图片进行缓存,从而节省流量的使用
*
* */
static LruCache<String,Bitmap> cache = new LruCache<String,Bitmap>(5 << 20){
@Override
protected int sizeOf(String key, Bitmap value) {
int size = value.getRowBytes() * value.getHeight();
return size;
}
};
private static final Executor executor = new ScheduledThreadPoolExecutor(4);
public static void loadImage(ImageView image,String url){
Bitmap bitmap = cache.get(url);
ImageLoader loader = (ImageLoader) image.getTag();//得到当前的标签
if (loader != null){
loader.cancel(false);
}
if (bitmap != null) {
image.setImageBitmap(bitmap);
}else {
new ImageLoader(image).executeOnExecutor(executor,url);
}
}
}
2.创建图片加载器ImageLoader类
public class ImageLoader extends AsyncTask<String,Void,Bitmap> {
private ImageView image;
private String url;
public ImageLoader(ImageView image) {
this.image = image;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// ImageLoader loader = (ImageLoader) image.getTag();
// if (loader != null) {
// loader.cancel(false);
// }
image.setTag(this);//给当前的异步添加标签,来实现图片在控件的阻塞式加载
image.setImageResource(R.mipmap.coming);
}
@Override
protected Bitmap doInBackground(String... params) {
url = params[0];
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
int code = connection.getResponseCode();
if (code == 200) {
InputStream is = connection.getInputStream();
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
// BitmapFactory.decodeStream(is);
// options.inSampleSize = 2;
// options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap != null) {
image.setImageBitmap(bitmap);
ImageUtil.cache.put(url,bitmap);
}else {
image.setImageResource(R.mipmap.ic_launcher);
}
image.setTag(null);
}
@Override
protected void onCancelled(Bitmap bitmap) {
if (bitmap != null) {
ImageUtil.cache.put(url,bitmap);
}
}
}