[Android]Volley的使用


Volley是Google I/O 2013上提出來的為Android提供簡單快速網絡訪問的項目。Volley特別適合數據量不大但是通信頻繁的場景

優勢

相比其他網絡載入類庫,Volley 的優勢官方主要提到如下幾點:

  1. 隊列網絡請求,並自動合理安排何時去請求。
  2. 提供了默認的磁盤和內存等緩存(Disk Caching & Memory Caching)選項。
  3. Volley 可以做到高度自定義,它能做到的不僅僅是緩存圖片等資源。
  4. Volley 相比其他的類庫更方便調試和跟蹤。

資料:

 

0. https://www.captechconsulting.com/blog/raymond-robinson/google-io-2013-volley-image-cache-tutorial

 

1. Asynchronous HTTP Requests in Android Using Volley

http://www.it165.net/pro/html/201310/7419.html 

作者:張興業  發布日期:2013-10-09 22:16:03

Volley是Android開發者新的瑞士軍刀,它提供了優美的框架,使得Android應用程序網絡訪問更容易和更快。 Volley抽象實現了底層的HTTP Client庫,讓你不關注HTTP Client細節,專注於寫出更加漂亮、干凈的RESTful HTTP請求。另外,Volley請求會異步執行,不阻擋主線程。

Volley提供的功能

簡單的講,提供了如下主要的功能:

1、封裝了的異步的RESTful 請求API;

2、一個優雅和穩健的請求隊列;

3、一個可擴展的架構,它使開發人員能夠實現自定義的請求和響應處理機制;

4、能夠使用外部HTTP Client庫;

5、緩存策略;

6、自定義的網絡圖像加載視圖(NetworkImageView,ImageLoader等);

 

為什么使用異步HTTP請求?

Android中要求HTTP請求異步執行,如果在主線程執行HTTP請求,可能會拋出android.os.NetworkOnMainThreadException 異常。阻塞主線程有一些嚴重的后果,它阻礙UI渲染,用戶體驗不流暢,它可能會導致可怕的ANR(Application Not Responding)。要避免這些陷阱,作為一個開發者,應該始終確保HTTP請求是在一個不同的線程。

 

怎樣使用Volley

這篇博客將會詳細的介紹在應用程程中怎么使用volley,它將包括一下幾方面:

1、安裝和使用Volley庫

2、使用請求隊列

3、異步的JSON、String請求

4、取消請求

5、重試失敗的請求,自定義請求超時

6、設置請求頭(HTTP headers)

7、使用Cookies

8、錯誤處理

 

安裝和使用Volley庫

引入Volley非常簡單,首先,從git庫先克隆一個下來:

 

然后編譯為jar包,再把jar包放到自己的工程的libs目錄。
 

使用請求隊列

 

Volley的所有請求都放在一個隊列,然后進行處理,這里是你如何將創建一個請求隊列:

 

1. RequestQueue mRequestQueue = Volley.newRequestQueue(this); // 'this' is Context

理想的情況是把請求隊列集中放到一個地方,最好是初始化應用程序類中初始化請求隊列,下面類做到了這一點:
 

01. public class ApplicationController extends Application {
02.  
03. /**
04. * Log or request TAG
05. */
06. public static final String TAG = "VolleyPatterns";
07.  
08. /**
09. * Global request queue for Volley
10. */
11. private RequestQueue mRequestQueue;
12.  
13. /**
14. * A singleton instance of the application class for easy access in other places
15. */
16. private static ApplicationController sInstance;
17.  
18. @Override
19. public void onCreate() {
20. super.onCreate();
21.  
22. // initialize the singleton
23. sInstance = this;
24. }
25.  
26. /**
27. * @return ApplicationController singleton instance
28. */
29. public static synchronized ApplicationController getInstance() {
30. return sInstance;
31. }
32.  
33. /**
34. * @return The Volley Request queue, the queue will be created if it is null
35. */
36. public RequestQueue getRequestQueue() {
37. // lazy initialize the request queue, the queue instance will be
38. // created when it is accessed for the first time
39. if (mRequestQueue == null) {
40. mRequestQueue = Volley.newRequestQueue(getApplicationContext());
41. }
42.  
43. return mRequestQueue;
44. }
45.  
46. /**
47. * Adds the specified request to the global queue, if tag is specified
48. * then it is used else Default TAG is used.
49. *
50. * @param req
51. * @param tag
52. */
53. public <T> void addToRequestQueue(Request<T> req, String tag) {
54. // set the default tag if tag is empty
55. req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
56.  
57. VolleyLog.d("Adding request to queue: %s", req.getUrl());
58.  
59. getRequestQueue().add(req);
60. }
61.  
62. /**
63. * Adds the specified request to the global queue using the Default TAG.
64. *
65. * @param req
66. * @param tag
67. */
68. public <T> void addToRequestQueue(Request<T> req) {
69. // set the default tag if tag is empty
70. req.setTag(TAG);
71.  
72. getRequestQueue().add(req);
73. }
74.  
75. /**
76. * Cancels all pending requests by the specified TAG, it is important
77. * to specify a TAG so that the pending/ongoing requests can be cancelled.
78. *
79. * @param tag
80. */
81. public void cancelPendingRequests(Object tag) {
82. if (mRequestQueue != null) {
83. mRequestQueue.cancelAll(tag);
84. }
85. }
86. }

