Android Volley 是Google开发的一个网络lib,可以让你更加简单并且快速的访问网络数据。Volley库的网络请求都是异步的,你不必担心异步处理问题。

Volley的优点:

  1. 请求队列和请求优先级
  2. 请求Cache和内存管理
  3. 扩展性性强
  4. 可以取消请求

##下载和编译volley.jar

  • 需要安装git,ant,android sdk

clone代码:
git clone https://android.googlesource.com/platform/frameworks/volley

  • 编译jar:
    android update project -p . ant jar

###Maven

format: jar

<dependency>
<groupId>com.mcxiaoke.volley</groupId>
<artifactId>library</artifactId>
<version>1.0.6</version>
</dependency>

###Gradle

format: jar

compile 'com.mcxiaoke.volley:library:1.0.6'

##Volley工作原理图

##创建Volley 单例
使用volley时,必须要创建一个请求队列RequestQueue,使用请求队列的最佳方式就是将它做成一个单例,整个app使用这么一个请求队列。

public class AppController extends Application {

public static final String TAG = AppController.class
.getSimpleName(); private RequestQueue mRequestQueue;
private ImageLoader mImageLoader; private static AppController mInstance; @Override
public void onCreate() {
super.onCreate();
mInstance = this;
} public static synchronized AppController getInstance() {
return mInstance;
} public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
} return mRequestQueue;
} public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
} public <T> void addToRequestQueue(Request<T> req, String tag) { req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
} public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
} public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}

另外,你还需要一个Cache来存放请求的图片:

public class LruBitmapCache extends LruCache<String, Bitmap> implement ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8; return cacheSize;
} public LruBitmapCache() {
this(getDefaultLruCacheSize());
} public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
} @Override
protected 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);
}
}

别忘记在AndroidManifest.xml文件中添加android.permission.INTERNET权限。

##创建Json请求
volley自带了JsonObjectRequestJsonArrayRequest分别来处理Json对象请求和Json数据请求(但是voley没有使用gson库写一个GsonRequest,发送一个request,volley直接返回一个java对象,不过我们可以自己写)。

###创建json object请求
发送一个请求只要这么简单,创建一个JsonRequest对象,写好response回调接口,并把这个请求放到请求队列中就可以了。JsonArrayRequest也类似。


String tag_json_obj = "json_obj_req";
String url = "http://api.androidhive.info/volley/person_object.json"; JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,url, null,
new Response.Listener<JSONObject>() { @Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
}
}, new Response.ErrorListener() { @Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}); AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

创建String请求

StringRequest可以用来请求任何string类型的数据:json,xml,文本等等。


String tag_string_req = "string_req"; String url = "http://api.androidhive.info/volley/string_response.html"; ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show(); StringRequest strReq = new StringRequest(Method.GET,
url, new Response.Listener<String>() { @Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
pDialog.hide(); }
}, new Response.ErrorListener() { @Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}); AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

创建POST请求

上面说的都是GET请求,下面来说一下POST请求,与GET请求不同的是,只要在创建请求的时候将请求类型改为POST请求,并且override Request的getParams方法即可。


String tag_json_obj = "json_obj_req"; String url = "http://api.androidhive.info/volley/person_object.json";
ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show(); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, null,
new Response.Listener<JSONObject>() { @Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
pDialog.hide();
}
}, new Response.ErrorListener() { @Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}) { @Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("name", "Androidhive");
params.put("email", "abc@androidhive.info");
params.put("password", "password123"); return params;
} }; AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

##添加请求头部信息


String tag_json_obj = "json_obj_req"; String url = "http://api.androidhive.info/volley/person_object.json"; ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show(); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,url, null,new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
pDialog.hide();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}) { @Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("apiKey", "xxxxxxxxxxxxxxx");
return headers;
}
}; AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

##创建Image请求
Volley库中自带了NetworkImageView类,这个ImageView可以自动使用volley下载图片

