博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android批量图片加载经典系列——使用二级缓存、异步网络负载形象
阅读量:4313 次
发布时间:2019-06-06

本文共 9563 字,大约阅读时间需要 31 分钟。

一、问题描写叙述

  Android应用中常常涉及从网络中载入大量图片,为提升载入速度和效率,降低网络流量都会採用二级缓存和异步载入机制。所谓二级缓存就是通过先从内存中获取、再从文件里获取,最后才会訪问网络。内存缓存(一级)本质上是Map集合以key-value对的方式存储图片的url和Bitmap信息。因为内存缓存会造成堆内存泄露, 管理相对复杂一些。可採用第三方组件,对于有经验的可自己编写组件,而文件缓存比較简单通常自己封装一下就可以。

以下就通过案例看怎样实现网络图片载入的优化。

二、案例介绍

  案例新闻的列表图片

 

三、主要核心组件

  以下先看看实现一级缓存(内存)、二级缓存(磁盘文件)所编写的组件

1、MemoryCache

  在内存中存储图片(一级缓存), 採用了1个map来缓存图片代码例如以下:

 
public class MemoryCache {    // 最大的缓存数     private static final int MAX_CACHE_CAPACITY = 30;    //用Map软引用的Bitmap对象, 保证内存空间足够情况下不会被垃圾回收        private HashMap
> mCacheMap = new LinkedHashMap
>() { private static final long serialVersionUID = 1L;//当缓存数量超过规定大小(返回true)会清除最早放入缓存的 protected boolean removeEldestEntry(Map.Entry
> eldest){ return size() > MAX_CACHE_CAPACITY;}; }; /** * 从缓存里取出图片 * @param id * @return 假设缓存有,而且该图片没被释放,则返回该图片,否则返回null */ public Bitmap get(String id){ if(!mCacheMap.containsKey(id)) return null; SoftReference
ref = mCacheMap.get(id); return ref.get(); } /** * 将图片增加缓存 * @param id * @param bitmap */ public void put(String id, Bitmap bitmap){ mCacheMap.put(id, new SoftReference
(bitmap)); } /** * 清除全部缓存 */ public void clear() { try { for(Map.Entry
>entry :mCacheMap.entrySet()) { SoftReference
sr = entry.getValue(); if(null != sr) { Bitmap bmp = sr.get(); if(null != bmp) bmp.recycle(); } } mCacheMap.clear(); } catch (Exception e) { e.printStackTrace();} }}

2、FileCache

  在磁盘中缓存图片(二级缓存),代码例如以下

 
public class FileCache {     //缓存文件文件夹     private File mCacheDir;    /**     * 创建缓存文件文件夹,假设有SD卡。则使用SD,假设没有则使用系统自带缓存文件夹     * @param context     * @param cacheDir 图片缓存的一级文件夹     */public FileCache(Context context, File cacheDir, String dir){if(android.os.Environment.getExternalStorageState().equals、(android.os.Environment.MEDIA_MOUNTED))            mCacheDir = new File(cacheDir, dir);      else        mCacheDir = context.getCacheDir();// 怎样获取系统内置的缓存存储路径      if(!mCacheDir.exists())  mCacheDir.mkdirs();    }    public File getFile(String url){        File f=null;        try {//对url进行编辑,解决中文路径问题            String filename = URLEncoder.encode(url,"utf-8");            f = new File(mCacheDir, filename);        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        return f;    }    public void clear(){//清除缓存文件        File[] files = mCacheDir.listFiles();        for(File f:files)f.delete();}}

3、编写异步载入组件AsyncImageLoader

