异步加载图片

本文介绍了一种使用Java实现的异步图像加载器,通过软引用缓存和线程异步操作来提升应用性能。该加载器能有效减轻内存压力,并在后台线程中加载图像,避免UI阻塞。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用java软缓冲和线程异步操作

import java.io.IOException;

import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;


public class AsyncImageLoader {


private HashMap<String, SoftReference<Drawable>> imageCache;


public AsyncImageLoader() {
imageCache = new HashMap<String, SoftReference<Drawable>>();
}


public Drawable loadDrawable(final String imageUrl,
final ImageView imageView, final ImageCallback imageCallback) {
if (imageCache.containsKey(imageUrl)) {

SoftReference<Drawable> softReference = imageCache.get(imageUrl);
Drawable drawable = softReference.get();
if (drawable != null) {
return drawable;
}
}
final Handler handler = new Handler() {
public void handleMessage(Message message) {
imageCallback.imageLoaded((Drawable) message.obj, imageView,
imageUrl);
}
};

new Thread() {
@Override
public void run() {
Drawable drawable = loadDrawable(imageUrl);
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
}
}.start();
return null;
}


public Drawable loadDrawable(String url) {
URL m;
InputStream i = null;
try {
m = new URL(url);
i = (InputStream) m.getContent();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Drawable d = Drawable.createFromStream(i, "src");
return d;
}




public interface ImageCallback {
public void imageLoaded(Drawable imageDrawable, ImageView imageView,
String imageUrl);
}

}

调用方法:

Drawable drawable = new AsyncImageLoader().loadDrawable(picUrl, pImageView, new ImageCallback()
{

public void imageLoaded(Drawable imageDrawable, ImageView imageView, String imageUrl)
{

imageView.setImageDrawable(imageDrawable);
}
});

if (drawable!=null)
{
pImageView.setImageDrawable(drawable);
}
}


注意 : pImageView是你要显示图片的ImageView的对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值