Volley是Gogle在Google I/O 2013所發表的網路框架,主要是為了加強Android網路應用的效能。推出Volley的原因是:
- 目前在Android上抓取網路資料的標準作法,是需要透過執行緒,再把結果送回主程序,過程稍嫌複雜
可說是集中非同步的網路通訊優點,同時提供了字串、JSON、圖片三種請求方式。內部再把Http和執行緒封裝起來。還提供Cache,使得在performance上改善不少。
Google建議使用Volley來存取資料量不大且頻繁的網路通訊,Volley在大量資料的傳輸上,效能很差。
目前沒有Google官方提供的Volley封裝檔,建議如下步驟:
String、Json、Image三個的寫法差不多,都是先從URL連結啟動請求之後,將請求加到Queue去處理(請注意,這是非同步的),若成功則在onResponse事件中取得回傳值,若失敗則會在onErrorResponse得到錯誤訊息。
for Gradle
compile 'com.mcxiaoke.volley:library:1.0.19'
Premission (AndroidManifest.xml)
別忘了,Volley 是需要是用網路的,所以記得加上這一行。
<uses-permission android:name="android.permission.INTERNET" />
Example
RequestQueue mQueue = Volley.newRequestQueue(context);
String url ="http://www.google.com";
StringRequest stringRequest = new StringRequest(url,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);
}
});
mQueue.add(stringRequest);
String url ="http://my-json-feed";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, "UTF-8",
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
});
mQueue.add(jsonObjectRequest);
String url="http://i.imgur.com/rwTYZzF.png";
ImageRequest imageRequest = new ImageRequest(
url, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
imageView.setImageBitmap(response);
}
}, 0, 0, null, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
imageView.setImageResource(R.drawable.default_image);
}
});
mQueue.add(imageRequest);
可稍微
改寫一下JsonRequest使得資料更好取得
String url = "http://my-json-feed";
// 取得資料並編碼
JsonArrayPostRequest jRequest = new JsonArrayPostRequest(url,
new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
//... easy to do something
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// 設定執行為最高優先權
jRequest.setPriority(Request.Priority.HIGH);
mQueue.add(jRequest);
ref:
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
http://code.tutsplus.com/tutorials/an-introduction-to-volley--cms-23800
https://github.com/mcxiaoke/android-volley
http://blog.csdn.net/guolin_blog/article/details/17482095