Volley是2013年Google在I/O大会上推出了一个新的网络通信框架。
Volley可以说集成了AsyncHttpClient和Universal-Image-Loader的优点。同时在性能上也进行了大幅度的调整,非常适合进行数据量不大,但是通信频繁的网络请求。
但是对于大数据量的网络操作,比如下载文件等的,Volley就表现的比较糟糕了。
Volley特点:
- 通信更快、更简单
- Get、Post网络请求及网络图像的高效率一部处理请求
- 对网络请求进行排序
- 网络请求的缓存
- 多级别取消请求
- 和Activity生命周期的联动
为什么使用Volley?
功能上:
- 高效的Get/Post方式的数据请求交互
- 网络图片加载和缓存
其他:
- 谷歌官方推出
- 性能很稳定和强劲
Android之Volley框架的使用
1.Volley的get和post请求方式的使用
挑选合适的对象:
- StringRequest //对请求返回的结果不确定是什么类型时使用的,可以涵盖下面两个对象
- JsonObjectRequest
- JsonArrayRequest
- 同时Volley还提供了请求的回调
首先来了解StringRequest的用法:GET请求方式
首先要准备Volley.jar包,这个随便就可以在网上down下来,down下来就直接导入项目。
然后准备一个消息请求的队列,全局的:
/**
* Created by Layne_Yao on 2017-12-20 上午10:02:56.
* CSDN:http://blog.csdn.net/Jsagacity
*/
public class MyApplication extends Application {
public static RequestQueue queues;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
queues = Volley.newRequestQueue(getApplicationContext());
}
public static RequestQueue getHttpQueues(){
return queues;
}
}
然后几个在AndroidManifest.xml里面添加这一句,顺带也添加网络请求权限:
接下来就发出一个Http请求了:
/**
* StringRequest方式的Get请求
*/
public static void volleyStringRequestGet() {
String url = "http://apis.juhe.cn/mobile/get?phone=13160863974&key=335adcc4e891ba4e4be6d7534fd54c5d";
// 这是StringRequest的请求方式
StringRequest request = new StringRequest(Method.GET, url,
new Listener<String>() {
// 请求成功的回调
@Override
public void onResponse(String arg0) {
Log.e("TAG", arg0);
}
}, new Response.ErrorListener() {
// 请求失败的回调
@Override
public void onErrorResponse(VolleyError arg0) {
Log.e("TAG", arg0.toString());
}
});
// 将请求添加到请求队列中
MyApplication.getHttpQueues().add(request);
}
请求结果:
StringRequest的用法:POST请求方式
/**
* StringRequest方式的Post请求
*/
public static void volleyStringRequestPost() {
String url = "http://apis.juhe.cn/mobile/get?";
// 这是StringRequest的请求方式
StringRequest request = new StringRequest(Method.POST, url,
new Listener<String>() {
@Override
public void onResponse(String arg0) {
Log.e("TAG", arg0);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
Log.e("TAG", arg0.toString());
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> hashMap = new HashMap<String, String>();
hashMap.put("phone", "13160863974");
hashMap.put("key", "335adcc4e891ba4e4be6d7534fd54c5d");
return hashMap;
}
};
// 添加到请求队列里面
MyApplication.getHttpQueues().add(request);
}
结果和GET请求是一样的,这里就不演示了。
JsonObjectRequest的用法:GET请求方式
/**
* JsonObjectRequest方式的Get请求
*/
public static void volleyJsonObjectRequestGet() {
String url = "http://apis.juhe.cn/mobile/get?phone=13160863974&key=335adcc4e891ba4e4be6d7534fd54c5d";
// 这是JsonObjectRequest的请求方式
JsonObjectRequest request = new JsonObjectRequest(Method.GET, url,
null, new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.e("TAG", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.toString());
}
});
MyApplication.getHttpQueues().add(request);
}
运行结果是一样的:
JsonObjectRequest的用法:POST请求方式
/**
* JsonObjectRequest方式的Post请求
*/
public static void volleyJsonObjectRequestPost() {
String url = "http://apis.juhe.cn/mobile/get?";
// 这是JsonObjectRequest的请求方法
HashMap<String, String> map = new HashMap<String, String>();
map.put("phone", "13160863974");
map.put("key", "335adcc4e891ba4e4be6d7534fd54c5d");
JSONObject object = new JSONObject(map);
JsonObjectRequest objectRequest = new JsonObjectRequest(Method.POST,
url, object, new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.e("TAG", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.toString());
}
});
MyApplication.getHttpQueues().add(objectRequest);
}
这个我的KEY也没有改动过,检查了几遍都不晓得是什么问题,就没有深究。
最后就是还有一个JsonArrayRequest,这里就不演示了,用法基本相似的。
2.Volley的取消队列网络请求和Volley与Activity生命周期的联动
原理基本差不多的。这里就演示在Activity销毁的时候,同时关闭请求。请求函数的处理,其实就是打了个标签:
/**
* StringRequest方式的Get请求
*/
public static void volleyStringRequestGet() {
String url = "http://apis.juhe.cn/mobile/get?phone=13160863974&key=335adcc4e891ba4e4be6d7534fd54c5d";
// 这是StringRequest的请求方式
StringRequest request = new StringRequest(Method.GET, url,
new Listener<String>() {
// 请求成功的回调
@Override
public void onResponse(String arg0) {
Log.e("TAG", arg0);
}
}, new Response.ErrorListener() {
// 请求失败的回调
@Override
public void onErrorResponse(VolleyError arg0) {
Log.e("TAG", arg0.toString());
}
});
//给这个请求打个有意义的标签,到时可以根据这个标签找到这个请求
request.setTag("abcGET");
// 将请求添加到请求队列中
MyApplication.getHttpQueues().add(request);
}
而后在Activity的周期函数里添加这样一行代码,就可以在Activity退出时,也取消该请求,甚至关闭整个请求队列
@Override
protected void onStop() {
super.onStop();
MyApplication.getHttpQueues().cancelAll("abcGET");
}
3.Volley的简单的二次回调封装
先封装一个请求回调接口
/**
* Created by Layne_Yao on 2017-12-20 下午1:54:34.
* CSDN:http://blog.csdn.net/Jsagacity
*/
public abstract class VolleyInterface {
public Context mContext;
public static Listener<String> mListener;
public static ErrorListener mErrorListener;
public VolleyInterface(Context context, Listener<String> listener,
ErrorListener errorListener) {
this.mContext = context;
this.mListener = listener;
this.mErrorListener = errorListener;
}
public abstract void onMySuccess(String result);
public abstract void onMyError(VolleyError error);
public Listener<String> loadingListener() {
mListener = new Listener<String>() {
@Override
public void onResponse(String response) {
onMySuccess(response);
}
};
return mListener;
}
public ErrorListener errorListener() {
mErrorListener = new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onMyError(error);
}
};
return mErrorListener;
}
}
然后封装请求:
/**
* Created by Layne_Yao on 2017-12-20 下午1:46:43.
* CSDN:http://blog.csdn.net/Jsagacity
*/
public class VolleyRequest {
public static StringRequest stringRequest;
public static Context context;
public static void RequestGet(Context context, String url, String tag,
VolleyInterface volleyInterface) {
//检查还有没有同样的请求,如果有就关闭
MyApplication.getHttpQueues().cancelAll(tag);
//生成StringRequest的Get请求
stringRequest = new StringRequest(Method.GET, url,
volleyInterface.loadingListener(),
volleyInterface.errorListener());
//添加tag标签
stringRequest.setTag(tag);
//添加进请求队列中
MyApplication.getHttpQueues().add(stringRequest);
MyApplication.getHttpQueues().start();
}
public static void RequestPost(Context context, String url, String tag,
final Map<String, String> params, VolleyInterface volleyInterface) {
MyApplication.getHttpQueues().cancelAll(tag);
stringRequest = new StringRequest(url,
volleyInterface.loadingListener(),
volleyInterface.errorListener()){
@Override
protected Map<String, String> getParams()
throws AuthFailureError {
return params;
}
};
stringRequest.setTag(tag);
MyApplication.getHttpQueues().add(stringRequest);
MyApplication.getHttpQueues().start();
}
}
最后简单的请求就完成了:
/**
* 使用二次回调的Get请求方式
*/
public static void volleyCallBackGet(final Context context) {
String url = "http://apis.juhe.cn/mobile/get?phone=13160863974&key=335adcc4e891ba4e4be6d7534fd54c5d";
String tag = "abcGet";
VolleyRequest.RequestGet(context, url, tag, new VolleyInterface(
context, VolleyInterface.mListener,
VolleyInterface.mErrorListener) {
@Override
public void onMySuccess(String result) {
Log.e("TAG", result);
}
@Override
public void onMyError(VolleyError error) {
Log.e("TAG", error.toString());
}
});
}
运行结果:
4.Volley加载图片的介绍及用法
- 缓存功能简单介绍
- 加载网络图片及监听
ImageRequest的请求方式
首先来简答的使用一下ImageRequest的图片请求方式:
//ImageRequest的方式
public static void volleyImage(final ImageView imageView) {
String url = "https://www.baidu.com/img/bdlogo.png";
ImageRequest request = new ImageRequest(url, new Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
imageView.setImageBitmap(response);
}
}, 0, 0, Config.RGB_565, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
imageView.setBackgroundResource(R.drawable.ic_launcher);
}
});
MyApplication.getHttpQueues().add(request);
}
在布局里面添加一个ImageView,在activity找到,调用上面函数是传进去就可以了,运行结果:
ImageLoader加LruCache图片缓存的方式
先封装图片的缓存BitmapCache类:
/**
* Created by Layne_Yao on 2017-12-20 下午3:52:50.
* CSDN:http://blog.csdn.net/Jsagacity
*/
public class BitmapCache implements ImageCache {
public LruCache<String, Bitmap> cache;
public int max = 10 * 1024 * 1024;
public BitmapCache() {
cache = new LruCache<String, Bitmap>(max) {
@Override
protected int sizeOf(String key, Bitmap value) {
// TODO Auto-generated method stub
return value.getRowBytes() * value.getHeight();
}
};
}
@Override
public Bitmap getBitmap(String url) {
// TODO Auto-generated method stub
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
// TODO Auto-generated method stub
cache.put(url, bitmap);
}
}
而后进行图片网络请求:
//ImageLoader加ImageCache图片缓存的方式
public static void volleyImageTwo(ImageView imageView) {
String url = "https://www.baidu.com/img/bdlogo.png";
ImageLoader loader = new ImageLoader(MyApplication.getHttpQueues(),
new BitmapCache());
ImageListener listener = ImageLoader.getImageListener(imageView,
R.drawable.ic_launcher, R.drawable.ic_launcher);
loader.get(url, listener);
}
运行结果:
NetworkImageView方式
NetworkImageView不同于以上两种方式是NetworkImageView是一个自定义控件,它是继承自ImageView的,具备ImageView控件的所有功能,并且在原生的基础之上加入了加载网络图片的功能。
在布局中添加:
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/network_image_view"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
进行网络图片请求:
//NetworkImageView的方式請求
public static void volleyImageThree(NetworkImageView networkImageView){
String url = "https://www.baidu.com/img/bdlogo.png";
ImageLoader loader = new ImageLoader(MyApplication.getHttpQueues(),
new BitmapCache());
//设置请求期间的显示
networkImageView.setDefaultImageResId(R.drawable.ic_launcher);
//设置请求失败的显示
networkImageView.setErrorImageResId(R.drawable.ic_launcher);
networkImageView.setImageUrl(url, loader);
}
运行结果:
以上就是对Volley框架的简单使用。
源码下载