您的位置:首页 > 理论基础 > 计算机网络

Android-网络框架03Volley

2017-02-17 14:29 337 查看
Volley官网:https://android.googlesource.com/platform/frameworks/volley

本文的意义

Google I/O 2013 推荐使用volley, 简单记录下使用方式。

Volley设计目标就是非常适合去进行数据量不大,但通信频繁的网络操作,而对于大数据量的网络操作,比如说下载文件等,Volley的表现就会非常糟糕。

转载请注明出处 ethan_xue博客

具体步骤

1.得到volley.jar

clone代码:

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

将代码编译成jar包:

android update project -p . ant jar 获得volley.jar包。

添加volley.jar到你的项目, 假若不能得到volley.jar也可以直接使用其代码

2.使用Volley框架实现网络数据请求主要有以下三个步骤:

创建RequestQueue对象,定义网络请求队列;

创建XXXRequest对象(XXX代表String,JSON,Image等等),定义网络数据请求的详细过程;

把XXXRequest对象添加到RequestQueue中,开始执行网络请求。

3.具体代码

3.1 创建RequestQueue对象,定义网络请求队列;

RequestQueue mQueue = Volley.newRequestQueue(context);


也可以放到application里

public class MyApplication extends Application{
// 建立请求队列
public static RequestQueue queue;

@Override
public void onCreate() {
super.onCreate();
queue = Volley.newRequestQueue(getApplicationContext());
}

public static RequestQueue getHttpQueue() {
return queue;
}
}


3.2 创建XXXRequest对象并添加到请求队列中

Volley提供了JsonObjectRequest、JsonArrayRequest、StringRequest等Request形式,也可以继承Request自定义。

以JsonObjectRequest为例

private final String url="http:/xxxxx";
JsonObjectRequest req=new JsonObjectRequest(url,null,new Response.Listener<JsonObject>(){
@Override
public void onResponse(JsonObject response){
//添加自己的响应逻辑,
Log.e("TAG", response.toString());
}
},
new ResponseError.Listener(){
@Override
public void onResponseError(VollerError error){
//错误处理
Log.e("Error Message:","Error is"+error);
}
});
// 设置该请求的标签, 可设置也可不设置,设置后可根据tag调用取消请求
request.setTag("urltag");
// 将请求添加到队列中, mQueue是在application初始化的话,应该调MyApplication.getHttpQueue().add(request);
mQueue.add(req);


3.3 取消请求

- 取消单个请求

// 网络请求标签为"utltag"
public void onStop() {
super.onStop();
MyApplication.getHttpQueues.cancelAll("utltag");
}


取消队列里全部请求

@Override
protected void onStop() {
super.onStop();
mRequestQueue.cancelAll(this);
}


Q&A

Volley能否加载图片

Volley除了网络请求外,还可以加载图片,不过不建议使用,没有专业的图片加载库强大,尤其是在listview,recyclerview使用的时候。

参考

http://www.open-open.com/lib/view/open1451223702339.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  网络 框架 Android