Android 应用中需要显示网络图片时,图片的加载过程较为耗时,因此加载过程使用线程池进行管理,
同时使用本地缓存保存图片(当来回滚动ListView时,调用缓存的图片),这样加载和显示图片较为友好。
参考:http://www.eoeandroid.com/thread-210082-1-1.html?_dsign=1b202888
核心代码:
1. MainActivity
package com.desmand.threadtest; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.ImageView; import java.io.IOException; import java.net.URL; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); loadImage("http://www.baidu.com/img/baidu_logo.gif", R.id.imageView1, 1); loadImage("http://cn.bing.com/sa/simg/bing_p_rr_teal.ico", R.id.imageView2, 2); loadImage("http://cache.soso.com/30d/img/web/logo.gif", R.id.imageView3, 3); loadImage("http://csdnimg.cn/www/images/csdnindex_logo.gif", R.id.imageView4, 4); loadImage("http://images.cnblogs.com/logo_small.gif", R.id.imageView5, 5); } // 4. 引入线程池,并引入内存缓存功能,并对外部调用封装了接口,简化调用过程 private AsyncImageLoader asyncImageLoader = new AsyncImageLoader(); private void loadImage(String url, final int id, final int count){ // 如果缓存过就会从缓存中取出图像,ImageCallback接口中方法也不会被执行 Drawable cacheImage = asyncImageLoader.loadDrawable(url, new AsyncImageLoader.ImageCallback() { // 请参见实现:如果第一次加载url时下面方法会执行 @Override public void imageLoaded(Drawable imageDrawable) { ((ImageView) findViewById(id)).setImageDrawable(imageDrawable); Log.i("test", "1count: " + count); } }); if (cacheImage != null){ ((ImageView) findViewById(id)).setImageDrawable(cacheImage); Log.i("test", "2count: " + count); } } // 3. 引入线程池来管理多线程 // private Handler handler3 = new Handler(); // private ExecutorService executorService = Executors.newFixedThreadPool(5); // // private void loadImage(final String url, final int id, final int count) { // executorService.submit(new Runnable() { // @Override // public void run() { // final Drawable drawable; // try { // drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png"); // // //模拟网络延时 // SystemClock.sleep(2000); // handler3.post(new Runnable() { // @Override // public void run() { // ((ImageView) MainActivity.this.findViewById(id)).setImageDrawable(drawable); // Log.i("test", "count: " + count); // } // }); // } catch (IOException e) { // e.printStackTrace(); // } // } // }); // } // 2. 采用handler+Thread模式实现多线程异步加载 // final Handler handler2 = new Handler() { // @Override // public void handleMessage(Message msg) { // ((ImageView) MainActivity.this.findViewById(msg.arg1)).setImageDrawable((Drawable) msg.obj); // Log.i("test", "count: " + msg.arg2); // } // }; // // private void loadImage(final String url, final int id, final int count) { // Thread thread = new Thread() { // @Override // public void run() { // Drawable drawable = null; // try { // drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png"); // } catch (IOException e) { // Log.d("test", e.getMessage()); // } // // // 模拟网络延时 // SystemClock.sleep(2000); // // Message message = handler2.obtainMessage(); // message.arg1 = id; // message.obj = drawable; // message.arg2 = count; // handler2.sendMessage(message); // } // }; // thread.start(); // } // 1. 主线程直接加载,不可用 // private Handler handler = new Handler(); // private void loadImage(final String url, final int id, final int count) { // handler.post(new Runnable() { // public void run() { // Drawable drawable = null; // try { // drawable = Drawable.createFromStream(new URL(url).openStream(), "image.gif"); // } 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); // // ((ImageView) MainActivity.this.findViewById(id)).setImageDrawable(drawable); // } // }); // } }
2. AsyncImageLoader
package com.desmand.threadtest; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.SystemClock; 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; /** * Created by fansen on 2016/02/23. */ public class AsyncImageLoader { // 为了加快速度,在内存中开启缓存(主要应用于重复图片较多时,或者同一个图片要多次被访问,比如在ListView时来回滚动) public Map<String, SoftReference<Drawable>> imageCache = new HashMap<>(); private ExecutorService executorService = Executors.newFixedThreadPool(5); private 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() { @Override public void run() { final Drawable drawable = loadImageFromUrl(imageUrl); imageCache.put(imageUrl, new SoftReference<>(drawable)); handler.post(new Runnable() { @Override public void run() { callback.imageLoaded(drawable); } }); } }); return null; } // 从网络上取数据方法 protected Drawable loadImageFromUrl(String imageUrl) { try { // 测试时,模拟网络延时,实际时这行代码不能有 SystemClock.sleep(2000); return Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png"); } catch (IOException e) { e.printStackTrace(); } return null; } //对外界开放的回调接口 public interface ImageCallback { //注意 此方法是用来设置目标对象的图像资源 void imageLoaded(Drawable imageDrawable); } }