引用:http://www.oschina.net/code/snippet_163910_6086
[代码] AsyncImageLoader.java
01 |
package cn.com.mzba.service; |
03 |
import java.io.InputStream; |
04 |
import java.lang.ref.SoftReference; |
06 |
import java.util.HashMap; |
08 |
import android.graphics.drawable.Drawable; |
09 |
import android.os.Handler; |
10 |
import android.os.Message; |
11 |
import android.widget.ImageView; |
17 |
public class AsyncImageLoader { |
20 |
* 软引用对象,在响应内存需要时,由垃圾回收器决定是否清除此对象。软引用对象最常用于实现内存敏感的缓存。 |
22 |
private HashMap<String, SoftReference<Drawable>> imageCache; |
24 |
public AsyncImageLoader(){ |
25 |
imageCache = new HashMap<String, SoftReference<Drawable>>(); |
28 |
public Drawable loadDrawable( final String imageUrl, final ImageView imageView, final ImageCallback imagecallback){ |
29 |
if (imageCache.containsKey(imageUrl)){ |
31 |
SoftReference<Drawable> softReference = imageCache.get(imageUrl); |
32 |
Drawable drawable = softReference.get(); |
37 |
final Handler handler = new Handler(){ |
39 |
public void handleMessage(Message msg) { |
40 |
super .handleMessage(msg); |
41 |
imagecallback.imageLoaded((Drawable)msg.obj, imageView, imageUrl); |
46 |
Drawable drawable = loadImageFromUrl(imageUrl); |
47 |
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable)); |
48 |
Message message = handler.obtainMessage( 0 , drawable); |
49 |
handler.sendMessage(message); |
56 |
public static Drawable loadImageFromUrl(String urlPath){ |
58 |
InputStream is = null ; |
60 |
url = new URL(urlPath); |
61 |
is = (InputStream)url.getContent(); |
65 |
Drawable drawable = Drawable.createFromStream(is, "src" ); |
[代码] ImageCallback.java
01 |
package cn.com.mzba.service; |
03 |
import android.graphics.drawable.Drawable; |
04 |
import android.widget.ImageView; |
06 |
public interface ImageCallback { |
07 |
public void imageLoaded(Drawable imageDrawable,ImageView imageView, String imageUrl); |
10 |
Drawable drawable = asyncImageLoader.loadDrawable(weiboInfo.getUserIcon(), viewUserIcon, new ImageCallback() { |
12 |
public void imageLoaded(Drawable imageDrawable, ImageView imageView,String imageUrl) { |
13 |
imageView.setImageDrawable(imageDrawable); |
17 |
viewUserIcon.setImageResource(R.drawable.portrait); |
19 |
viewUserIcon.setImageDrawable(drawable); |