  android中採用单线程模型即应用执行在UI主线程中。且Android又是实时操作系统要求及时响应否则出现ANR错误。因此对于耗时操作要求不能堵塞UI主线程,须要开启一个线程处理(如本应用中的图片载入)并将线程放入队列中,当执行完毕后再通知UI主线程进行更改,同一时候移除任务——这就是异步任务,在android中实现异步可通过本系列一中所用到的AsyncTask或者使用thread+handler机制,在这里是全然是通过代码编写实现的,这样我们能够更清晰的看到异步通信的实现的本质,代码例如以下

 
public class AsyncImageLoader{    private MemoryCache mMemoryCache;//内存缓存    private FileCache mFileCache;//文件缓存    private ExecutorService mExecutorService;//线程池//记录已经载入图片的ImageView    private Map
mImageViews = Collections .synchronizedMap(new WeakHashMap
());//保存正在载入图片的url private List
mTaskQueue = new ArrayList
(); /** * 默认採用一个大小为5的线程池 * @param context * @param memoryCache 所採用的快速缓存 * @param fileCache 所採用的文件缓存 */ public AsyncImageLoader(Context context, MemoryCache memoryCache, FileCache fileCache) { mMemoryCache = memoryCache; mFileCache = fileCache; mExecutorService = Executors.newFixedThreadPool(5);//建立一个容量为5的固定尺寸的线程池(最大正在执行的线程数量) } /** * 依据url载入对应的图片 * @param url * @return 先从一级缓存中取图片有则直接返回,假设没有则异步从文件(二级缓存)中取,假设没有再从网络端获取 */ public Bitmap loadBitmap(ImageView imageView, String url) { //先将ImageView记录到Map中,表示该ui已经执行过图片载入了 mImageViews.put(imageView, url); Bitmap bitmap = mMemoryCache.get(url);//先从一级缓存中获取图片 if(bitmap == null) { enquequeLoadPhoto(url, imageView);//再从二级缓存和网络中获取 } return bitmap; } /** * 加入图片下载队列 * @param url */ private void enquequeLoadPhoto(String url, ImageView imageView) { //假设任务已经存在,则不又一次加入 if(isTaskExisted(url)) return; LoadPhotoTask task = new LoadPhotoTask(url, imageView); synchronized (mTaskQueue) { mTaskQueue.add(task);//将任务加入到队列中 } mExecutorService.execute(task);//向线程池中提交任务,假设没有达到上限(5),则执行否则被堵塞 } /** * 推断下载队列中是否已经存在该任务 * @param url * @return */ private boolean isTaskExisted(String url) { if(url == null) return false; synchronized (mTaskQueue) { int size = mTaskQueue.size(); for(int i=0; i

  编写完毕之后。对于异步任务的运行仅仅需调用AsyncImageLoader中的loadBitmap()方法就可以很方便,对于AsyncImageLoader组件的代码最好结合凝视好好理解一下。这样对于Android中线程之间的异步通信就会有深刻的认识。

4、工具类ImageUtil

 
public class ImageUtil {    /**     * 从网络获取图片,并缓存在指定的文件里     * @param url 图片url     * @param file 缓存文件     * @return     */    public static Bitmap loadBitmapFromWeb(String url, File file) {        HttpURLConnection conn = null;        InputStream is = null;        OutputStream os = null;        try {            Bitmap bitmap = null;            URL imageUrl = new URL(url);            conn = (HttpURLConnection) imageUrl.openConnection();            conn.setConnectTimeout(30000);            conn.setReadTimeout(30000);            conn.setInstanceFollowRedirects(true);            is = conn.getInputStream();            os = new FileOutputStream(file);            copyStream(is, os);//将图片缓存到磁盘中            bitmap = decodeFile(file);            return bitmap;        } catch (Exception ex) {            ex.printStackTrace();            return null;        } finally {            try {                if(os != null) os.close();                if(is != null) is.close();                if(conn != null) conn.disconnect();            } catch (IOException e) {    }        }    }        public static Bitmap decodeFile(File f) {        try {            return BitmapFactory.decodeStream(new FileInputStream(f), null, null);        } catch (Exception e) { }         return null;    }    private  static void copyStream(InputStream is, OutputStream os) {        final int buffer_size = 1024;        try {            byte[] bytes = new byte[buffer_size];            for (;;) {                int count = is.read(bytes, 0, buffer_size);                if (count == -1)                    break;                os.write(bytes, 0, count);            }        } catch (Exception ex) {            ex.printStackTrace();        }    }}
四、測试应用

 组件之间的时序图:

 

1、编写MainActivity

 
public class MainActivity extends Activity {     ListView list;    ListViewAdapter adapter;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        list=(ListView)findViewById(R.id.list);        adapter=new ListViewAdapter(this, mStrings);        list.setAdapter(adapter);    }    public void onDestroy(){        list.setAdapter(null);        super.onDestroy();        adapter.destroy();    }  private String[] mStrings={ "http://news.21-sun.com/UserFiles/x_Image/x_20150606083511_0.jpg","http://news.21-sun.com/UserFiles/x_Image/x_20150606082847_0.jpg",…..};}

2、编写适配器

 
public class ListViewAdapter extends BaseAdapter {    private Activity mActivity;    private String[] data;    private static LayoutInflater inflater=null;    private AsyncImageLoader imageLoader;//异步组件    public ListViewAdapter(Activity mActivity, String[] d) {        this.mActivity=mActivity;        data=d;        inflater = (LayoutInflater)mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);        MemoryCache mcache=new MemoryCache();//内存缓存 File sdCard = android.os.Environment.getExternalStorageDirectory();//获得SD卡        File cacheDir = new File(sdCard, "jereh_cache" );//缓存根文件夹    FileCache fcache=new FileCache(mActivity, cacheDir, "news_img");//文件缓存       imageLoader = new AsyncImageLoader(mActivity, mcache,fcache);    }    public int getCount() {        return data.length;    }    public Object getItem(int position) {        return position;    }    public long getItemId(int position) {        return position;    }      public View getView(int position, View convertView, ViewGroup parent) {        ViewHolder vh=null;        if(convertView==null){            convertView = inflater.inflate(R.layout.item, null);            vh=new ViewHolder();            vh.tvTitle=(TextView)convertView.findViewById(R.id.text);            vh.ivImg=(ImageView)convertView.findViewById(R.id.image);            convertView.setTag(vh);                }else{            vh=(ViewHolder)convertView.getTag();        }        vh.tvTitle.setText("标题信息測试———— "+position);        vh.ivImg.setTag(data[position]);        //异步载入图片。先从一级缓存、再二级缓存、最后网络获取图片        Bitmap bmp = imageLoader.loadBitmap(vh.ivImg, data[position]);        if(bmp == null) {            vh.ivImg.setImageResource(R.drawable.default_big);        } else {            vh.ivImg.setImageBitmap(bmp);        }        return convertView;    }    private class ViewHolder{        TextView tvTitle;        ImageView ivImg;    }    public void destroy() {        imageLoader.destroy();    }}

 

  想要了解很多其它内容的小伙伴。能够点击,亲自执行測试。

  疑问咨询或技术交流,请增加官方QQ群: (452379712)

 

作者:
出处:
 
本文版权归和CSDN共同拥有,欢迎转载。但未经作者允许必须保留此段声明。且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
 

版权声明:本文博主原创文章,博客,未经同意不得转载。

转载于:https://www.cnblogs.com/mengfanrong/p/4909320.html

你可能感兴趣的文章
LeetCode-Bitwise AND of Numbers Range
查看>>
Windows Server 2012和2008中使用计划任务定时执行BAT批处理文件 定时备份mysql数据...
查看>>
费马小定理与GCD&LCM
查看>>
P1077 摆花
查看>>
zynq修改ramdisk文件系统
查看>>
C#测量程序运行时间及cpu使用时间
查看>>
并发编程
查看>>
我自己曾经经历的CMMI3认证通过关于软件测试的访谈【转载】
查看>>
C# 操作Excel ——Excel获取数据、时间、图片
查看>>
【Express系列】第3篇——接入mysql
查看>>
js 高亮显示关键字
查看>>
CPU工作原理简图
查看>>
进程互斥于同步
查看>>
小米公布2017二季度手机出货量:环比增长70%
查看>>
IntelliJ Idea 集成svn 和使用[转自网络]
查看>>
VS2013 密钥 – 所有版本
查看>>
缓冲一日
查看>>
apache常用配置文件讲解
查看>>
html设置透明度
查看>>
读写锁详解
查看>>