研究了android从网络上异步加载图像:

(1)由于android UI更新支持单一线程原则,所以从网络上取数据并更新到界面上,为了不阻塞主线程首先可能会想到以下方法。

在主线程中new 一个Handler对象,加载图像方法如下所示

  1. private void loadImage(final String url, final int id) {
  2. handler.post(new Runnable() {
  3. public void run() {
  4. Drawable drawable = null;
  5. try {
  6. drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
  7. } catch (IOException e) {
  8. }
  9. ((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
  10. }
  11. });
  12. }

上面这个方法缺点很显然,经测试,如果要加载多个图片,这并不能实现异步加载,而是等到所有的图片都加载完才一起显示,因为它们都运行在一个线程中。

然后,我们可以简单改进下,将Handler+Runnable模式改为Handler+Thread+Message模式不就能实现同时开启多个线程吗?

(2)在主线程中new 一个Handler对象,代码如下:

  1. final Handler handler2=new Handler(){
  2. @Override
  3. public void handleMessage(Message msg) {
  4. ((ImageView) LazyLoadImageActivity.this.findViewById(msg.arg1)).setImageDrawable((Drawable)msg.obj);
  5. }
  6. };

对应加载图像代码如下:对应加载图像代码如下:对应加载图像代码如下:

  1. // 引入线程池来管理多线程
  2. private void loadImage3(final String url, final int id) {
  3. executorService.submit(new Runnable() {
  4. public void run() {
  5. try {
  6. final Drawable drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
  7. handler.post(new Runnable() {
  8. public void run() {
  9. ((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
  10. }
  11. });
  12. } catch (Exception e) {
  13. throw new RuntimeException(e);
  14. }
  15. }
  16. });
  17. }

(4)为了更方便使用我们可以将异步加载图像方法封装一个类,对外界只暴露一个方法即可,考虑到效率问题我们可以引入内存缓存机制,做法是

建立一个HashMap,其键(key)为加载图像url,其值(value)是图像对象Drawable。先看一下我们封装的类

  1. public class AsyncImageLoader3 {
  2. //为了加快速度,在内存中开启缓存(主要应用于重复图片较多时,或者同一个图片要多次被访问,比如在ListView时来回滚动)
  3. public Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
  4. private ExecutorService executorService = Executors.newFixedThreadPool(5);    //固定五个线程来执行任务
  5. private final Handler handler=new Handler();
  6. /**
  7. *
  8. * @param imageUrl     图像url地址
  9. * @param callback     回调接口
  10. * @return     返回内存中缓存的图像,第一次加载返回null
  11. */
  12. public Drawable loadDrawable(final String imageUrl, final ImageCallback callback) {
  13. //如果缓存过就从缓存中取出数据
  14. if (imageCache.containsKey(imageUrl)) {
  15. SoftReference<Drawable> softReference = imageCache.get(imageUrl);
  16. if (softReference.get() != null) {
  17. return softReference.get();
  18. }
  19. }
  20. //缓存中没有图像,则从网络上取出数据,并将取出的数据缓存到内存中
  21. executorService.submit(new Runnable() {
  22. public void run() {
  23. try {
  24. final Drawable drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");
  25. imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
  26. handler.post(new Runnable() {
  27. public void run() {
  28. callback.imageLoaded(drawable);
  29. }
  30. });
  31. } catch (Exception e) {
  32. throw new RuntimeException(e);
  33. }
  34. }
  35. });
  36. return null;
  37. }
  38. //从网络上取数据方法
  39. protected Drawable loadImageFromUrl(String imageUrl) {
  40. try {
  41. return Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");
  42. } catch (Exception e) {
  43. throw new RuntimeException(e);
  44. }
  45. }
  46. //对外界开放的回调接口
  47. public interface ImageCallback {
  48. //注意 此方法是用来设置目标对象的图像资源
  49. public void imageLoaded(Drawable imageDrawable);
  50. }
  51. }

这样封装好后使用起来就方便多了。在主线程中首先要引入AsyncImageLoader3 对象,然后直接调用其loadDrawable方法即可,需要注意的是ImageCallback接口的imageLoaded方法是唯一可以把加载的图像设置到目标ImageView或其相关的组件上。

在主线程调用代码:

先实例化对象 private AsyncImageLoader3 asyncImageLoader3 = new AsyncImageLoader3();

调用异步加载方法:

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

5)同理,下面也给出采用Thread+Handler+MessageQueue+内存缓存代码,原则同(4),只是把线程池换成了Thread+Handler+MessageQueue模式而已。代码如下:5)同理,下面也给出采用Thread+Handler+MessageQueue+内存缓存代码,原则同(4),只是把线程池换成了Thread+Handler+MessageQueue模式而已。代码如下:

  1. public class AsyncImageLoader {
  2. //为了加快速度,加入了缓存(主要应用于重复图片较多时,或者同一个图片要多次被访问,比如在ListView时来回滚动)
  3. private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
  4. /**
  5. *
  6. * @param imageUrl     图像url地址
  7. * @param callback     回调接口
  8. * @return     返回内存中缓存的图像,第一次加载返回null
  9. */
  10. public Drawable loadDrawable(final String imageUrl, final ImageCallback callback) {
  11. //如果缓存过就从缓存中取出数据
  12. if (imageCache.containsKey(imageUrl)) {
  13. SoftReference<Drawable> softReference = imageCache.get(imageUrl);
  14. if (softReference.get() != null) {
  15. return softReference.get();
  16. }
  17. }
  18. final Handler handler = new Handler() {
  19. @Override
  20. public void handleMessage(Message msg) {
  21. callback.imageLoaded((Drawable) msg.obj);
  22. }
  23. };
  24. new Thread() {
  25. public void run() {
  26. Drawable drawable = loadImageFromUrl(imageUrl);
  27. imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
  28. handler.sendMessage(handler.obtainMessage(0, drawable));
  29. }
  30. }.start();
  31. /*
  32. 下面注释的这段代码是Handler的一种代替方法
  33. */
  34. //        new AsyncTask() {
  35. //            @Override
  36. //            protected Drawable doInBackground(Object... objects) {
  37. //                  Drawable drawable = loadImageFromUrl(imageUrl);
  38. //                imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
  39. //                return  drawable;
  40. //            }
  41. //
  42. //            @Override
  43. //            protected void onPostExecute(Object o) {
  44. //                  callback.imageLoaded((Drawable) o);
  45. //            }
  46. //        }.execute();
  47. return null;
  48. }
  49. protected Drawable loadImageFromUrl(String imageUrl) {
  50. try {
  51. return Drawable.createFromStream(new URL(imageUrl).openStream(), "src");
  52. } catch (Exception e) {
  53. throw new RuntimeException(e);
  54. }
  55. }
  56. //对外界开放的回调接口
  57. public interface ImageCallback {
  58. public void imageLoaded(Drawable imageDrawable);
  59. }
  60. }

至此,异步加载就介绍完了,下面给出的代码为测试用的完整代码:

  1. package com.bshark.supertelphone.activity;
  2. import android.app.Activity;
  3. import android.graphics.drawable.Drawable;
  4. import android.os.Bundle;
  5. import android.os.Handler;
  6. import android.os.Message;
  7. import android.widget.ImageView;
  8. import com.bshark.supertelphone.R;
  9. import com.bshark.supertelphone.ui.adapter.util.AsyncImageLoader;
  10. import com.bshark.supertelphone.ui.adapter.util.AsyncImageLoader3;
  11. import java.io.IOException;
  12. import java.net.URL;
  13. import java.util.concurrent.ExecutorService;
  14. import java.util.concurrent.Executors;
  15. public class LazyLoadImageActivity extends Activity {
  16. final Handler handler=new Handler();
  17. final Handler handler2=new Handler(){
  18. @Override
  19. public void handleMessage(Message msg) {
  20. ((ImageView) LazyLoadImageActivity.this.findViewById(msg.arg1)).setImageDrawable((Drawable)msg.obj);
  21. }
  22. };
  23. private ExecutorService executorService = Executors.newFixedThreadPool(5);    //固定五个线程来执行任务
  24. private AsyncImageLoader asyncImageLoader = new AsyncImageLoader();
  25. private AsyncImageLoader3 asyncImageLoader3 = new AsyncImageLoader3();
  26. @Override
  27. public void onCreate(Bundle savedInstanceState) {
  28. super.onCreate(savedInstanceState);
  29. setContentView(R.layout.main);
  30. //  loadImage("http://www.chinatelecom.com.cn/images/logo_new.gif", R.id.image1);
  31. //  loadImage("http://www.baidu.com/img/baidu_logo.gif", R.id.image2);
  32. //  loadImage("http://cache.soso.com/30d/img/web/logo.gif", R.id.image3);
  33. //        loadImage("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
  34. //  loadImage("http://cache.soso.com/30d/img/web/logo.gif", R.id.image5);
  35. loadImage2("http://www.chinatelecom.com.cn/images/logo_new.gif", R.id.image1);
  36. loadImage2("http://www.baidu.com/img/baidu_logo.gif", R.id.image2);
  37. loadImage2("http://cache.soso.com/30d/img/web/logo.gif", R.id.image3);
  38. loadImage2("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
  39. loadImage2("http://cache.soso.com/30d/img/web/logo.gif", R.id.image5);
  40. //        loadImage3("http://www.chinatelecom.com.cn/images/logo_new.gif", R.id.image1);
  41. //  loadImage3("http://www.baidu.com/img/baidu_logo.gif", R.id.image2);
  42. //  loadImage3("http://cache.soso.com/30d/img/web/logo.gif", R.id.image3);
  43. //        loadImage3("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
  44. //  loadImage3("http://cache.soso.com/30d/img/web/logo.gif", R.id.image5);
  45. //        loadImage4("http://www.chinatelecom.com.cn/images/logo_new.gif", R.id.image1);
  46. //  loadImage4("http://www.baidu.com/img/baidu_logo.gif", R.id.image2);
  47. //  loadImage4("http://cache.soso.com/30d/img/web/logo.gif", R.id.image3);
  48. //        loadImage4("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
  49. //  loadImage4("http://cache.soso.com/30d/img/web/logo.gif", R.id.image5);
  50. //        loadImage5("http://www.chinatelecom.com.cn/images/logo_new.gif", R.id.image1);
  51. //        //为了测试缓存而模拟的网络延时
  52. //        SystemClock.sleep(2000);
  53. //  loadImage5("http://www.baidu.com/img/baidu_logo.gif", R.id.image2);
  54. //        SystemClock.sleep(2000);
  55. //  loadImage5("http://cache.soso.com/30d/img/web/logo.gif", R.id.image3);
  56. //        SystemClock.sleep(2000);
  57. //        loadImage5("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
  58. //        SystemClock.sleep(2000);
  59. //  loadImage5("http://cache.soso.com/30d/img/web/logo.gif", R.id.image5);
  60. //        SystemClock.sleep(2000);
  61. //         loadImage5("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
  62. }
  63. @Override
  64. protected void onDestroy() {
  65. executorService.shutdown();
  66. super.onDestroy();
  67. }
  68. //线程加载图像基本原理
  69. private void loadImage(final String url, final int id) {
  70. handler.post(new Runnable() {
  71. public void run() {
  72. Drawable drawable = null;
  73. try {
  74. drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
  75. } catch (IOException e) {
  76. }
  77. ((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
  78. }
  79. });
  80. }
  81. //采用handler+Thread模式实现多线程异步加载
  82. private void loadImage2(final String url, final int id) {
  83. Thread thread = new Thread(){
  84. @Override
  85. public void run() {
  86. Drawable drawable = null;
  87. try {
  88. drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
  89. } catch (IOException e) {
  90. }
  91. Message message= handler2.obtainMessage() ;
  92. message.arg1 = id;
  93. message.obj = drawable;
  94. handler2.sendMessage(message);
  95. }
  96. };
  97. thread.start();
  98. thread = null;
  99. }
  100. // 引入线程池来管理多线程
  101. private void loadImage3(final String url, final int id) {
  102. executorService.submit(new Runnable() {
  103. public void run() {
  104. try {
  105. final Drawable drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
  106. handler.post(new Runnable() {
  107. public void run() {
  108. ((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
  109. }
  110. });
  111. } catch (Exception e) {
  112. throw new RuntimeException(e);
  113. }
  114. }
  115. });
  116. }
  117. //引入线程池,并引入内存缓存功能,并对外部调用封装了接口,简化调用过程
  118. private void loadImage4(final String url, final int id) {
  119. //如果缓存过就会从缓存中取出图像,ImageCallback接口中方法也不会被执行
  120. Drawable cacheImage = asyncImageLoader.loadDrawable(url,new AsyncImageLoader.ImageCallback() {
  121. //请参见实现:如果第一次加载url时下面方法会执行
  122. public void imageLoaded(Drawable imageDrawable) {
  123. ((ImageView) findViewById(id)).setImageDrawable(imageDrawable);
  124. }
  125. });
  126. if(cacheImage!=null){
  127. ((ImageView) findViewById(id)).setImageDrawable(cacheImage);
  128. }
  129. }
  130. //采用Handler+Thread+封装外部接口
  131. private void loadImage5(final String url, final int id) {
  132. //如果缓存过就会从缓存中取出图像,ImageCallback接口中方法也不会被执行
  133. Drawable cacheImage = asyncImageLoader3.loadDrawable(url,new AsyncImageLoader3.ImageCallback() {
  134. //请参见实现:如果第一次加载url时下面方法会执行
  135. public void imageLoaded(Drawable imageDrawable) {
  136. ((ImageView) findViewById(id)).setImageDrawable(imageDrawable);
  137. }
  138. });
  139. if(cacheImage!=null){
  140. ((ImageView) findViewById(id)).setImageDrawable(cacheImage);
  141. }
  142. }
  143. }

xml文件大致如下:

    1. <?xml version="1.0" encoding="utf-8"?>
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. android:layout_width="fill_parent"
    4. android:orientation="vertical"
    5. android:layout_height="fill_parent" >
    6. <ImageView android:id="@+id/image1" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
    7. <ImageView android:id="@+id/image2" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
    8. <ImageView android:id="@+id/image3" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
    9. <ImageView android:id="@+id/image5" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
    10. <ImageView android:id="@+id/image4" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
    11. </LinearLayout>

Android异步加载图像(含线程池,缓存方法)的更多相关文章

  1. 转: Android异步加载图像小结

    转:http://blog.csdn.net/sgl870927/article/details/6285535 研究了android从网络上异步加载图像,现总结如下: (1)由于android UI ...

  2. 演化理解 Android 异步加载图片

    原文:http://www.cnblogs.com/ghj1976/archive/2011/05/06/2038738.html#3018499 在学习"Android异步加载图像小结&q ...

  3. Android异步加载

    一.为什么要使用异步加载? 1.Android是单线程模型 2.耗时操作阻碍UI线程 二.异步加载最常用的两种方式 1.多线程.线程池 2.AsyncTask 三.实现ListView图文混排 3-1 ...

  4. [转载]Android 异步加载解决方案

    2013-12-25 11:15:47 Android 异步加载解决方案,转载自: http://www.open-open.com/lib/view/open1345017746897.html 请 ...

  5. 演化理解 Android 异步加载图片(转)

    演化理解 Android 异步加载图片(转)http://www.cnblogs.com/CJzhang/archive/2011/10/20/2218474.html

  6. 实例演示Android异步加载图片

    本文给大家演示异步加载图片的分析过程.让大家了解异步加载图片的好处,以及如何更新UI.首先给出main.xml布局文件:简单来说就是 LinearLayout 布局,其下放了2个TextView和5个 ...

  7. 实例演示Android异步加载图片(转)

    本文给大家演示异步加载图片的分析过程.让大家了解异步加载图片的好处,以及如何更新UI.首先给出main.xml布局文件:简单来说就是 LinearLayout 布局,其下放了2个TextView和5个 ...

  8. Android 异步加载图片,使用LruCache和SD卡或手机缓存,效果非常的流畅

      Android 高手进阶(21)  版权声明:本文为博主原创文章,未经博主允许不得转载. 转载请注明出处http://blog.csdn.net/xiaanming/article/details ...

  9. Android 异步加载数据 AsyncTask异步更新界面

    官方文档:     AsyncTask enables proper and easy use of the UI thread. This class allows to perform backg ...

随机推荐

  1. intel 系列的PC机处理器是大端的还是小端的?

    intel 系列的PC机处理器是大端的还是小端的?由于要安装oracle,需要知道是大端机器还是小端的,你好,现在流行的PC,是微型处理器,也就是所谓的小端处理器. 大端处理器是由若干个微型处理器有机 ...

  2. ASP.NET MVC学习笔记-----Bundles

    在网页中,我们经常需要引用大量的javascript和css文件,在加上许多javascript库都包含debug版和经过压缩的release版(比如jquery),不仅麻烦还很容易引起混乱,所以AS ...

  3. springmvc 定时器

    CronTrigger配置格式: 格式: [秒] [分] [小时] [日] [月] [周] [年] 序号 说明  是否必填  允许填写的值 允许的通配符 1  秒  是  0-59    , - *  ...

  4. Unity 3D学习之 Prime31 Game Center插件用法

    http://momowing.diandian.com/post/2012-11-08/40041806328 It's my life~: 为app 连入Game Center 功能而困扰的朋友们 ...

  5. unity3d iPhone文件目录介绍

    原地址:http://cl314413.blog.163.com/blog/static/190507976201210259126559/ 如何查看iPhone文件存放目录?首先需要越狱,越狱后打开 ...

  6. select function in ruby

    http://ruby-doc.org/ http://ruby-doc.org/core-2.3.0/Array.html#method-i-select [1,2,3,4,5].select { ...

  7. SQL注入--宽字节注入

    PHP测试代码: <?php // 面向对象写法 $id=addslashes($_GET[‘id’]); //获取id并转义预定义字符 // /$id=$_GET[‘id’]; $mysqli ...

  8. tomcat配置文件之Server.xml

    Server.xml包含的元素有<Server>.<Service>.<Connector>.<Engine>.<Host>.<Con ...

  9. php页面打开响应时间

    $start_time = array_sum(explode(' ',microtime())); //your code here   $end_time = array_sum(explode( ...

  10. HDOJ 1301

    9852303 2013-12-18 11:47:01 Accepted 1301 0MS 264K 1117 B C++ 泽泽 Jungle Roads Time Limit: 2000/1000 ...