添加Volley库
首先需要下载Volley的jar包或者自己编译Volley源码,Volley源码的下载地址:
https://android.googlesource.com/platform/frameworks/volley/+archive/master.tar.gz
以Android Studio添加Volley源码为例,下载好Volley源码后,将其解压,得到目录volley-master
。
在Andorid Studio的菜单File - New - Import Module...
选项中将解压的目录作为module导入到项目中,下面以volley-master
作为volley模块的名称。
需要注意的一点是,在volley-master/build.gradle
文件中,含有volley源码的编译信息,如下所示:
android {
compileSdkVersion 22
buildToolsVersion = '22.0.1'
}
则编译该源码所需要的Android SDK Build-tools
的版本为22.0.1,应该保证系统中安装了该版本的build-tools。因为更高版本的build-tools中废弃了一些类,会导致使用高版本的build-tools无法编译通过。
选中导入的要作为库的volley-master模块,在菜单中选择Build - Rebuild Project
编译模块。
编译完成后,在菜单中选择File - Project Structure...
或者按快捷键Ctrl+Alt+Shift+S
打开Project Structure面板,在左侧选中要使用volley框架的module,然后在右侧选择Dependencies
选项卡,点击右边的绿色加号按钮
,选择3 Module dependency
,在弹出的窗口中选择导入volley-master模块,之后即可使用volley。
Volley的简单用法
使用volley前,首先要建立一个volley的全局请求队列,用来管理请求。
在Application类中创建全局请求队列,在onCreate()方法中实例化请求队列,为请求队列设置get方法。
public class MyApplication extends Application {
//Volley的全局请求队列
public static RequestQueue sRequestQueue;
/**
* @return Volley全局请求队列
*/
public static RequestQueue getRequestQueue() {
return sRequestQueue;
}
@Override
public void onCreate() {
super.onCreate();
//实例化Volley全局请求队列
sRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
}
然后要在AndroidManifest中注册Application,添加网络权限。
<uses-permission android:name="android.permission.INTERNET"/>
<application android:name=".MyApplication"/>
StringRequest和JsonObjectRequest
可以在volley源码中查看volley有哪些请求方式,这里以StringRequest和JsonObjectRequest为例。
JsonObjectRequest处理返回JSON格式数据的请求,当返回数据格式非JSON格式或对所请求的数据的返回格式不确定时使用StringRequest。
下面只写出部分示例代码,完整代码请看:
https://github.com/VDerGoW/AndroidMain/tree/master/volley-demo/src/main/java/tips/volleytest
StringRequest的使用示例:
创建StringRequest实例,传入请求类型(GET/POST)请求的URL,请求成功的监听器,请求失败的监听器四个参数。其中两个监听器需要实现接口方法,分别处理请求成功和请求失败的事件。
为StringRequest实例设置tag,可以通过该tag在全局队列中访问到该实例。
将StringRequest实例加入到全局队列中。
GET方式:
/**
* Volley的StringRequest使用示例
* HTTP method : GET
*/
public void volleyStringRequestDemo_GET() {
//Volley request,参数:请求方式,请求的URL,请求成功的回调,请求失败的回调
StringRequest stringRequest = new StringRequest(Request.Method.GET, url_GET, new Response.Listener<String>() {
/**
* 请求成功的回调
* @param response 请求返回的数据
*/
@Override
public void onResponse(String response) {
// TODO: 处理返回结果
Log.i("### onResponse", "GET_StringRequest:" + response);
}
}, new Response.ErrorListener() {
/**
* 请求失败的回调
* @param error VolleyError
*/
@Override
public void onErrorResponse(VolleyError error) {
// TODO: 处理错误
Log.e("### onErrorResponse", "GET_StringRequest:" + error.toString());
}
});
//为request设置tag,通过该tag在全局队列中访问request
stringRequest.setTag(VOLLEY_TAG);//StringRequestTest_GET
//将request加入全局队列
MyApplication.getRequestQueue().add(stringRequest);
}
POST方式的使用示例:
使用POST方式需要实现StringRequest类的getParams()方法,实现参数映射。
/**
* Volley的StringRequest使用示例
* HTTP method : POST
* 内部注释和方法volleyStringRequestDemo_GET()相同
*/
public void volleyStringRequestDome_POST() {
String url = JUHE_API_URL;
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// TODO: 处理返回结果
Log.i("### onResponse", "POST_StringRequest:" + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO: 处理错误
Log.e("### onErrorResponse", "POST_StringRequest:" + error.toString());
}
}) {
/**
* 返回含有POST或PUT请求的参数的Map
*/
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> paramMap = new HashMap<>();
// TODO: 处理POST参数
paramMap.put("postcode", postcode);
paramMap.put("key", JUHE_APPKEY);
return paramMap;
}
};
stringRequest.setTag(VOLLEY_TAG);//StringRequest_POST
MyApplication.getRequestQueue().add(stringRequest);
}
JsonObjectRequest的使用示例:
GET方式:
/**
* Volley的JsonObjectRequest使用示例
* HTTP method : GET
* 内部注释和方法volleyStringRequestDemo_GET()相同
*/
public void volleyJsonObjectRequestDemo_GET() {
/*
* 第三个参数:request的参数(POST),传入null表示没有需要传递的参数
* 此处为GET方式传输,参数已经包含在URL中
* */
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url_GET, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// TODO: 处理返回结果
Log.i("### onResponse", "GET_JsonObjectRequest:" + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO: 处理错误
Log.e("### onErrorResponse", "GET_JsonObjectRequest:" + error.toString());
}
});
jsonObjectRequest.setTag(VOLLEY_TAG);//JsonObjectRequestTest_GET
MyApplication.getRequestQueue().add(jsonObjectRequest);
}
Activity的退出的同时停止Volley网络请求
覆写Activity的oStop()方法,在其中调用全局队列的cancelAll()方法,传入相应的tag,取消其网络请求。
@Override
protected void onStop() {
super.onStop();
//当Activity停止运行后,取消Activity的所有网络请求
MyApplication.getRequestQueue().cancelAll(VOLLEY_TAG);
Log.i("### onStop", "cancel all:tag=" + VOLLEY_TAG);
}
ImageRequest的使用
ImageRequest的使用示例:
public class VolleyImageRequestDemo {
public static final String IMAGE_URL = "https://www.baidu.com/img/bd_logo1.png";
public static final String VOLLEY_TAG = "tag_volley_image_request";
public void volleyImageRequestDemo(final Callback callback) {
// @param maxWidth : Maximum width to decode this bitmap to, or zero for none
// @param maxHeight : Maximum height to decode this bitmap to, or zero for none
// If both width and height are zero, the image will be decoded to its natural size
ImageRequest imageRequest = new ImageRequest(IMAGE_URL, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
// 请求成功
callback.onSuccess(response);
}
}, 0, 0, ImageView.ScaleType.FIT_XY, Bitmap.Config.RGB_565, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// 请求失败
Log.i("### onErrorResponse", "ImageRequest:" + error.toString());
callback.onError(error);
}
});
imageRequest.setTag(VOLLEY_TAG);
MyApplication.getRequestQueue().add(imageRequest);
}
// 为了能单独写一个类出来,又能把请求到的图片设置到Activity的ImageView中
// 我写了个回调接口,如果把ImageRequest直接写在Activity中,就不需要回调了
public interface Callback {
void onSuccess(Bitmap response);
void onError(VolleyError error);
}
}
ImageLoader的使用
使用ImageLoader,首先要有一个ImageCache,所以要定义一个类,实现ImageLoader.ImageCache接口。然后实现getBitmap()方法和putBitmap()方法,并在构造方法中实例化一个LruCache对象,用于存放图片。
ImageCache示例:
/**
* Simple cache adapter interface. If provided to the ImageLoader, it
* will be used as an L1 cache before dispatch to Volley. Implementations
* must not block. Implementation with an LruCache is recommended.
*/
public class VolleyBitmapCacheDemo implements ImageLoader.ImageCache {
private LruCache<String, Bitmap> mCache;
public VolleyBitmapCacheDemo() {
int maxMemorySize = 1024 * 1024 * 10;
mCache = new LruCache<String, Bitmap>(maxMemorySize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getRowBytes() * bitmap.getHeight();
}
};
}
@Override
public Bitmap getBitmap(String key) {
return mCache.get(key);
}
@Override
public void putBitmap(String key, Bitmap bitmap) {
mCache.put(key, bitmap);
}
}
然后在Activity中使用ImageLoader:
ImageLoader imageLoader = new ImageLoader(MyApplication.getRequestQueue(), new VolleyBitmapCacheDemo());
ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(mLoaderImage, R.mipmap.ic_launcher,R.mipmap.ic_launcher);
imageLoader.get(IMAGE_URL, imageListener);
完整的示例代码请看:
https://github.com/VDerGoW/AndroidMain/tree/master/volley-demo/src/main/java/tips/volleytest