Android异步加载图像(含线程池,缓存方法)
研究了android从网络上异步加载图像:
(1)由于android UI更新支持单一线程原则,所以从网络上取数据并更新到界面上,为了不阻塞主线程首先可能会想到以下方法。
在主线程中new 一个Handler对象,加载图像方法如下所示
- private void loadImage(final String url, final int id) {
- handler.post(new Runnable() {
- public void run() {
- Drawable drawable = null;
- try {
- drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
- } catch (IOException e) {
- }
- ((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
- }
- });
- }
上面这个方法缺点很显然,经测试,如果要加载多个图片,这并不能实现异步加载,而是等到所有的图片都加载完才一起显示,因为它们都运行在一个线程中。
然后,我们可以简单改进下,将Handler+Runnable模式改为Handler+Thread+Message模式不就能实现同时开启多个线程吗?
(2)在主线程中new 一个Handler对象,代码如下:
- final Handler handler2=new Handler(){
- @Override
- public void handleMessage(Message msg) {
- ((ImageView) LazyLoadImageActivity.this.findViewById(msg.arg1)).setImageDrawable((Drawable)msg.obj);
- }
- };
对应加载图像代码如下:对应加载图像代码如下:对应加载图像代码如下:
- // 引入线程池来管理多线程
- private void loadImage3(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");
- handler.post(new Runnable() {
- public void run() {
- ((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
- }
- });
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- });
- }
(4)为了更方便使用我们可以将异步加载图像方法封装一个类,对外界只暴露一个方法即可,考虑到效率问题我们可以引入内存缓存机制,做法是
建立一个HashMap,其键(key)为加载图像url,其值(value)是图像对象Drawable。先看一下我们封装的类
- public class AsyncImageLoader3 {
- //为了加快速度,在内存中开启缓存(主要应用于重复图片较多时,或者同一个图片要多次被访问,比如在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 = Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");
- 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 {
- return Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- //对外界开放的回调接口
- public interface ImageCallback {
- //注意 此方法是用来设置目标对象的图像资源
- public void imageLoaded(Drawable imageDrawable);
- }
- }
这样封装好后使用起来就方便多了。在主线程中首先要引入AsyncImageLoader3 对象,然后直接调用其loadDrawable方法即可,需要注意的是ImageCallback接口的imageLoaded方法是唯一可以把加载的图像设置到目标ImageView或其相关的组件上。
在主线程调用代码:
先实例化对象 private AsyncImageLoader3 asyncImageLoader3 = new AsyncImageLoader3();
调用异步加载方法:
- //引入线程池,并引入内存缓存功能,并对外部调用封装了接口,简化调用过程
- private void loadImage4(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);
- }
- }
5)同理,下面也给出采用Thread+Handler+MessageQueue+内存缓存代码,原则同(4),只是把线程池换成了Thread+Handler+MessageQueue模式而已。代码如下:5)同理,下面也给出采用Thread+Handler+MessageQueue+内存缓存代码,原则同(4),只是把线程池换成了Thread+Handler+MessageQueue模式而已。代码如下:
- public class AsyncImageLoader {
- //为了加快速度,加入了缓存(主要应用于重复图片较多时,或者同一个图片要多次被访问,比如在ListView时来回滚动)
- private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
- /**
- *
- * @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();
- }
- }
- final Handler handler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- callback.imageLoaded((Drawable) msg.obj);
- }
- };
- new Thread() {
- public void run() {
- Drawable drawable = loadImageFromUrl(imageUrl);
- imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
- handler.sendMessage(handler.obtainMessage(0, drawable));
- }
- }.start();
- /*
- 下面注释的这段代码是Handler的一种代替方法
- */
- // new AsyncTask() {
- // @Override
- // protected Drawable doInBackground(Object... objects) {
- // Drawable drawable = loadImageFromUrl(imageUrl);
- // imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
- // return drawable;
- // }
- //
- // @Override
- // protected void onPostExecute(Object o) {
- // callback.imageLoaded((Drawable) o);
- // }
- // }.execute();
- return null;
- }
- protected Drawable loadImageFromUrl(String imageUrl) {
- try {
- return Drawable.createFromStream(new URL(imageUrl).openStream(), "src");
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- //对外界开放的回调接口
- public interface ImageCallback {
- public void imageLoaded(Drawable imageDrawable);
- }
- }
至此,异步加载就介绍完了,下面给出的代码为测试用的完整代码:
- package com.bshark.supertelphone.activity;
- import android.app.Activity;
- import android.graphics.drawable.Drawable;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.widget.ImageView;
- import com.bshark.supertelphone.R;
- import com.bshark.supertelphone.ui.adapter.util.AsyncImageLoader;
- import com.bshark.supertelphone.ui.adapter.util.AsyncImageLoader3;
- import java.io.IOException;
- import java.net.URL;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- public class LazyLoadImageActivity extends Activity {
- final Handler handler=new Handler();
- final Handler handler2=new Handler(){
- @Override
- public void handleMessage(Message msg) {
- ((ImageView) LazyLoadImageActivity.this.findViewById(msg.arg1)).setImageDrawable((Drawable)msg.obj);
- }
- };
- private ExecutorService executorService = Executors.newFixedThreadPool(5); //固定五个线程来执行任务
- private AsyncImageLoader asyncImageLoader = new AsyncImageLoader();
- private AsyncImageLoader3 asyncImageLoader3 = new AsyncImageLoader3();
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // loadImage("http://www.chinatelecom.com.cn/images/logo_new.gif", R.id.image1);
- // loadImage("http://www.baidu.com/img/baidu_logo.gif", R.id.image2);
- // loadImage("http://cache.soso.com/30d/img/web/logo.gif", R.id.image3);
- // loadImage("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
- // loadImage("http://cache.soso.com/30d/img/web/logo.gif", R.id.image5);
- loadImage2("http://www.chinatelecom.com.cn/images/logo_new.gif", R.id.image1);
- loadImage2("http://www.baidu.com/img/baidu_logo.gif", R.id.image2);
- loadImage2("http://cache.soso.com/30d/img/web/logo.gif", R.id.image3);
- loadImage2("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
- loadImage2("http://cache.soso.com/30d/img/web/logo.gif", R.id.image5);
- // loadImage3("http://www.chinatelecom.com.cn/images/logo_new.gif", R.id.image1);
- // loadImage3("http://www.baidu.com/img/baidu_logo.gif", R.id.image2);
- // loadImage3("http://cache.soso.com/30d/img/web/logo.gif", R.id.image3);
- // loadImage3("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
- // loadImage3("http://cache.soso.com/30d/img/web/logo.gif", R.id.image5);
- // loadImage4("http://www.chinatelecom.com.cn/images/logo_new.gif", R.id.image1);
- // loadImage4("http://www.baidu.com/img/baidu_logo.gif", R.id.image2);
- // loadImage4("http://cache.soso.com/30d/img/web/logo.gif", R.id.image3);
- // loadImage4("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
- // loadImage4("http://cache.soso.com/30d/img/web/logo.gif", R.id.image5);
- // loadImage5("http://www.chinatelecom.com.cn/images/logo_new.gif", R.id.image1);
- // //为了测试缓存而模拟的网络延时
- // SystemClock.sleep(2000);
- // loadImage5("http://www.baidu.com/img/baidu_logo.gif", R.id.image2);
- // SystemClock.sleep(2000);
- // loadImage5("http://cache.soso.com/30d/img/web/logo.gif", R.id.image3);
- // SystemClock.sleep(2000);
- // loadImage5("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
- // SystemClock.sleep(2000);
- // loadImage5("http://cache.soso.com/30d/img/web/logo.gif", R.id.image5);
- // SystemClock.sleep(2000);
- // loadImage5("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
- }
- @Override
- protected void onDestroy() {
- executorService.shutdown();
- super.onDestroy();
- }
- //线程加载图像基本原理
- private void loadImage(final String url, final int id) {
- handler.post(new Runnable() {
- public void run() {
- Drawable drawable = null;
- try {
- drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
- } catch (IOException e) {
- }
- ((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
- }
- });
- }
- //采用handler+Thread模式实现多线程异步加载
- private void loadImage2(final String url, final int id) {
- Thread thread = new Thread(){
- @Override
- public void run() {
- Drawable drawable = null;
- try {
- drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
- } catch (IOException e) {
- }
- Message message= handler2.obtainMessage() ;
- message.arg1 = id;
- message.obj = drawable;
- handler2.sendMessage(message);
- }
- };
- thread.start();
- thread = null;
- }
- // 引入线程池来管理多线程
- private void loadImage3(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");
- handler.post(new Runnable() {
- public void run() {
- ((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
- }
- });
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- });
- }
- //引入线程池,并引入内存缓存功能,并对外部调用封装了接口,简化调用过程
- private void loadImage4(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);
- }
- }
- //采用Handler+Thread+封装外部接口
- private void loadImage5(final String url, final int id) {
- //如果缓存过就会从缓存中取出图像,ImageCallback接口中方法也不会被执行
- Drawable cacheImage = asyncImageLoader3.loadDrawable(url,new AsyncImageLoader3.ImageCallback() {
- //请参见实现:如果第一次加载url时下面方法会执行
- public void imageLoaded(Drawable imageDrawable) {
- ((ImageView) findViewById(id)).setImageDrawable(imageDrawable);
- }
- });
- if(cacheImage!=null){
- ((ImageView) findViewById(id)).setImageDrawable(cacheImage);
- }
- }
- }
xml文件大致如下:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:orientation="vertical"
- android:layout_height="fill_parent" >
- <ImageView android:id="@+id/image1" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
- <ImageView android:id="@+id/image2" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
- <ImageView android:id="@+id/image3" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
- <ImageView android:id="@+id/image5" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
- <ImageView android:id="@+id/image4" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
- </LinearLayout>
Android异步加载图像(含线程池,缓存方法)的更多相关文章
- 转: Android异步加载图像小结
转:http://blog.csdn.net/sgl870927/article/details/6285535 研究了android从网络上异步加载图像,现总结如下: (1)由于android UI ...
- 演化理解 Android 异步加载图片
原文:http://www.cnblogs.com/ghj1976/archive/2011/05/06/2038738.html#3018499 在学习"Android异步加载图像小结&q ...
- Android异步加载
一.为什么要使用异步加载? 1.Android是单线程模型 2.耗时操作阻碍UI线程 二.异步加载最常用的两种方式 1.多线程.线程池 2.AsyncTask 三.实现ListView图文混排 3-1 ...
- [转载]Android 异步加载解决方案
2013-12-25 11:15:47 Android 异步加载解决方案,转载自: http://www.open-open.com/lib/view/open1345017746897.html 请 ...
- 演化理解 Android 异步加载图片(转)
演化理解 Android 异步加载图片(转)http://www.cnblogs.com/CJzhang/archive/2011/10/20/2218474.html
- 实例演示Android异步加载图片
本文给大家演示异步加载图片的分析过程.让大家了解异步加载图片的好处,以及如何更新UI.首先给出main.xml布局文件:简单来说就是 LinearLayout 布局,其下放了2个TextView和5个 ...
- 实例演示Android异步加载图片(转)
本文给大家演示异步加载图片的分析过程.让大家了解异步加载图片的好处,以及如何更新UI.首先给出main.xml布局文件:简单来说就是 LinearLayout 布局,其下放了2个TextView和5个 ...
- Android 异步加载图片,使用LruCache和SD卡或手机缓存,效果非常的流畅
Android 高手进阶(21) 版权声明:本文为博主原创文章,未经博主允许不得转载. 转载请注明出处http://blog.csdn.net/xiaanming/article/details ...
- Android 异步加载数据 AsyncTask异步更新界面
官方文档: AsyncTask enables proper and easy use of the UI thread. This class allows to perform backg ...
随机推荐
- 转:浅谈Radius协议 -来自CSDN:http://blog.csdn.net/wangpengqi/article/details/17097221
浅谈Radius协议 2013-12-03 16:06 5791人阅读 评论(0) 收藏 举报 分类: Radius协议分析(6) 从事Radius协议开发有段时间了,小弟不怕才疏学浅,卖弄一下, ...
- 淘宝(阿里百川)手机客户端开发日记第六篇 Service详解(六)
Service和Thread的关系 不少初学者都可能会有这样的疑惑,Service和Thread到底有什么关系呢?什么时候应该用Service,什么时候又应该用Thread? 答案是Service和T ...
- codeforces 258div2 A Game With Sticks(DP)
题目链接:http://codeforces.com/contest/451/problem/A 解题报告:有n跟红色的棍子横着放,m根蓝色的棍子竖着放,它们形成n*m个交点,两个人轮流在里面选择交点 ...
- 深入学习微框架:Spring Boot - NO
http://blog.csdn.net/hengyunabc/article/details/50120001 Our primary goals are: Provide a radically ...
- java 实现二分查找法
/** * 二分查找又称折半查找,它是一种效率较高的查找方法. [二分查找要求]:1.必须采用顺序存储结构 2.必须按关键字大小有序排列. * @author Administrator * */ p ...
- php对象引用和析构函数的关系
在php中构造函数和析构函数都属于魔术方法,比如构造函数在某一个类中,当这个类被实例化的时候就会自动调用,而析构函数是在这个类的对象被销毁的时候自动调用,默认情况下是在程序执行结束时自动调用. 如果我 ...
- 【VirtualBox】端口转发,ssh
端口转发 VirualBox的设置 - 网络 - 端口转发 里面有主机IP.主机端口.子系统IP.子系统端口 设置后的含义是:当外部访问主机IP:主机端口后,将会把访问映射到虚拟机的子系统IP和子系统 ...
- 解决 jersey javax.ws.rs.core.UriBuilder.fromUri(UriBuilder.java:119)
检查是否Jar冲突 保留一个jersey-server-*.jar
- jQuery过滤选择器
//基本过滤器$('li:first').css('background','#ccc');//第一个元素$('li:last').css('background','red');//最后一个元素$( ...
- 自定义viewgroup实现ArcMenu
最终效果如下 实现思路 通过效果图,会有几个问题: a.动画效果如何实现 可以看出动画是从顶点外外发射的,可能有人说,那还不简单,默认元素都在定点位置,然后TraslateAnimation就好了:这 ...