博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android Volley框架的使用(三)
阅读量:4329 次
发布时间:2019-06-06

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

  此博文源码下载地址  

Image Request

为了更方便的使用Volley中的图片请求,我们同样先在VolleyController类中封装一个ImageLoader

public class LruBitmapCache extends LruCache
implements ImageCache{ public static int getDefaultLruCacheSize(){ final int maxMemory=(int)(Runtime.getRuntime().maxMemory/1024); final int cacheSize=maxMemory/8; return cacheSize; } public LruBitmapCache(){ this(getDefaultLruBitmapCacheSize); } public LruBitmapCache(int sizeInKiloBytes){ super(sizeInkiloBytes); } @Override public int sizeOf(String key,Bitmap Value){ return value.getRowBytes()*value.getHeight()/1024; } @Override public Bitmap getBitmap(String url){ return get(url); } @Override public void putBitmap(String url,Bitmap bitmap){ put(url,bitmap); } }

 

package com.javen.volley;import android.content.Context;import android.text.TextUtils;import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.toolbox.ImageLoader;import com.android.volley.toolbox.Volley;public class VolleyController {    // 创建一个TAG,方便调试或Log    private static final String TAG = "VolleyController";    // 创建一个全局的请求队列    private RequestQueue reqQueue;    private ImageLoader imageLoader;    // 创建一个static ApplicationController对象,便于全局访问    private static VolleyController mInstance;        private Context mContext;    private VolleyController(Context context) {        mContext=context;    }    /**     * 以下为需要我们自己封装的添加请求取消请求等方法     */    // 用于返回一个VolleyController单例    public static VolleyController getInstance(Context context) {        if (mInstance == null) {            synchronized(VolleyController.class)            {                if (mInstance == null) {                    mInstance = new VolleyController(context);                }            }        }        return mInstance;    }    // 用于返回全局RequestQueue对象,如果为空则创建它    public RequestQueue getRequestQueue() {        if (reqQueue == null){            synchronized(VolleyController.class)            {                if (reqQueue == null){                    reqQueue = Volley.newRequestQueue(mContext);                }            }        }        return reqQueue;    }            public ImageLoader getImageLoader(){        getRequestQueue();        //如果imageLoader为空则创建它,第二个参数代表处理图像缓存的类        if(imageLoader==null){            imageLoader=new ImageLoader(reqQueue, new LruBitmapCache());        }        return imageLoader;    }    /**     * 将Request对象添加进RequestQueue,由于Request有*StringRequest,JsonObjectResquest...     * 等多种类型,所以需要用到*泛型。同时可将*tag作为可选参数以便标示出每一个不同请求     */    public 
void addToRequestQueue(Request
req, String tag) { // 如果tag为空的话,就是用默认TAG req.setTag(TextUtils.isEmpty(tag) ? TAG : tag); getRequestQueue().add(req); } public
void addToRequestQueue(Request
req) { req.setTag(TAG); getRequestQueue().add(req); } // 通过各Request对象的Tag属性取消请求 public void cancelPendingRequests(Object tag) { if (reqQueue != null) { reqQueue.cancelAll(tag); } }}
  1. 完成上述步骤后,在使用的时候我们首先需要获取ImageLoader对象
    ImageLoader imageLoader=VolleyController.getInstance(context).getImageLoader();
  2. 将图片载入ImageView  可以使用Volley自己提供的一个Image视图,NetworkImageView,几行代码就可以搞定
    //将NetworkImageView布局在布局文件中NetworkImageView imageView=(NetworkImageView)findViewById(R.id.networkimageview); //需要用到imageLoader imageView.setImageUrl(url,imageLoader);

    如果要将图片直接载入ImageView,可以通过以下方法:

    ImageLoader imageLoader=VolleyController.getInstance(context).getImageLoader();        imageLoader.get(url,new ImageListener(){           @Override           public void onResponse(ImageContainer response,boolean arg)  {                if(response.getBitmap()!=null){                //设置imageView                //    imageView.setImageBitmap(response.getBitmap());                                    }            }            @Override            public void onErrorResponse(VolleyError error){                L.e("Image Error"+error.getMessage());                }            });

 

Volley Cache

     Volley有着强大的缓存机制用来维护请求到的缓存,这节省了不必要的网络消耗和等待时间,下面是一些关于缓存的常用方法

  1. 从缓存中读取请求:即先从缓存读取看是否有缓存数据,如果没有则请求网络数据
    Cache cache=VolleyController.getInstance(context).getRequestQueue().getCache();        Entry entry=cache.get(url);        if(entry!=null){            try{                String data=new String(entry.data,"Utf-8");                //处理data,将其转化为JSON,XML,Bitmap等等                }catch(Exception e){                    e.printStackTrace();                }        }else{            //缓存中不存在,做网络请求        }
  2. 缓存失效:缓存失效并不意味这删除缓存,volley仍将使用缓存对象,直到服务器返回新数据,一旦接收到新数据,将覆盖原来的缓存
    VolleyController.getInstance(context).getRequestQueue().getCache().invalidate(url,true);

     

  3. 关闭缓存:如果你想禁用特定Url的缓存可以使用以下方法
    VolleyController.getInstance(context).getRequestQueue().getCache().remove(url);
  4. 删除来自特定url的缓存
    VolleyController.getInstance(context).getRequestQueue().getCache().remove(url);

     

  5. 删除所有缓存
    VolleyController.getInstance(context).getRequestQueue().getCache()clear(url);

    总结:

    综上,已经学完了Volley框架的使用,在实际应用中遇到具体的问题需要具体考虑,必要时要学会查阅资料,除了以上几篇提到的参考资料,最好能FQ去看看google官方关于Volley的文档。

    参考资料: 

转载于:https://www.cnblogs.com/zyw-205520/p/4950535.html

你可能感兴趣的文章
HTTP:每个Web开发人员必须知道的协议 - 第2部分
查看>>
nginx作防盗链设置
查看>>
Tkinter控件(python GUI)
查看>>
【git】切换分支获取代码
查看>>
JavaScript改动CSS伪元素:after和:before的样式
查看>>
Windows App开发之开发准备
查看>>
css3的选择器
查看>>
Broadcast Receiver注意事项
查看>>
ActionBar点击弹出下拉框操作
查看>>
swift新手入门视频教程-08-枚举
查看>>
HDU 1164 Eddy's research I【素数筛选法】
查看>>
ORACLE单字符函数的函数
查看>>
人活系列Streetlights (秩)
查看>>
php:兄弟连之面向对象版图形计算器1
查看>>
更换网页背景(写入cookie)
查看>>
IOS基础之UILineBreakModeWordWrap
查看>>
Objective-C中常用的结构体NSRange,NSPoint,NSSize(CGSize),NSRect
查看>>
二叉堆实现优先队列
查看>>
HDU 1251 统计难题(字典树,map)
查看>>
Mybatis sql映射文件浅析 Mybatis简介(三) 简介
查看>>