android 异步加载图片

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

AsyncImageLoader.java

package cn.com.mzba.service;

import java.io.InputStream;
import java.lang.ref.SoftReference;
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;
/**
 * 实现图片的异步载入显示
 * @author kandanle
 *
 */
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(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                imagecallback.imageLoaded((Drawable)msg.obj, imageView, imageUrl);
            }
        };
        new Thread(){
            public void run() {
                Drawable drawable = loadImageFromUrl(imageUrl);
                imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
                Message message = handler.obtainMessage(0, drawable);
                handler.sendMessage(message);
            }
        }.start();

        return null;
    }

    public static Drawable loadImageFromUrl(String urlPath){
        URL url;
        InputStream is = null;
        try{
            url = new URL(urlPath);
            is = (InputStream)url.getContent();
        }catch(Exception e){
            e.printStackTrace();
        }
        Drawable drawable = Drawable.createFromStream(is, "src");
        return drawable;
    }

}

ImageCallback.java

package cn.com.mzba.service;

import android.graphics.drawable.Drawable;
import android.widget.ImageView;

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

Drawable drawable = asyncImageLoader.loadDrawable(weiboInfo.getUserIcon(), viewUserIcon, new ImageCallback() {
    @Override
    public void imageLoaded(Drawable imageDrawable, ImageView imageView,String imageUrl) {
    imageView.setImageDrawable(imageDrawable);
        }
});
if(drawable == null){
    viewUserIcon.setImageResource(R.drawable.portrait);
}else{
    viewUserIcon.setImageDrawable(drawable);
}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:IOS开发—网络监听

下一篇:C#自定读取配置文件类