列表异步线程加载图片

手机客户端以列表形式展示数据是非常常见的一种方式。然而列表中要显示图片(比如:头像)就要采用异步线程加载的方式,这样做是为了防止加载图片数据的时候,花费时间过长,阻塞UI线程,从而达到保持App的流畅性的目的。 

下面我将分享 OSChina.NET Android版客户端的列表异步线程加载图片的方法: 

 

图片缓存

private static HashMap<String, SoftReference<Bitmap>> cache;  

图片缓存是当有加载过相同的图片的时候,可以快速重复使用,比如同一个人的头像。

图片控件集合

private static Map<ImageView, String> imageViews;  

图片控件集合是一个Map,记录当前ImageView控件对应的图片地址,用来防止异步线程加载图片时候ImageView控件显示的图片与实际图片地址对应的图片不符,出现错乱。

线程池

private static ExecutorService pool;  

固定线程池里的并发线程数,可以防止用户在快速滑动列表的时候,不执行已经滑过去的加载线程。

具体的初始化代码:

static {  cache = new HashMap<String, SoftReference<Bitmap>>();  pool = Executors.newFixedThreadPool(5);  //固定线程池imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());}


接下来,我们来看看具体是如何加载图片的:

public void loadBitmap(String url, ImageView imageView, Bitmap defaultBmp, int width, int height) {  imageViews.put(imageView, url);  Bitmap bitmap = getBitmapFromCache(url);  if (bitmap != null) {  //显示缓存图片imageView.setImageBitmap(bitmap);  } else {  //加载SD卡中的图片缓存String filename = FileUtils.getFileName(url);String filepath = imageView.getContext().getFilesDir() + File.separator + filename;File file = new File(filepath);if(file.exists()){//显示SD卡中的图片缓存Bitmap bmp = ImageUtils.getBitmap(imageView.getContext(), filename);imageView.setImageBitmap(bmp);}else{//线程加载网络图片imageView.setImageBitmap(defaultBmp);queueJob(url, imageView, width, height);}}  }  

上面的代码中,我们根据图片的url地址,先从图片缓存里面查找是否已缓存过,如果没有,再从SD卡的图片缓存文件中查找,如果再没有,最后才是加载网络图片。这才是以最快速的方式显示图片。

下面,我将贴出完整的代码:

/*** 异步线程加载图片工具类* @author  liux*/
public class BitmapManager {  private static HashMap<String, SoftReference<Bitmap>> cache;  private static ExecutorService pool;  private static Map<ImageView, String> imageViews;  private Bitmap defaultBmp;  static {  cache = new HashMap<String, SoftReference<Bitmap>>();  pool = Executors.newFixedThreadPool(5);  //固定线程池imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());}  public BitmapManager(){}public BitmapManager(Bitmap def) {this.defaultBmp = def;}/*** 设置默认图片* @param bmp*/public void setDefaultBmp(Bitmap bmp) {  defaultBmp = bmp;  }   /*** 加载图片* @param url* @param imageView*/public void loadBitmap(String url, ImageView imageView) {  loadBitmap(url, imageView, this.defaultBmp, 0, 0);}/*** 加载图片-可设置加载失败后显示的默认图片* @param url* @param imageView* @param defaultBmp*/public void loadBitmap(String url, ImageView imageView, Bitmap defaultBmp) {  loadBitmap(url, imageView, defaultBmp, 0, 0);}/*** 加载图片-可指定显示图片的高宽* @param url* @param imageView* @param width* @param height*/public void loadBitmap(String url, ImageView imageView, Bitmap defaultBmp, int width, int height) {  imageViews.put(imageView, url);  Bitmap bitmap = getBitmapFromCache(url);  if (bitmap != null) {  //显示缓存图片imageView.setImageBitmap(bitmap);  } else {  //加载SD卡中的图片缓存String filename = FileUtils.getFileName(url);String filepath = imageView.getContext().getFilesDir() + File.separator + filename;File file = new File(filepath);if(file.exists()){//显示SD卡中的图片缓存Bitmap bmp = ImageUtils.getBitmap(imageView.getContext(), filename);imageView.setImageBitmap(bmp);}else{//线程加载网络图片imageView.setImageBitmap(defaultBmp);queueJob(url, imageView, width, height);}}  }  /*** 从缓存中获取图片* @param url*/public Bitmap getBitmapFromCache(String url) {  Bitmap bitmap = null;if (cache.containsKey(url)) {  bitmap = cache.get(url).get();  }  return bitmap;  }  /*** 从网络中加载图片* @param url* @param imageView* @param width* @param height*/public void queueJob(final String url, final ImageView imageView, final int width, final int height) {   final Handler handler = new Handler() {  public void handleMessage(Message msg) {  String tag = imageViews.get(imageView);  if (tag != null && tag.equals(url)) {  if (msg.obj != null) {  imageView.setImageBitmap((Bitmap) msg.obj);  try {//向SD卡中写入图片缓存ImageUtils.saveImage(imageView.getContext(), FileUtils.getFileName(url), (Bitmap) msg.obj);} catch (IOException e) {e.printStackTrace();}} }  }  };  pool.execute(new Runnable() {   public void run() {  Message message = Message.obtain();  message.obj = downloadBitmap(url, width, height);  handler.sendMessage(message);  }  });  } /*** 下载图片-可指定显示图片的高宽* @param url* @param width* @param height*/private Bitmap downloadBitmap(String url, int width, int height) {   Bitmap bitmap = null;try {//http加载图片bitmap = ApiClient.getNetBitmap(url);if(width > 0 && height > 0) {//指定显示图片的高宽bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);} //放入缓存cache.put(url, new SoftReference<Bitmap>(bitmap));} catch (Exception e) {e.printStackTrace();}return bitmap;  }  
}


工具类使用 
实例化时,可以设置默认的显示图片: 

BitmapManager bmpManager = new BitmapManager(BitmapFactory.decodeResource(context.getResources(), R.drawable.loading));

调用加载图片的方法:

bmpManager.loadBitmap(imageURL, imageView);

转载于:https://www.cnblogs.com/daocaowu/p/3172739.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/261450.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

matlab连续卷积动画实现(gui编程)

一.代码运行结果 二.代码 function varargout tianqi(varargin) % TIANQI MATLAB code for tianqi.fig % TIANQI, by itself, creates a new TIANQI or raises the existing % singleton*. % % H TIANQI returns the handle to a new TIANQI or the handle t…

sql2005备份还原详解

1、备份 点击要备份的数据库右键-任务-备份 备份类型&#xff1a;完整 2、还原 点击数据库右键-还原数据库 目标数据库&#xff1a;&#xff08;数据库名&#xff09; 选择 原设备&#xff1a;&#xff08;你备份的xxx.bak文件&#xff09; 在选…

python爬虫框架怎么安装_celery如何在python爬虫中安装?

在我们学习了不少关于celery框架的知识后&#xff0c;很多小伙伴已经想要正式使用celery了。这里小编也不知道大家安装好了celery没有~为了照顾一下动手能力不太强的python小白&#xff0c;小编把celery框架安装的方法整理了出来&#xff0c;没有安装成功的小伙伴也可以参考一下…

codeforces C. Diverse Permutation(构造)

题意&#xff1a;1...n 的全排列中 p1, p2, p3....pn中&#xff0c;找到至少有k个|p1-p2| , |p2-p3|, ...|pn-1 - pn| 互不相同的元素&#xff01; 思路&#xff1a; 保证相邻的两个数的差值的绝对值为单调递减序列..... 如果够k个了&#xff0c;最后将没有访问到的元素直接添加…

(转)父子节点遍历

原创作品&#xff0c;允许转载&#xff0c;转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://qianzhang.blog.51cto.com/317608/1205679 对于树/图的遍历&#xff0c;通常有2种算法来实现&#xff1a;迭代(Iteration)和递归(Recursi…

SharePoint 2007 做Migration后用户处理

新公司的一部分任务是做Migration&#xff0c;从用户角度来说分为两种情况&#xff0c;第一种是在同一个Domain下作网站的Migration&#xff0c;另外一种就是在不同Domain下做Migration。在同一Domain下做Migration&#xff0c;User不会出现问题&#xff0c;因为在Import后&…

Ubuntu GNOME 15.10升级16.4LTS

为什么80%的码农都做不了架构师&#xff1f;>>> 当Ubuntu GNOME官方已经发送16.4后&#xff0c;执行以下命令 sudo do-release-upgrade 显示没有新系统更新 在网上找到另一种方法是执行以下命令&#xff1a; sudo ppa-purge ppa:gnome3-team/gnome3-staging sudo p…

matplotlib plot 分组_小白学 Python 数据分析(16):Matplotlib(一)坐标系

人生苦短&#xff0c;我用 Python前文传送门&#xff1a;小白学 Python 数据分析(1)&#xff1a;数据分析基础小白学 Python 数据分析(2)&#xff1a;Pandas (一)概述小白学 Python 数据分析(3)&#xff1a;Pandas (二)数据结构 Series小白学 Python 数据分析(4)&#xff1a;Pa…

hdu 1423 最长公共递增子序列

这题一开始把我给坑了&#xff0c;我还没知道LCIS的算法&#xff0c;然后就慢慢搞吧&#xff0c;幸运的是还真写出来了&#xff0c;只不过麻烦了一点。 我是将该题转换为多条线段相交&#xff0c;然后找出最多多少条不相交&#xff0c;并且其数值死递增的。 代码如下&#xff1…

安卓从业者应该关注:Android 6.0的运行时权限

Android 6.0&#xff0c;代号棉花糖&#xff0c;自发布伊始&#xff0c;其主要的特征运行时权限就很受关注。因为这一特征不仅改善了用户对于应用的使用体验&#xff0c;还使得应用开发者在实践开发中需要做出改变。 没有深入了解运行时权限的开发者通常会有很多疑问&#xff0…

git把另一个盘的代码上传_如何使用Git上传代码到GitHub

初始化Git1. 安装Git客户端一路下一步下一步既可2. 配置Git1. 在电脑硬盘里找一块地方存放本地仓库,右键Git Bash进入git命令行执行如下代码 生成.git文件夹,表示本地git创建成功git config --global user.name "littonishir"git config --global user.email "l…

sh脚本学习之: sh脚本 、sed、awk

sh脚本 sh命令的批处理文件&#xff0c;支持更复杂的逻辑。  Shell中的变量 参数   $0  当前脚本路径 $1....$n  脚本执行对应的第n个参数 条件判断   文件判断 test [op] path e存在  f是文件  d是目录  r可读  w可写  x可执行   if判断/case if[条件判…

Silverlight OOB Setup

Sl的安装大家都知道&#xff1a;在程序点右键&#xff0c;选择安装。有没有另外一种方法&#xff0c;类似普通软件那样&#xff0c;通过安装包安装&#xff1f;答案当然是 有参考&#xff1a;http://www.code Technorati 标签: project.com/KB/install/slsetup.aspx思路很简单&…

2016-04-29 二分查找的面试题

为什么80%的码农都做不了架构师&#xff1f;>>> 1.面试题 例如&#xff1a; ip计算后的值&#xff1d;53文本内容&#xff1a;1,100,北京 101,1000,上海 1001,3001,广州 ...求ip53对应的省份2.代码如下&#xff1a; #!/usr/bin/python # coding: utf8def ip_find(i…

gettype拿不到值_王者荣耀:被低估的强势打野,就是这位拿大锤子的阿姨!

王者峡谷的小伙伴你们好&#xff0c;今天就为你们推荐一下这位野区女霸主钟无艳&#xff0c;不仅高伤害而且操作简单&#xff01;版本更新在5月14日版本更新中&#xff0c;钟无艳的三个技能都被加强了&#xff0c;所有的蓝耗都被固定&#xff0c;不再随技能等级的成长值&#x…

如何培训

Ground roles 1>No phone,no computer.2>没有私下讨论 3>parkng Lot 1. 演讲技巧 2. 隐喻 说服别人时&#xff0c;讲故事&#xff0c;举例子 3. 问题回答 4. 会场设置 转载于:https://www.cnblogs.com/myfav/p/3176621.html

【笔记】MATLAB中的图形(2)

三维作图 1、mesh(z)语句 mesh(z)语句可以给出矩阵z元素的三维消隐图&#xff0c;网络表面由z坐标点定义&#xff0c;与前面叙述的x-y平面的线格相同&#xff0c;图形由临近的点连接而成。它可用来显示用其他方式难以输出的包含大量数据的大型矩阵&#xff0c;也可以用来绘制z变…

Kindeditor放置两个调用readonly错误

开始 需要调用Kindeditor中的readonly的方法&#xff0c;但是一直提示edit is undefined 而editor.readonly(true)又只对第一个对象有效 所以只能换换形式&#xff0c;干脆将下面的kindeditor拿上来 虽然是满足自己这个需求&#xff0c;但是真正的原因解决办法&#xff0c;还是…

acl在内核里的位置_Linux 进程在内核眼中是什么样子的?

本篇算是进程管理的的揭幕篇&#xff0c;简单介绍一个进程在内核眼里的来龙去脉&#xff0c;为接下来的进程创建&#xff0c;进程调度&#xff0c;进程管理等篇章做好学习准备。从程序到进程再到内核啥是程序&#xff0c;啥是进程&#xff0c;一张图可以给我们解释&#xff1a;…

majikan

转载于:https://www.cnblogs.com/YOUEN/p/3179091.html