Android 淺析 Volley (一) 使用
前言
Linus Benedict Torvalds : RTFSC – Read The Fucking Source Code
概括
Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster.
Volley excels at RPC-type operations used to populate a UI, such as fetching a page of search results as structured data. It integrates easily with any protocol and comes out of the box with support for raw strings, images, and JSON. By providing built-in support for the features you need, Volley frees you from writing boilerplate code and allows you to concentrate on the logic that is specific to your app.
使用
Http請求
Step 1.創建RequestQueue隊列
RequestQueue mQueue = Volley.newRequestQueue(this);
通過newRequestQueue
創建一個新的RequestQueue隊列。
Step 2.創建StringRequest對象
StringRequest stringRequest = new StringRequest(
"http://www.baidu.com",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("TAG", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}
);
這里可以看到StringRequest有三個默認參數,第一個是目標的Url,第二個是設置一個回調,第三個是監聽錯誤回調的。
Step 3.將quest對象添加到隊列里
mQueue.add(stringRequest);
最后就是將StringRequest對象往StringRequest里面扔就行了。
圖片請求
Step 1.創建RequestQueue對象
RequestQueue mQueue = Volley.newRequestQueue(this);
通過newRequestQueue
創建一個新的RequestQueue隊列。
Step 2.創建ImageRequest對象
mImageView = (ImageView) findViewById(R.id.imageView);
ImageRequest imageRequest = new ImageRequest(
"http://app.sjk.ijinshan.com/market/img/zs/2300841/20150805140347461.png",
new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
mImageView.setImageBitmap(response);
}
}, 0, 0,
Config.RGB_565, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mImageView.setImageResource(R.drawable.default_image);
}
}
);
ImageRequest的構造函數接收六個參數,第一個參數就是圖片的URL地址。第二個參數是圖片請求成功的回調,這里我們把返回的Bitmap參數設置到ImageView中。第三第四個參數分別用于指定允許圖片最大的寬度和高度,如果指定的網絡圖片的寬度或高度大于這里的最大值,則會對圖片進行壓縮,指定成0的話就表示不管圖片有多大,都不會進行壓縮。第五個參數用于指定圖片的顏色屬性,Bitmap.Config下的幾個常量都可以在這里使用,其中ARGB_8888可以展示最好的顏色屬性,每個圖片像素占據4個字節的大小,而RGB_565則表示每個圖片像素占據2個字節大小。第六個參數是圖片請求失敗的回調,這里我們當請求失敗時在ImageView中顯示一張默認圖片。
Step 3.將quest對象添加到隊列里
mQueue.add(stringRequest);
最后就是將StringRequest對象往StringRequest里面扔就行了。
自定義Quest請求
自定義類
自定義的請求其實很簡單,首先是繼承父類Request<T>,然后重載其中兩個函數parseNetworkResponse(NetworkResponse response)
,deliverResponse(XmlPullParser response)
。就可以像用StringResponse那樣去使用了。
總結
Volley總體來說非常好用和方便,封裝好了各種網絡請求,特別是底層支持對開發者來說免除了很多煩惱,還可以定制自己的Response。