異步的JSON、String請求

Volley提供了以下的實用工具類進行異步HTTP請求:

 

  • JsonObjectRequest — To send and receive JSON Object from the Server
  • JsonArrayRequest — To receive JSON Array from the Server
  • StringRequest — To retrieve response body as String (ideally if you intend to parse the response by yourself)

JsonObjectRequest

這個類可以用來發送和接收JSON對象。這個類的一個重載構造函數允許設置適當的請求方法(DELETE,GET,POST和PUT)。如果您正在使用一個RESTful服務端,可以使用這個類。下面的示例顯示如何使GET和POST請求。
 

GET請求:

 

01. final String URL = "/volley/resource/12";
02. // pass second argument as "null" for GET requests
03. JsonObjectRequest req = new JsonObjectRequest(URL, null,
04. new Response.Listener<JSONObject>() {
05. @Override
06. public void onResponse(JSONObject response) {
07. try {
08. VolleyLog.v("Response:%n %s", response.toString(4));
09. } catch (JSONException e) {
10. e.printStackTrace();
11. }
12. }
13. }, new Response.ErrorListener() {
14. @Override
15. public void onErrorResponse(VolleyError error) {
16. VolleyLog.e("Error: ", error.getMessage());
17. }
18. });
19.  
20. // add the request object to the queue to be executed
21. ApplicationController.getInstance().addToRequestQueue(req);

POST請求:

 

01. final String URL = "/volley/resource/12";
02. // Post params to be sent to the server
03. HashMap<String, String> params = new HashMap<String, String>();
04. params.put("token", "AbCdEfGh123456");
05.  
06. JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
07. new Response.Listener<JSONObject>() {
08. @Override
09. public void onResponse(JSONObject response) {
10. try {
11. VolleyLog.v("Response:%n %s", response.toString(4));
12. } catch (JSONException e) {
13. e.printStackTrace();
14. }
15. }
16. }, new Response.ErrorListener() {
17. @Override
18. public void onErrorResponse(VolleyError error) {
19. VolleyLog.e("Error: ", error.getMessage());
20. }
21. });
22.  
23. // add the request object to the queue to be executed
24. ApplicationController.getInstance().addToRequestQueue(req);

JsonArrayRequest

這個類可以用來接受 JSON Arrary,不支持JSON Object。這個類現在只支持 HTTP GET。由於支持GET,你可以在URL的后面加上請求參數。類的構造函數不支持請求參數。

 

01. final String URL = "/volley/resource/all?count=20";
02. JsonArrayRequest req = new JsonArrayRequest(URL, new Response.Listener<JSONArray> () {
03. @Override
04. public void onResponse(JSONArray response) {
05. try {
06. VolleyLog.v("Response:%n %s", response.toString(4));
07. } catch (JSONException e) {
08. e.printStackTrace();
09. }
10. }
11. }, new Response.ErrorListener() {
12. @Override
13. public void onErrorResponse(VolleyError error) {
14. VolleyLog.e("Error: ", error.getMessage());
15. }
16. });
17.  
18. // add the request object to the queue to be executed
19. ApplicationController.getInstance().addToRequestQueue(req);

StringRequest

這個類可以用來從服務器獲取String,如果想自己解析請求響應可以使用這個類,例如返回xml數據。它還可以使用重載的構造函數定制請求。

 

01. final String URL = "/volley/resource/recent.xml";
02. StringRequest req = new StringRequest(URL, new Response.Listener<String>() {
03. @Override
04. public void onResponse(String response) {
05. VolleyLog.v("Response:%n %s", response);
06. }
07. }, new Response.ErrorListener() {
08. @Override
09. public void onErrorResponse(VolleyError error) {
10. VolleyLog.e("Error: ", error.getMessage());
11. }
12. });
13.  
14. // add the request object to the queue to be executed
15. ApplicationController.getInstance().addToRequestQueue(req);

取消請求

Volley提供了強大的API取消未處理或正在處理的請求。取消請求最簡單的方法是調用請求隊列cancelAll(tag)的方法,前提是你在添加請求時設置了標記。這樣就能使標簽標記的請求掛起。


給請求設置標簽:

 

1. request.setTag("My Tag");

使用ApplicationController添加使用了標簽的請求到隊列中:

 

1. ApplicationController.getInstance().addToRequestQueue(request, "My Tag");


取消所有指定標記的請求:

 

1. mRequestQueue.cancelAll("My Tag");

重試失敗的請求,自定義請求超時

Volley中沒有指定的方法來設置請求超時時間,可以設置RetryPolicy 來變通實現。DefaultRetryPolicy類有個initialTimeout參數,可以設置超時時間。要確保最大重試次數為1,以保證超時后不重新請求。

 

 

 

