Volley框架
Volley框架
volley是谷歌官方在2013年推出的Android平台上的网络通信库
特点
- 网络通信更快,更简单,开发效率高,稳定性高。
- 对get和post网络请求以及网络图片高效的
异步处理
请求。 - 可以对网络请求进行优先级
排序处理
。 - 网络请求的
缓存
。 - 多级别取消请求。
- 和Activity生命周期的联动。
缺点
不适合数据的上传与下载
Get和Post请求接口的使用
请求对象
- StringRequest 返回结果类型不确定(它包含后面两种)
StringRequest request =newStringRequest(Request.Method.GET, REQUEST_URL,newResponse.Listener<String>(){
@Override
publicvoid onResponse(String s){//数据请求成功
result.setText("请求成功:"+ s);
}
},newResponse.ErrorListener(){
@Override
publicvoid onErrorResponse(VolleyError volleyError){//数据请求失败
result.setText("请求失败:"+ volleyError.getMessage());
}
});
- JsonObjectRequest
JSONObject jsonRequest =newJSONObject();//Get请求传递参数jsonRequest可以为空null
JsonObjectRequest request =newJsonObjectRequest(Request.Method.GET, REQUEST_URL,null,newResponse.Listener<JSONObject>(){
@Override
publicvoid onResponse(JSONObject jsonObject){
result.setText("请求成功:"+ jsonObject);
}
},newResponse.ErrorListener(){
@Override
publicvoid onErrorResponse(VolleyError volleyError){
result.setText("请求失败:"+ volleyError.getMessage());
}
});
- JsonArrayRequest
JsonArrayRequest request =newJsonArrayRequest(REQUEST_URL,newResponse.Listener<JSONArray>(){
@Override
publicvoid onResponse(JSONArray jsonArray){
result.setText("请求成功:"+ jsonArray);
}
},newResponse.ErrorListener(){
@Override
publicvoid onErrorResponse(VolleyError volleyError){
result.setText("请求失败:"+ volleyError.getMessage());
}
});
网络请求队列建立和取消队列建立
- 建立一个全局的请求队列。
//创建请求队列
privatestaticRequestQueue queues;
//初始化请求队列
queues =Volley.newRequestQueue(getApplicationContext());
- 建立一个请求并加入队列中。
MyApplication.getQueues().add(request);
- 取消队列
MyApplication.getQueues().cancelAll(tag);
与Activity生命周期的联动
- 可以在Activity销毁的同时关闭请求。
- 设置Tag标签,在onStop()里执行取消请求。
@Override
protectedvoid onStop(){
super.onStop();
//结束请求
MyApplication.getQueues().cancelAll("StringRequest_get");
}
Volley调用实例源码展示
demo效果如下
- 布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.xhb.app.MainActivity"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="@+id/_StringRequestGet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="StringRequestGet"
android:text="StringRequestGet"
android:textAllCaps="false"/>
<Button
android:id="@+id/StringRequestPost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@id/_StringRequestGet"
android:onClick="StringRequestPost"
android:text="StringRequestPost"
android:textAllCaps="false"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="@+id/JsonObjectRequestGet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="JsonObjectRequestGet"
android:text="JsonObjectRequestGet"
android:textAllCaps="false"/>
<Button
android:id="@+id/JsonObjectRequestPost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@id/JsonObjectRequestGet"
android:onClick="JsonObjectRequestPost"
android:text="JsonObjectRequestPost"
android:textAllCaps="false"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="@+id/JsonArrayRequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:onClick="JsonArrayRequest"
android:text="JsonArrayRequest"
android:textAllCaps="false"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="@+id/MyRequestGet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="MyRequestGet"
android:text="MyRequestGet"
android:textAllCaps="false"/>
<Button
android:id="@+id/MyRequestPost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@id/MyRequestGet"
android:onClick="MyRequestPost"
android:text="MyRequestPost"
android:textAllCaps="false"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="@+id/ImageRequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="ImageRequest"
android:text="ImageRequest"
android:textAllCaps="false"/>
<Button
android:id="@+id/ImageLoader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@id/ImageRequest"
android:onClick="ImageLoader"
android:text="ImageLoader"
android:textAllCaps="false"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<ImageView
android:id="@+id/image_imageRequest"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:textAllCaps="false"/>
<ImageView
android:id="@+id/image_iamgeLoader"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@id/image_imageRequest"
android:src="@mipmap/ic_launcher"
android:textAllCaps="false"/>
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="请求结果为:"/>
<TextView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
- 全局初始化文件
publicclassMyApplicationextendsApplication{
//创建请求队列
privatestaticRequestQueue queues;
@Override
publicvoid onCreate(){
super.onCreate();
//初始书请求队列
queues =Volley.newRequestQueue(getApplicationContext());
}
publicstaticRequestQueue getQueues(){
return queues;
}
}
- 主要实现文件
publicclassMainActivityextendsAppCompatActivity{
publicstaticfinalString BASE ="http://op.juhe.cn/onebox/weather/query";
publicstaticfinalString REQUEST_URL = BASE +"?cityname=%E5%8D%81%E5%A0%B0&key=634f562a2b3900e051c6af6e2dc3017e";
publicstaticfinalString IMAGE_URL ="https://pic.cnblogs.com/avatar/789527/20160825180355.png";
privateTextView result;
privateImageView image_imageRequest, image_iamgeLoader;
@Override
protectedvoid onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result =(TextView) findViewById(R.id.result);
image_imageRequest =(ImageView) findViewById(R.id.image_imageRequest);
image_iamgeLoader =(ImageView) findViewById(R.id.image_iamgeLoader);
}
publicvoidStringRequestGet(View view){
//StringRequest
StringRequest request =newStringRequest(Request.Method.GET, REQUEST_URL,newResponse.Listener<String>(){
@Override
publicvoid onResponse(String s){//数据请求成功
result.setText("请求成功:"+ s);
}
},newResponse.ErrorListener(){
@Override
publicvoid onErrorResponse(VolleyError volleyError){//数据请求失败
result.setText("请求失败:"+ volleyError.getMessage());
}
});
request.setTag("StringRequest_get");
MyApplication.getQueues().add(request);
}
publicvoidStringRequestPost(View view){
//StringRequest
StringRequest request =newStringRequest(Request.Method.POST, BASE,newResponse.Listener<String>(){
@Override
publicvoid onResponse(String s){//数据请求成功
result.setText("请求成功:"+ s);
}
},newResponse.ErrorListener(){
@Override
publicvoid onErrorResponse(VolleyError volleyError){//数据请求失败
result.setText("请求失败:"+ volleyError.getMessage());
}
}){
@Override//传递参数
protectedMap<String,String> getParams()throwsAuthFailureError{
Map<String,String> map =newHashMap<>();
map.put("key","634f562a2b3900e051c6af6e2dc3017e");
map.put("cityname","十堰");
return map;
}
};
request.setTag("StringRequestPost");
MyApplication.getQueues().add(request);
}
publicvoidJsonObjectRequestGet(View view){
//JsonObjectRequest
JSONObject jsonRequest =newJSONObject();//Get请求传递参数jsonRequest可以为空null
JsonObjectRequest request =newJsonObjectRequest(Request.Method.GET, REQUEST_URL,null,newResponse.Listener<JSONObject>(){
@Override
publicvoid onResponse(JSONObject jsonObject){
result.setText("请求成功:"+ jsonObject);
}
},newResponse.ErrorListener(){
@Override
publicvoid onErrorResponse(VolleyError volleyError){
result.setText("请求失败:"+ volleyError.getMessage());
}
});
request.setTag("JsonObjectRequestGet");
MyApplication.getQueues().add(request);
}
publicvoidJsonObjectRequestPost(View view){
Map<String,String> map =newHashMap<>();
map.put("key","634f562a2b3900e051c6af6e2dc3017e");
map.put("cityname","十堰");
JSONObject jsonRequest =newJSONObject(map);
JsonObjectRequest request =newJsonObjectRequest(Request.Method.POST, BASE, jsonRequest,newResponse.Listener<JSONObject>(){
@Override
publicvoid onResponse(JSONObject jsonObject){
result.setText("请求成功:"+ jsonObject.toString());
}
},newResponse.ErrorListener(){
@Override
publicvoid onErrorResponse(VolleyError volleyError){
result.setText("请求失败:"+ volleyError.getMessage());
}
});
request.setTag("JsonObjectRequestPost");
MyApplication.getQueues().add(request);
}
publicvoidJsonArrayRequest(View view){
JsonArrayRequest request =newJsonArrayRequest(REQUEST_URL,newResponse.Listener<JSONArray>(){
@Override
publicvoid onResponse(JSONArray jsonArray){
result.setText("请求成功:"+ jsonArray);
}
},newResponse.ErrorListener(){
@Override
publicvoid onErrorResponse(VolleyError volleyError){
result.setText("请求失败:"+ volleyError.getMessage());
}
});
request.setTag("JsonArrayRequest");
MyApplication.getQueues().add(request);
}
publicvoidMyRequestGet(View view){
newVolleyRequest().RequestGet(this, REQUEST_URL,"MyRequestGet",newResultBack(this,ResultBack.listener,ResultBack.errorListener){
@Override
publicvoid onSuccess(String s){
result.setText("请求成功:"+ s);
}
@Override
publicvoid onFailure(VolleyError volleyError){
result.setText("请求失败:"+ volleyError.getMessage());
}
});
}
publicvoidMyRequestPost(View view){
Map<String,String> map =newHashMap<>();
map.put("key","634f562a2b3900e051c6af6e2dc3017e");
map.put("cityname","十堰");
newVolleyRequest().RequestPost(this, REQUEST_URL,"MyRequestPost", map,newResultBack(this,ResultBack.listener,ResultBack.errorListener){
@Override
publicvoid onSuccess(String s){
result.setText("请求成功:"+ s);
}
@Override
publicvoid onFailure(VolleyError volleyError){
result.setText("请求失败:"+ volleyError.getMessage());
}
});
}
//ImageRequest方式加载图片
publicvoidImageRequest(View view){
ImageRequest request =newImageRequest(IMAGE_URL,newResponse.Listener<Bitmap>(){
@Override
publicvoid onResponse(Bitmap bitmap){//加载成功
image_imageRequest.setImageBitmap(bitmap);
}
},0,0,Bitmap.Config.RGB_565,newResponse.ErrorListener(){//加载失败
@Override
publicvoid onErrorResponse(VolleyError volleyError){
image_imageRequest.setImageResource(R.mipmap.ic_launcher);
}
});
request.setTag("ImageRequest");
MyApplication.getQueues().add(request);
}
//ImageLoader加载图片
publicvoidImageLoader(View view){
ImageLoader imageLoader =newImageLoader(MyApplication.getQueues(),newBitmapCache());
ImageLoader.ImageListener listener = imageLoader.getImageListener(image_iamgeLoader, R.mipmap.ic_launcher, R.mipmap.ic_launcher);
imageLoader.get(IMAGE_URL, listener);
}
@Override
protectedvoid onStop(){
super.onStop();
//结束请求
MyApplication.getQueues().cancelAll("StringRequest_get");
}
}
- Volley简单的二次回调封装
publicclassVolleyRequest{
publicstaticStringRequest stringRequest;
publicstaticvoidRequestGet(Context context,String url,String tag,ResultBack reback){
MyApplication.getQueues().cancelAll(tag);
stringRequest=newStringRequest(Request.Method.GET, url,reback.loadingListener(),reback.errorListener());
stringRequest.setTag(tag);
MyApplication.getQueues().add(stringRequest);
MyApplication.getQueues().start();
}
publicstaticvoidRequestPost(Context context,String url,String tag,finalMap<String,String> map,ResultBack reback){
MyApplication.getQueues().cancelAll(tag);
stringRequest=newStringRequest(Request.Method.GET, url, reback.loadingListener(),reback.errorListener()){
@Override
protectedMap<String,String> getParams()throwsAuthFailureError{
return map;
}
};
stringRequest.setTag(tag);
MyApplication.getQueues().add(stringRequest);
MyApplication.getQueues().start();
}
}
自定义的回调接口
publicabstractclassResultBack{
publicContext context;
publicstaticResponse.Listener<String> listener;
publicstaticResponse.ErrorListener errorListener;
publicResultBack(Context context,Response.Listener<String> listener,Response.ErrorListener errorListener){
this.context = context;
this.listener = listener;
this.errorListener = errorListener;
}
publicResponse.Listener<String> loadingListener(){
listener =newResponse.Listener<String>(){
@Override
publicvoid onResponse(String s){
onSuccess(s);
}
};
return listener;
}
publicResponse.ErrorListener errorListener(){
errorListener =newResponse.ErrorListener(){
@Override
publicvoid onErrorResponse(VolleyError volleyError){
onFailure(volleyError);
}
};
return errorListener;
}
publicabstractvoid onSuccess(String s);
publicabstractvoid onFailure(VolleyError volleyError);
}
- 图像缓存类
publicclassBitmapCacheimplementsImageLoader.ImageCache{
publicLruCache<String,Bitmap> mBitmapLruCache;
publicint max=1024*1024*10;// 最大缓存10M,超过就会回收
publicBitmapCache(){
mBitmapLruCache=newLruCache<String,Bitmap>(max){
@Override
protectedint sizeOf(String key,Bitmap value){
return value.getRowBytes()*value.getHeight();
}
};
}
@Override
publicBitmap getBitmap(String s){
return mBitmapLruCache.get(s);
}
@Override
publicvoid putBitmap(String s,Bitmap bitmap){
mBitmapLruCache.put(s,bitmap);
}
}