###用NetworkImageView加载图片
首先,说明一下,加载图片的原理:

NetworkImageView加载图片需要一个ImageLoader和一个图片URL,这个ImageLoader对象需要一个请求队列对象和ImageCahe对象。调用NetworkImageView的setUrl方法后,首先会判断当前ImageView的URL和新传入的URL是否一致,如果相同,就不用再发送http请求了,如果不同,那么就使用ImageLoader对象来发送http请求获取图片。

ImageLoader imageLoader = AppController.getInstance().getImageLoader();

imgNetWorkView.setImageUrl(Const.URL_IMAGE, imageLoader);

加载一个图片只要这么简单~~~

###用ImageView来加载图片
这个过程和NetworkImageView类似

ImageLoader imageLoader = AppController.getInstance().getImageLoader();

imageLoader.get(Const.URL_IMAGE, new ImageListener() {

    @Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Image Load Error: " + error.getMessage());
} @Override
public void onResponse(ImageContainer response, boolean arg1) {
if (response.getBitmap() != null) { imageView.setImageBitmap(response.getBitmap());
}
}
});

可以再简单一点:

// Loading image with placeholder and error image
imageLoader.get(Const.URL_IMAGE, ImageLoader.getImageListener(imageView, R.drawable.ico_loading, R.drawable.ico_error))

ImageLoader.getImageListener方法中已经写了一个默认的ImageListener

##Volley Cachevolley中自带了强大的cache机制来管理请求cache,这会减少网络请求次数和用户等待时间。

###从请求Cache中加载请求

Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(url);
if(entry != null){
try {
String data = new String(entry.data, "UTF-8"); } catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}else{ }

###使请求缓存失效失效并不意味这删除,Volley还会继续使用缓存的对象直到从服务器上获取到了新的数据,新的数据会覆盖旧的数据。

AppController.getInstance().getRequestQueue().getCache().invalidate(url, true);

###关闭Cache
如果你想将某一个请求的Cache功能关闭,直接调用Request的setShouldCache()方法就可以:


StringRequest stringReq = new StringRequest(....); stringReq.setShouldCache(false);

###将某一URL的Cache删除
调用Cacheremove方法可以删除这个URL的cache:

AppController.getInstance().getRequestQueue().getCache().remove(url);

###删除所有的Cache

AppController.getInstance().getRequestQueue().getCache().clear();

##取消请求
在你添加一个请求到请求队列中的时候,你可以发现,addToRequestQueue(request, tag)方法还接受一个tag参数,这个tag就是用来标记某一类请求的,这样就可以取消这个tag的所有请求了:

String tag_json_arry = "json_req";
ApplicationController.getInstance().getRequestQueue().cancelAll("feed_request");

##请求优先级
在创建一个request的时候可以Override Request方法的getPriority方法返回一个优先级,优先级分为:Normal, Low, Immediate, High

private Priority priority = Priority.HIGH;

StringRequest strReq = new StringRequest(Method.GET,
Const.URL_STRING_REQ, new Response.Listener<String>() { @Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog(); }
}, new Response.ErrorListener() { @Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
@Override
public Priority getPriority() {
return priority;
} };

##Missing! 创建xml请求
就像创建Gson请求一样,你可以自定义一个XMLRequest类来请求xml数据