Setting Request Timeout

1
request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 1, 1.0f)); 
 

 

如果你想失敗后重新請求(因超時),您可以指定使用上面的代碼,增加重試次數。注意最后一個參數,它允許你指定一個退避乘數可以用來實現“指數退避”來從RESTful服務器請求數據。

設置請求頭(HTTP headers)

有時候需要給HTTP請求添加額外的頭信息,一個常用的例子是添加 “Authorization”到HTTP 請求的頭信息。Volley請求類提供了一個 getHeaers()的方法,重載這個方法可以自定義HTTP 的頭信息。

 

添加頭信息:

 

01. JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
02. new Response.Listener<JSONObject>() {
03. @Override
04. public void onResponse(JSONObject response) {
05. // handle response
06. }
07. }, new Response.ErrorListener() {
08. @Override
09. public void onErrorResponse(VolleyError error) {
10. // handle error                       
11. }
12. }) {
13.  
14. @Override
15. public Map<String, String> getHeaders() throws AuthFailureError {
16. HashMap<String, String> headers = new HashMap<String, String>();
17. headers.put("CUSTOM_HEADER", "Yahoo");
18. headers.put("ANOTHER_CUSTOM_HEADER", "Google");
19. return headers;
20. }
21. };

使用Cookies

Volley中沒有直接的API來設置cookies,Volley的設計理念就是提供干凈、簡潔的API來實現RESTful HTTP請求,不提供設置cookies是合理的。

 

下面是修改后的ApplicationController類,這個類修改了getRequestQueue()方法,包含了 設置cookie方法,這些修改還是有些粗糙。

 

01. // http client instance
02. private DefaultHttpClient mHttpClient;
03. public RequestQueue getRequestQueue() {
04. // lazy initialize the request queue, the queue instance will be
05. // created when it is accessed for the first time
06. if (mRequestQueue == null) {
07. // Create an instance of the Http client.
08. // We need this in order to access the cookie store
09. mHttpClient = new DefaultHttpClient();
10. // create the request queue
11. mRequestQueue = Volley.newRequestQueue(this, new HttpClientStack(mHttpClient));
12. }
13. return mRequestQueue;
14. }
15.  
16. /**
17. * Method to set a cookie
18. */
19. public void setCookie() {
20. CookieStore cs = mHttpClient.getCookieStore();
21. // create a cookie
22. cs.addCookie(new BasicClientCookie2("cookie", "spooky"));
23. }
24.  
25.  
26. // add the cookie before adding the request to the queue
27. setCookie();
28.  
29. // add the request to the queue
30. mRequestQueue.add(request);

錯誤處理

正如前面代碼看到的,在創建一個請求時,需要添加一個錯誤監聽onErrorResponse。如果請求發生異常,會返回一個VolleyError實例。

以下是Volley的異常列表:

AuthFailureError:如果在做一個HTTP的身份驗證,可能會發生這個錯誤。

NetworkError:Socket關閉,服務器宕機,DNS錯誤都會產生這個錯誤。

NoConnectionError:和NetworkError類似,這個是客戶端沒有網絡連接。

ParseError:在使用JsonObjectRequest或JsonArrayRequest時,如果接收到的JSON是畸形,會產生異常。

SERVERERROR:服務器的響應的一個錯誤,最有可能的4xx或5xx HTTP狀態代碼。

TimeoutError:Socket超時,服務器太忙或網絡延遲會產生這個異常。默認情況下,Volley的超時時間為2.5秒。如果得到這個錯誤可以使用RetryPolicy。

 

可以使用一個簡單的Help類根據這些異常提示相應的信息:
 

 

01. public class VolleyErrorHelper {
02. /**
03. * Returns appropriate message which is to be displayed to the user
04. * against the specified error object.
05. *
06. * @param error
07. * @param context
08. * @return
09. */
10. public static String getMessage(Object error, Context context) {
11. if (error instanceof TimeoutError) {
12. return context.getResources().getString(R.string.generic_server_down);
13. }
14. else if (isServerProblem(error)) {
15. return handleServerError(error, context);
16. }
17. else if (isNetworkProblem(error)) {
18. return context.getResources().getString(R.string.no_internet);
19. }
20. return context.getResources().getString(R.string.generic_error);
21. }
22.  
23. /**
24. * Determines whether the error is related to network
25. * @param error
26. * @return
27. */
28. private static boolean isNetworkProblem(Object error) {
29. return (error instanceof NetworkError) || (error instanceof NoConnectionError);
30. }
31. /**
32. * Determines whether the error is related to server
33. * @param error
34. * @return
35. */
36. private static boolean isServerProblem(Object error) {
37. return (error instanceof ServerError) || (error instanceof AuthFailureError);
38. }
39. /**
40. * Handles the server error, tries to determine whether to show a stock message or to
41. * show a message retrieved from the server.
42. *
43. * @param err
44. * @param context
45. * @return
46. */
47. private static String handleServerError(Object err, Context context) {
48. VolleyError error = (VolleyError) err;
49.  
50. NetworkResponse response = error.networkResponse;
51.  
52. if (response != null) {
53. switch (response.statusCode) {
54. case 404:
55. case 422:
56. case 401:
57. try {
58. // server might return error like this { "error": "Some error occured" }
59. // Use "Gson" to parse the result
60. HashMap<String, String> result = new Gson().fromJson(new String(response.data),
61. new TypeToken<Map<String, String>>() {
62. }.getType());
63.  
64. if (result != null && result.containsKey("error")) {
65. return result.get("error");
66. }
67.  
68. } catch (Exception e) {
69. e.printStackTrace();
70. }
71. // invalid request
72. return error.getMessage();
73.  
74. default:
75. return context.getResources().getString(R.string.generic_server_down);
76. }
77. }
78. return context.getResources().getString(R.string.generic_error);
79. }
80. }
總結:

