加载图片的三种模式

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        loadImage("http://img4.imgtn.bdimg.com/it/u=1079107641,923986729&fm=21&gp=0.jpg", R.id.imageView1);
        loadImage("http://e.hiphotos.baidu.com/zhidao/wh%3D450%2C600/sign=fe006f4be950352ab1342d0c6673d7c4/267f9e2f07082838dbc3bce8b899a9014d08f104.jpg", R.id.imageView2);
        loadImage("http://img0.imgtn.bdimg.com/it/u=617019380,113848072&fm=21&gp=0.jpg", R.id.imageView5);
    }
    
    
    /**
     * Handler+Thread+Message模式
     */
//    final Handler handler=new Handler(){
//
//        @Override
//        public void handleMessage(Message msg) {
//            // TODO Auto-generated method stub
//            super.handleMessage(msg);
//             ((ImageView) MainActivity.this.findViewById(msg.arg1))
//             .setImageDrawable((Drawable) msg.obj);    
//        }
//        
//    };
//     private void loadImage(final String url, final int id) {
//                 new Thread(new Runnable() {
//                    
//                    @Override
//                    public void run() {
//                         Drawable drawable = null;
//                         try {
//                                 drawable = Drawable.createFromStream(
//                                                 new URL(url).openStream(), "image.jpg");
//                         } catch (IOException e) {
//                                 Log.d("test", e.getMessage());
//                         }
//                         if (drawable == null) {
//                                 Log.d("test", "null drawable");
//                         } else {
//                                 Log.d("test", "not null drawable");
//                         }
//                         // 为了测试缓存而模拟的网络延时
//                         SystemClock.sleep(2000);
//                        Message message=handler.obtainMessage();
//                        message.arg1=id;
//                        message.obj=drawable;
//                        handler.sendMessage(message);
//                    }
//                }).start();
//                 
//                 
//         
// }

   


    /**
     *Handler+ExecutorService(线程池)+MessageQueue模式
     *这里我们象第一步一样使用了 handler.post(new Runnable() {  更新前段显示当然是在UI主线程,
     *我们还有 executorService.submit(new Runnable() { 来确保下载是在线程池的线程中.
     */
//    private Handler handler = new Handler();
//
//    private ExecutorService executorService = Executors.newFixedThreadPool(5);
//
//    // 引入线程池来管理多线程
//    private void loadImage(final String url, final int id) {
//            executorService.submit(new Runnable() {
//                    public void run() {
//                            try {
//                                    final Drawable drawable = Drawable.createFromStream(
//                                                    new URL(url).openStream(), "image.png");
//                                    // 模拟网络延时
//                                    SystemClock.sleep(2000);
//                                    handler.post(new Runnable() {
//                                            public void run() {
//                                                    ((ImageView) MainActivity.this.findViewById(id))
//                                                                    .setImageDrawable(drawable);
//                                            }
//                                    });
//                            } catch (Exception e) {
//                                    throw new RuntimeException(e);
//                            }
//                    }
//            });

//    }



    /**
     * Handler+ExecutorService(线程池)+MessageQueue+缓存模式
     */

     private AsyncImageLoader asyncImageLoader = new AsyncImageLoader();

     // 引入线程池,并引入内存缓存功能,并对外部调用封装了接口,简化调用过程
     private void loadImage(final String url, final int id) {
             // 如果缓存过就会从缓存中取出图像,ImageCallback接口中方法也不会被执行
             Drawable cacheImage = asyncImageLoader.loadDrawable(url,
                             new AsyncImageLoader.ImageCallback() {
                                     // 请参见实现:如果第一次加载url时下面方法会执行
                                     public void imageLoaded(Drawable imageDrawable) {
                                             ((ImageView) findViewById(id))
                                                             .setImageDrawable(imageDrawable);
                                     }
                             });
             if (cacheImage != null) {
                     ((ImageView) findViewById(id)).setImageDrawable(cacheImage);
             }
     }
    
}

 class AsyncImageLoader {
    // 为了加快速度,在内存中开启缓存(主要应用于重复图片较多时,或者同一个图片要多次被访问,比如在ListView时来回滚动)
    public Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
   
    private ExecutorService executorService = Executors.newFixedThreadPool(5); // 固定五个线程来执行任务
    private final Handler handler = new Handler();

    /**
     *
     * @param imageUrl
     *            图像url地址
     * @param callback
     *            回调接口
     * @return 返回内存中缓存的图像,第一次加载返回null
     */
    public Drawable loadDrawable(final String imageUrl,
                    final ImageCallback callback) {
            // 如果缓存过就从缓存中取出数据
            if (imageCache.containsKey(imageUrl)) {
                    SoftReference<Drawable> softReference = imageCache.get(imageUrl);
                    if (softReference.get() != null) {
                            return softReference.get();
                    }
            }
            // 缓存中没有图像,则从网络上取出数据,并将取出的数据缓存到内存中
            executorService.submit(new Runnable() {
                    public void run() {
                            try {
                                    final Drawable drawable = loadImageFromUrl(imageUrl);
                                           
                                    imageCache.put(imageUrl, new SoftReference<Drawable>(
                                                    drawable));

                                    handler.post(new Runnable() {
                                            public void run() {
                                                    callback.imageLoaded(drawable);
                                            }
                                    });
                            } catch (Exception e) {
                                    throw new RuntimeException(e);
                            }
                    }
            });
            return null;
    }
 // 从网络上取数据方法
    protected Drawable loadImageFromUrl(String imageUrl) {
            try {
                    // 测试时,模拟网络延时,实际时这行代码不能有
                    SystemClock.sleep(2000);

                    return Drawable.createFromStream(new URL(imageUrl).openStream(),
                                    "image.png");

            } catch (Exception e) {
                    throw new RuntimeException(e);
            }
    }

    // 对外界开放的回调接口
    public interface ImageCallback {
            // 注意 此方法是用来设置目标对象的图像资源
            public void imageLoaded(Drawable imageDrawable);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值