Android库Volley的使用介绍的更多相关文章

  1. GitHub 上排名前 100 的 Android 开源库进行简单的介绍

    若有任何疑问可通过邮件或微博联系我 项目名称 项目简介 1. react-native 这个是 Facebook 在 React.js Conf 2015 大会上推出的基于 JavaScript 的开 ...

  2. 我的Android进阶之旅】GitHub 上排名前 100 的 Android 开源库进行简单的介绍

    GitHub Android Libraries Top 100 简介 本文转载于:https://github.com/Freelander/Android_Data/blob/master/And ...

  3. Android网络通信库Volley简介

    1. 什么是Volley 在这之前,我们在程序中需要和网络通信的时候,大体使用的东西莫过于AsyncTaskLoader,HttpURLConnection,AsyncTask,HTTPClient( ...

  4. NDK中android.mk文件的简单介绍和第三方库的调用

    先贴一个样例,然后解释一下: LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := mydjvuapi SRC_FILE_ ...

  5. Android网络通信库Volley简介(转)

    以前反编译过android market,发现里面有用到volley,起这么个名字不知道啥用的,现在才知道主讲者Ficus Kirkpatrick 就是负责开发Google play 的. 看完视频, ...

  6. android网络请求库volley方法详解

    使用volley进行网络请求:需先将volley包导入androidstudio中 File下的Project Structrue,点加号导包 volley网络请求步骤: 1. 创建请求队列     ...

  7. Android系统性能调优工具介绍

    http://blog.csdn.net/innost/article/details/9008691 经作者授权,发表Tieto某青年牛的一篇<程序员>大作. Android系统性能调优 ...

  8. 今年新鲜出炉的30个流行Android库,你一定需要

    作者|Michal Bialas 2017年快过去了,你年初的定的目标都快完成了吗?总结过去三个月内发布的 最新的30 个 Android 库和项目.你一定需要,建议收藏!让你事半功倍 1.Mater ...

  9. 怎么通过activity里面的一个按钮跳转到另一个fragment(android FragmentTransaction.replace的用法介绍)

    即:android FragmentTransaction.replace的用法介绍 Fragment的生命周期和它的宿主Activity密切相关,几乎和宿主Activity的生命周期一致,他们之间最 ...

随机推荐

  1. zoj 1204 Additive equations

    ACCEPT acm作业 http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=204 因为老师是在集合那里要我们做这道题.所以我很是天 ...

  2. Mybatis 学习-2

    创建基于session的util类,在线程中共享SqlSession package cn.smartapp.blogs.pojo; import java.io.Serializable; impo ...

  3. 解决qt5在ubuntu下无法调用fcitx输入中文的问题

    如题,在以前安装qt5.2.1的时候就遇到了这个问题.当时上网搜了很多资料,结果都解决不了,发现都是复制来复制去. 这次因为要用qt5.3.0在ubuntu下写个程序,所以不解决这个问题不行了.就继续 ...

  4. JAVA-数据库连接【转】

    SqlServer.Oracle.MySQL的连接,除了地址和驱动包不同,其他都一样的. 1 public String urlString="jdbc:sqlserver://localh ...

  5. mac 找文件

    如何找到 etc 方法1: ! D# D! s2 F" f 七度苹果电脑软件1.打开Finder,按快键盘 Command + Shift + G,即可调出 前往文件夹 ,也可以左上角 找到 ...

  6. Oracle select case when

    Case具有两种格式.简单Case函数和Case搜索函数. --简单Case函数 CASE sex WHEN '1' THEN '男' WHEN '2' THEN '女' ELSE '其他' END ...

  7. JMETER JDBC操作

    本文目标 1.添加测试计划 2.配置JDBC连接 3.插入数据 4.使用控制器 5.查看插入结果   1.添加测试计划 添加mysql驱动   2.添加测试计划 3.添加JDBC连接   在这里JDB ...

  8. eclipse debug时老提示edit source lookup path解决方案

    用myeclipse debug web应用的时候,总提示edit source lookup path,每次都得手动选择项目,费时费力.在网上终于找到了方法. 搬运:http://www.educi ...

  9. bzoj 1818: [Cqoi2010]内部白点

    #include<cstdio> #include<iostream> #include<algorithm> using namespace std; struc ...

  10. comboBox绑定数据库、模糊查询

    实现: 一.绑定数据库 点击查询按钮,comboBox显示从数据库查到的某字段的一列数据 方法:在按钮的点击事件绑定数据库 private void button1_Click(object send ...