Volley是一個非常好的庫,你可以嘗試使用一下,它會幫助你簡化網絡請求,帶來更多的益處。

我也希望更加全面的介紹Volley,以后可能會介紹使用volley加載圖像的內容,歡迎關注。

謝謝你的閱讀,希望你能喜歡。

 

 

2. [譯]Google I/O 2013:Volley 圖片緩存教程

http://www.inferjay.com/blog/2013/08/03/google-i-o-2013-volley-image-cache-tutorial/  Inferjay的技術博客

Gooogle I/O 2013已經結束了,並且對於Android開發的未來它給我們留下了更大的期望。令人非常興奮的是在今年的I/O大會上展示了一個叫Volley的庫。Volley是一個處理和緩存網絡請求的庫,減少開發人員在實際的每一個應用中寫同樣的樣板代碼。寫樣板代碼是很無聊的並且也增加了開發人員出錯的幾率。Google是出於這些考慮創建了Volley

如果你還沒有看過Gooogle I/O中關於Volley的介紹,在繼續這篇文章之前我建議你先去看看關於Volley的介紹,對它有一些基本的理解。

在Google I/O介紹的時候,Ficus Kirpatrick講了很多關於Volley如何的有助於圖片加載。你會發現在Volley作為你的圖片加載解決方案的時候,雖然Volley自己處理了L2的緩存,它需要但是沒有包含L1的緩存。許多人會使用像Universal Image Loader或者Square`s newer Picasso這些第三方的庫去處理圖片的加載;然而這些庫通常已經同時處理了圖片的加載和緩存。所以,我們如何使用Volley來替換圖片的加載和緩存呢?首先,讓我們看看Volley提供的便利的加載方法,我們稍后再看他們的不同之處。

ImageLoader

ImageLoader這個類需要一個Request的實例以及一個ImageCache的實例。圖片通過一個URL和一個ImageListener實例的get()方法就可以被加載。從哪里,ImageLoader會檢查ImageCache,而且如果緩存里沒有圖片就會從網絡上獲取。

NetworkImageView

這個類在布局文件中替換ImageViews,並且將使用ImageLoaderNetworkImageViewsetUrl()這個方法需要一個字符串的URL路徑以及一個ImageLoader的實例。然后它使用ImageLoaderget()方法獲取圖片數據。

1
2
3
4
5
6
7
8
<com.android.volley.toolbox.NetworkImageView  android:id="@+id/twitterUserImage"  android:layout_alignParentLeft="true"  android:layout_alignParentTop="true"  android:layout_width="40dp"  android:layout_height="40dp"  android:padding="5dp"  /> 

ImageCache

VolleyImageCache接口允許你使用你喜歡的L1緩存實現。不幸的是Volley沒有提供默認的實現。在I/O的介紹中展示了BitmapLruCache的一點代碼片段,但是Volley這個庫本身並不包含任何相關的實現。

ImageCache接口有兩個方法,getBitmap(String url)putBitmap(String url, Bitmap bitmap).這兩個方法足夠簡單直白,他們可以添加任何的緩存實現。

在Volley中添加圖片緩存

對於這個例子,我創建了一個簡單的應用,它從Twitter上搜索提取“CapTech”這個詞的推文,並且把包含這個詞的推文的用戶名和照片顯示在一個ListView中,在你滑動這個列表的時候將自動加載以前的記錄,並根據需要從緩存中拉取圖片。

alt text

例子里有2個可用的緩存實現。一個基於內存的LRU緩存。對於磁盤緩存實現我選擇使用由Jake Wharton寫的DiskLruCache。我只所以選擇這個實現是因為他在Android社區中被經常使用和推薦的並且有一些人試圖去改進它。使用一個基於磁盤的L1緩存有可能導致i/o阻塞的問題。Volley已經內置了一個磁盤L2緩存。磁盤L1緩存包括在內了,由於我原來不知道Volley是如何處理圖片請求緩存的。

在這個例子中主要的組件實現如下:

RequestManager

RequestManager維護了我們的一個RequestQueue的引用。Volley使用RequestQueue不僅處理了我們給Twitter的數據請求,而且也處理了我的的圖片加載。

RequestQueue

這個類雖然跟圖片加載沒有直接的關系,但是它是具有代表性,它是如何繼承VolleyRequest類去處理你的JSON解析。它使用GET請求到Twtter並獲取TwitterData對象。

BitmapLruImageCache

這是一個基於“least recently used(最近最少使用算法,簡稱LRU)”內存緩存實現。它是快速的並且不會引起I/O阻塞的。推薦這種方法。

DiskLruImageCache

DiskLruImageCache是一個DiskLruCachebitmap-centered的包裝實現。它從DiskLruCache中獲取和添加bitmaps,並且處理緩存的實例。一個磁盤緩存或許會引起I/O的阻塞。

ImageCacheManager

ImageCacheManager持有一個我們的ImageCacheVolley ImageLoader的引用。

有一件事情你要注意,在ImageCacheManager中我們使用了字符串URL的hashCode()值作為緩存的Key。這么做是因為在URL中的某些字符不能作為緩存的Key。

BuzzArrayAdapter

這是一個簡單的Adapter。這里唯一要注意的是我們實現了Volley的Listener和ErrListener接口並且將這個 Adapter作為 NetworkImageView’s的setUrl(String string , Listener listener, ErrorListener errorListener) 方法的Listener。這個Adapter還有一點額外的代碼,用來在滾動的時候加載老的推文。

1
2
3
4
5
6
7
8
Tweet tweet = mData.get(position); if(tweet != null){ viewHolder.twitterUserImage.setImageUrl(tweet.getUserImageUrl(),ImageCacheManager.getInstance().getImageLoader());  viewHolder.userNameTextView.setText("@" + tweet.getUsername());  viewHolder.messageTextView.setText(tweet.getMessage());  viewHolder.tweetTimeTextView.setText(formatDisplayDate(tweet.getCreatedDate()));  viewHolder.destinationUrl = tweet.getDestinationUrl(); }

Putting it all together

把這些組件組合在一起,圖片加載和緩存是如此的簡單。在啟動時,在MainApplication這個類中初始化RequestManagerImageCacheManager。在那里你可以定義你想要的L1緩存類型。內存緩存是默認的。

MainActivity中我們調用TwitterManager並且加載我們的的初始數據集。一旦我們接收到響應我們就把這個響應傳遞給一個BuzzArrayAdapter並把這個Adapter設置到我們的ListView上。

正如我們已經在上面看到了BuzzArrayAdapter的代碼,對於NetworkImageView所有繁重的圖片加載操作我們僅僅需要從我們的ImageCacheManager中獲取一個ImageLoader的實例傳遞給它就可以了。

ImageCacheManager會檢查我的LRU緩存實現並且如果這個圖片是可用的就會返回它。如果這個圖片不在在緩存中那么就從網絡獲取它。

當你滾動ListView的時候BuzzArrayAdapter將一起加載額外的推文和圖片,並且重用在緩存中已經存在的圖片。

Closing Thoughts on Volley

雖然Volley是好用的,快速的,很容易實現的;但他也有一些不足的地方:

  • 這個庫沒有任何的文檔和例子。
  • 比如緩存配置組件,他們為什么不做成可配置的。
  • 從以上可以看出,除了一個比較奇怪的基本圖片緩存實現以外,它甚至可能有使用NoImageCache的實現,或者在緩存完全可選的時候,你只是想從網絡上獲取任何東西。

關於Volley在開發者社區中有很多令人激動的事情,並且有很的好的理由。感覺它就像一個庫,它包含了一部分舊的Android API.像在I/O上公布的新的定位API,它是非常純凈的~~~~

Github上的例子源碼

VolleyImageCacheExample

附件:

VolleyImageCacheExample-master.zip

原文作者:

Trey Robinson

原文地址:

http://blogs.captechconsulting.com/blog/raymond-robinson/google-io-2013-volley-image-cache-tutorial

關於本文

前端時間偶然間看到了Volley,最近開始做一個新項目又重新去看了看I/O中關於Volley的介紹,感覺Volley很牛逼,於是就想在新項目中試試Volley,找來找去關於Volley的 資料幾乎沒有,在Google中找到了這篇文章,看了覺得不錯,於是就決定翻譯一下,一來加深自己的理解,二來呢順便補一下自己那慘不忍睹的英語。由於本 人英語水平比較爛,翻譯的時候有可能會曲解原作者的意思,建議英語好的大牛飄過此文去看作者的原文,歡迎大家吐槽和拍磚,覺得譯文中有那些地方我翻譯的不 妥的地方歡迎回復指正,我們相互學習~~~

聲明

轉載須以超鏈接形式標明文章原始出處和作者信息及版權聲明.

 

3. Android開源框架Volley(Google IO 2013)源代碼及內部實現分析

http://my.oschina.net/u/1420982/blog/184209

 

1.Volley概述

在項目開發過程中,博主曾寫過大量的訪問網絡重復代碼,特別是ListView adapter很難避免getView()方法不被重復調用,如果ImageView不利用緩存機制,那么網絡的負荷就會更大!曾將訪問網絡代碼和緩存封 裝起來使用,但是中間仍存在不少瑕疵!今年的Google I/O 2013上,Volley發布了!Volley是Android平台上的網絡通信庫,能使網絡通信更快,更簡單,更健壯

SouthEast.jpg (145.72 KB, 下載次數: 0)

下載附件  保存到相冊

昨天 16:24 上傳

 

Volley特別適合數據量不大但是通信頻繁的場景,現在android提供的源碼已經包含Volley,以后在項目中,可以根據需求引入Volley jar文件!

2.Volley源碼分析 (1).Volley.java Volley.newRequestQueue()方法在一個app最好執行一次,可以使用單例設計模式或者在application完成初始化,具體原因請查看代碼分析

  1. /**
  2. * @author zimo2013
  3. * [url=home.php?mod=space&uid=189949]@See[/url] http://blog.csdn.net/zimo2013
  4. */
  5. public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
  6.     File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

  7.     String userAgent = "volley/0";
  8.     try {
  9.         String packageName = context.getPackageName();
  10.         PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
  11.         userAgent = packageName + "/" + info.versionCode;
  12.     } catch (NameNotFoundException e) {
  13.     }

  14.     if (stack == null) {
  15.         if (Build.VERSION.SDK_INT >= 9) {
  16.             stack = new HurlStack();
  17.         } else {
  18.             stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
  19.         }
  20.     }

  21.     Network network = new BasicNetwork(stack);

  22.     //cacheDir 緩存路徑 /data/data/<pkg name>/cache/<name>
  23.     RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
  24.     queue.start();
  25.     /*
  26.      * 實例化一個RequestQueue,其中start()主要完成相關工作線程的開啟,
  27.      * 比如開啟緩存線程CacheDispatcher先完成緩存文件的掃描, 還包括開啟多個NetworkDispatcher訪問網絡線程,
  28.      * 該多個網絡線程將從 同一個 網絡阻塞隊列中讀取消息
  29.      *
  30.      * 此處可見,start()已經開啟,所有我們不用手動的去調用該方法,在start()方法中如果存在工作線程應該首先終止,並重新實例化工作線程並開啟
  31.      * 在訪問網絡很頻繁,而又重復調用start(),勢必會導致性能的消耗;但是如果在訪問網絡很少時,調用stop()方法,停止多個線程,然后調用start(),反而又可以提高性能,具體可折中選擇
  32.      */

  33.     return queue;
  34. }
復制代碼


(2).RequestQueue.java

  1. /**
  2. * RequestQueue類存在2個非常重要的PriorityBlockingQueue類型的成員字段mCacheQueue mNetworkQueue ,該PriorityBlockingQueue為java1.5並發庫提供的新類
  3. * 其中有幾個重要的方法,比如take()為從隊列中取得對象,如果隊列不存在對象,將會被阻塞,直到隊列中存在有對象,類似於Looper.loop()
  4. *
  5. * 實例化一個request對象,調用RequestQueue.add(request),該request如果不允許被緩存,將會被添加至mNetworkQueue隊列中,待多個NetworkDispatcher線程take()取出對象
  6. * 如果該request可以被緩存,該request將會被添加至mCacheQueue隊列中,待mCacheDispatcher線程從mCacheQueue.take()取出對象,
  7. * 如果該request在mCache中不存在匹配的緩存時,該request將會被移交添加至mNetworkQueue隊列中,待網絡訪問完成后,將關鍵頭信息添加至mCache緩存中去!
  8. *
  9. * @author zimo2013
  10. * @see http://blog.csdn.net/zimo2013
  11. */
  12. public void start() {
  13.     stop();
  14.    
  15.     mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
  16.     mCacheDispatcher.start();

  17.     // Create network dispatchers (and corresponding threads) up to the pool size.
  18.     for (int i = 0; i < mDispatchers.length; i++) {
  19.         NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,
  20.                 mCache, mDelivery);
  21.         mDispatchers[i] = networkDispatcher;
  22.         networkDispatcher.start();
  23.     }
  24. }
復制代碼


(3).CacheDispatcher.java

  1. /**
  2. * @author zimo2013
  3. * @see http://blog.csdn.net/zimo2013
  4. */
  5. @Override
  6. public void run() {
  7.     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

  8.     //緩存初始化,會遍歷整個緩存文件夾
  9.     mCache.initialize();
  10.     {
  11.             //執行代碼
  12.             /*if (!mRootDirectory.exists()) {
  13.             if (!mRootDirectory.mkdirs()) {
  14.                 VolleyLog.e("Unable to create cache dir %s", mRootDirectory.getAbsolutePath());
  15.             }
  16.             return;
  17.         }

  18.         File[] files = mRootDirectory.listFiles();
  19.         if (files == null) {
  20.             return;
  21.         }
  22.         for (File file : files) {
  23.             FileInputStream fis = null;
  24.             try {
  25.                 fis = new FileInputStream(file);
  26.                 CacheHeader entry = CacheHeader.readHeader(fis);
  27.                 entry.size = file.length();
  28.                 putEntry(entry.key, entry);
  29.             } catch (IOException e) {
  30.                 if (file != null) {
  31.                    file.delete();
  32.                 }
  33.             } finally {
  34.                 try {
  35.                     if (fis != null) {
  36.                         fis.close();
  37.                     }
  38.                 } catch (IOException ignored) { }
  39.             }
  40.         }*/
  41.     }

  42.     while (true) {
  43.         try {
  44.                 //該方法可能會被阻塞
  45.             final Request request = mCacheQueue.take();

  46.             Cache.Entry entry = mCache.get(request.getCacheKey());
  47.             if (entry == null) {
  48.                     //緩存不存在,則將該request添加至網絡隊列中
  49.                 mNetworkQueue.put(request);
  50.                 continue;
  51.             }

  52.             //是否已經過期
  53.             if (entry.isExpired()) {
  54.                 request.setCacheEntry(entry);
  55.                 mNetworkQueue.put(request);
  56.                 continue;
  57.             }

  58.             Response<?> response = request.parseNetworkResponse(
  59.                     new NetworkResponse(entry.data, entry.responseHeaders));

  60.             //存在緩存,執行相關操作

  61.         } catch (InterruptedException e) {
  62.         }
  63.     }
  64. }
復制代碼


(4).NetworkDispatcher.java

  1. /**
  2. * @author zimo2013
  3. * @see http://blog.csdn.net/zimo2013
  4. */
  5. @Override
  6. public void run() {
  7.     Request request;
  8.     while (true) {
  9.         try {
  10.                 //可能會被
  11.             request = mQueue.take();
  12.         } catch (InterruptedException e) {
  13.             // We may have been interrupted because it was time to quit.
  14.             if (mQuit) {
  15.                 return;
  16.             }
  17.             continue;
  18.         }

  19.         try {
  20.                
  21.                 //訪問網絡,得到數據
  22.             NetworkResponse networkResponse = mNetwork.performRequest(request);

  23.             if (networkResponse.notModified && request.hasHadResponseDelivered()) {
  24.                 request.finish("not-modified");
  25.                 continue;
  26.             }

  27.             // Parse the response here on the worker thread.
  28.             Response<?> response = request.parseNetworkResponse(networkResponse);

  29.             // 寫入緩存
  30.             if (request.shouldCache() && response.cacheEntry != null) {
  31.                 mCache.put(request.getCacheKey(), response.cacheEntry);
  32.                 request.addMarker("network-cache-written");
  33.             }

  34.             // Post the response back.
  35.             request.markDelivered();
  36.             mDelivery.postResponse(request, response);
  37.         } catch (VolleyError volleyError) {
  38.             parseAndDeliverNetworkError(request, volleyError);
  39.         } catch (Exception e) {
  40.             VolleyLog.e(e, "Unhandled exception %s", e.toString());
  41.             mDelivery.postError(request, new VolleyError(e));
  42.         }
  43.     }
  44. }
復制代碼


(5).StringRequest.java

其中在parseNetworkResponse()中,完成將byte[]到String的轉化,可能會出現字符亂 碼,HttpHeaderParser.parseCharset(response.headers)方法在尚未指定是返回為ISO-8859-1,可 以修改為 utf-8
  1. public class StringRequest extends Request<String> {
  2.     private final Listener<String> mListener;

  3.     /**
  4.      * Creates a new request with the given method.
  5.      *
  6.      * @param method the request {@link Method} to use
  7.      * @param url URL to fetch the string at
  8.      * @param listener Listener to receive the String response
  9.      * @param errorListener Error listener, or null to ignore errors
  10.      */
  11.     public StringRequest(int method, String url, Listener<String> listener,
  12.             ErrorListener errorListener) {
  13.         super(method, url, errorListener);
  14.         mListener = listener;
  15.     }

  16.     public StringRequest(String url, Listener<String> listener, ErrorListener errorListener) {
  17.         this(Method.GET, url, listener, errorListener);
  18.     }

  19.     @Override
  20.     protected void deliverResponse(String response) {
  21.         mListener.onResponse(response);
  22.     }

  23.     @Override
  24.     protected Response<String> parseNetworkResponse(NetworkResponse response) {
  25.         String parsed;
  26.         try {
  27.                 //將data字節數據轉化為String對象
  28.             parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
  29.         } catch (UnsupportedEncodingException e) {
  30.             parsed = new String(response.data);
  31.         }
  32.         //返回Response對象,其中該對象包含訪問相關數據
  33.         return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
  34.     }
  35. }
復制代碼


(6).ImageLoader.java

  1. /**
  2. * @author zimo2013
  3. * @see http://blog.csdn.net/zimo2013
  4. */
  5. public ImageContainer get(String requestUrl, ImageListener imageListener,
  6.         int maxWidth, int maxHeight) {
  7.     throwIfNotOnMainThread();
  8.     final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight);

  9.     //從mCache得到bitmap對象,因此可以覆寫ImageCache,完成圖片的三級緩存,即在原有的LruCache添加一個軟引用緩存
  10.     Bitmap cachedBitmap = mCache.getBitmap(cacheKey);
  11.     if (cachedBitmap != null) {
  12.             //得到緩存對象
  13.         ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, null, null);
  14.         imageListener.onResponse(container, true);
  15.         return container;
  16.     }

  17.     ImageContainer imageContainer =
  18.             new ImageContainer(null, requestUrl, cacheKey, imageListener);

  19.     // 首先更新該view,其指定了defaultImage
  20.     imageListener.onResponse(imageContainer, true);

  21.     // 根據可以去檢查該請求是否已經發起過
  22.     BatchedImageRequest request = mInFlightRequests.get(cacheKey);
  23.     if (request != null) {
  24.         request.addContainer(imageContainer);
  25.         return imageContainer;
  26.     }

  27.     Request<?> newRequest =
  28.         new ImageRequest(requestUrl, new Listener<Bitmap>() {
  29.             @Override
  30.             public void onResponse(Bitmap response) {
  31.                     //如果請求成功
  32.                 onGetImageSuccess(cacheKey, response);
  33.             }
  34.         }, maxWidth, maxHeight,
  35.         Config.RGB_565, new ErrorListener() {
  36.             @Override
  37.             public void onErrorResponse(VolleyError error) {
  38.                 onGetImageError(cacheKey, error);
  39.             }
  40.         });
  41.     //添加至請求隊列中
  42.     mRequestQueue.add(newRequest);
  43.     //同一添加進map集合,以方便檢查該request是否正在請求網絡,可以節約資源
  44.     mInFlightRequests.put(cacheKey, new BatchedImageRequest(newRequest, imageContainer));
  45.     return imageContainer;
  46. }
復制代碼
  1. private void onGetImageSuccess(String cacheKey, Bitmap response) {
  2.         //緩存對象
  3.     mCache.putBitmap(cacheKey, response);

  4.     // 請求完成,不需要檢測
  5.     BatchedImageRequest request = mInFlightRequests.remove(cacheKey);

  6.     if (request != null) {
  7.         request.mResponseBitmap = response;
  8.         //處理結果
  9.         batchResponse(cacheKey, request);
  10.     }
  11. }
復制代碼
  1. private void batchResponse(String cacheKey, BatchedImageRequest request) {
  2.     mBatchedResponses.put(cacheKey, request);
  3.     //通過handler,發送一個操作
  4.     if (mRunnable == null) {
  5.         mRunnable = new Runnable() {
  6.             @Override
  7.             public void run() {
  8.                 for (BatchedImageRequest bir : mBatchedResponses.values()) {
  9.                     for (ImageContainer container : bir.mContainers) {
  10.                         if (container.mListener == null) {
  11.                             continue;
  12.                         }
  13.                         if (bir.getError() == null) {
  14.                             container.mBitmap = bir.mResponseBitmap;
  15.                             //更新結果
  16.                             container.mListener.onResponse(container, false);
  17.                         } else {
  18.                             container.mListener.onErrorResponse(bir.getError());
  19.                         }
  20.                     }
  21.                 }
  22.                 mBatchedResponses.clear();
  23.                 mRunnable = null;
  24.             }

  25.         };
  26.         // mHandler對應的looper是MainLooper,因此被MainLooper.loop()得到該message,故該runnable操作在主線程中執行,
  27.         mHandler.postDelayed(mRunnable, mBatchResponseDelayMs);
  28.     }
  29. }
復制代碼


3.總結

SouthEast.jpg (187.99 KB, 下載次數: 0)

下載附件  保存到相冊

昨天 16:24 上傳

 

RequestQueue類存在2個非常重要的PriorityBlockingQueue類型的成員字段mCacheQueue mNetworkQueue ,該PriorityBlockingQueue為java1.5並發庫提供的!其中有幾個重要的方法,比如take()為從隊列中取得對象,如果隊列不 存在對象,將會被阻塞,直到隊列中存在有對象,類似於Looper.loop()。實例化一個request對象,調用 RequestQueue.add(request),該request如果不允許被緩存,將會被添加至mNetworkQueue隊列中,待多個 NetworkDispatcher線程從mNetworkQueue中take()取出對象。如果該request可以被緩存,該request將會被 添加至mCacheQueue隊列中,待mCacheDispatcher線程從mCacheQueue.take()取出對象,如果該request在 mCache中不存在匹配的緩存時,該request將會被移交添加至mNetworkQueue隊列中,待網絡訪問完成后,將關鍵頭信息添加至 mCache緩存中去,並通過ResponseDelivery主線程調用request的相關方法!Volley實例


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM