編輯:關於 Android 程式設計
以前做 API 連線,GET、POST 這些操作大多直接靠 Android 內建的類別硬寫,程式碼又長又不好維護。後來想著換一套好用的 library,應該能事半功倍,於是挑了三套社群討論度比較高的方案來評估:
專案網址:https://github.com/mcxiaoke/android-volley
Volley 內建了 JsonObjectRequest 與 JsonArrayRequest,分別負責 JSON 物件與 JSON 陣列類型的請求。值得一提的是,Volley 並沒有提供基於 Gson 的 GsonRequest(也就是發出一個 request、直接拿到一個 Java 物件),不過這部分我們可以自己動手包裝。
建立物件請求的寫法相當直觀:new 一個 Request 物件、實作回呼介面,再把請求丟進請求佇列即可,陣列請求也是同樣套路。
// Tag used to cancel the request String tag_json_obj = "json_obj_req"; String url = "https://api.androidhive.info/volley/person_object.json"; JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); } }); // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj); StringRequest 幾乎什麼都能抓:JSON、XML、純文字都適用,泛用性最高。
// Tag used to cancel the request String tag_string_req = "string_req"; String url = "https://api.androidhive.info/volley/string_response.html"; ProgressDialog pDialog = new ProgressDialog(this); pDialog.setMessage("Loading..."); pDialog.show(); StringRequest strReq = new StringRequest(Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, response.toString()); pDialog.hide(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); pDialog.hide(); } }); // Adding request to request queue AppController.getInstance().addToRequestQueue(strReq, tag_string_req); 前面示範的都是 GET,POST 的差别其實只有兩處:把請求方法改成 POST,然後覆寫 getParams() 把參數帶上去。
// Tag used to cancel the request String tag_json_obj = "json_obj_req"; String url = "https://api.androidhive.info/volley/person_object.json"; ProgressDialog pDialog = new ProgressDialog(this); pDialog.setMessage("Loading..."); pDialog.show(); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); pDialog.hide(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); pDialog.hide(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("name", "Androidhive"); params.put("email", "abc@androidhive.info"); params.put("password", "password123"); return params; } }; // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj); 需要帶 token、apiKey 或指定 Content-Type 時,覆寫 getHeaders() 就好。
// Tag used to cancel the request String tag_json_obj = "json_obj_req"; String url = "https://api.androidhive.info/volley/person_object.json"; ProgressDialog pDialog = new ProgressDialog(this); pDialog.setMessage("Loading..."); pDialog.show(); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,url, null,new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); pDialog.hide(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); pDialog.hide(); } }) { /** * Passing some request headers * */ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); headers.put("apiKey", "xxxxxxxxxxxxxxx"); return headers; } }; // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj); Volley 附了一個 NetworkImageView,可以直接用它來抓圖,省下不少工。
先講原理:NetworkImageView 只需要一個 ImageLoader 和一個圖片網址,而 ImageLoader 又依賴一組請求佇列與一個 ImageCache。呼叫 setImageUrl() 之後,它會先比對目前 ImageView 上的網址跟新傳進來的網址是否相同;相同就不重送請求,不同才透過 ImageLoader 發出 HTTP 連線。
ImageLoader imageLoader = AppController.getInstance().getImageLoader(); // If you are using NetworkImageView imgNetWorkView.setImageUrl(Const.URL_IMAGE, imageLoader);
做法與上面類似,只是改成透過 ImageLoader 的 get() 回呼取得 Bitmap。
ImageLoader imageLoader = AppController.getInstance().getImageLoader(); // If you are using normal ImageView imageLoader.get(Const.URL_IMAGE, new ImageListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Image Load Error: " + error.getMessage()); } @Override public void onResponse(ImageContainer response, boolean arg1) { if (response.getBitmap() != null) { // load image into imageview imageView.setImageBitmap(response.getBitmap()); } } }); 想再偷懶一點,可以直接用現成的 listener,順便把佔位圖與錯誤圖一起指定:
// Loading image with placeholder and error image imageLoader.get(Const.URL_IMAGE, ImageLoader.getImageListener(imageView, R.drawable.ico_loading, R.drawable.ico_error));
Volley 內建了一套相當完整的 cache 機制來管理請求結果,能有效減少網路往返次數,也縮短使用者等待的時間。要直接從快取把資料取出來:
Cache cache = AppController.getInstance().getRequestQueue().getCache(); Entry entry = cache.get(url); if(entry != null){ try { String data = new String(entry.data, "UTF-8"); // handle data, like converting it to xml, json, bitmap etc., } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }else{ // Cached response doesn't exists. Make network call here } 讓快取失效:這裡的「失效」並不是刪除,Volley 仍會沿用舊的快取內容,直到伺服器回來的新資料把它覆蓋為止。
AppController.getInstance().getRequestQueue().getCache().invalidate(url, true);
關閉單一請求的快取:直接對該 Request 呼叫 setShouldCache(false)。
// String request StringRequest stringReq = new StringRequest(....); // disable cache stringReq.setShouldCache(false);
刪除指定網址的快取:
AppController.getInstance().getRequestQueue().getCache().remove(url);
清空所有快取:
AppController.getInstance().getRequestQueue().getCache().clear();
addToRequestQueue(request, tag) 的第二個參數就是標記用的 tag。替同一類請求打上同一個 tag,之後就能一次全部取消,例如離開頁面時清掉殘留的請求。
String tag_json_arry = "json_req"; ApplicationController.getInstance().getRequestQueue().cancelAll("feed_request"); 覆寫 getPriority() 即可指定優先順序,共有 Normal、Low、Immediate、High 四種。
private Priority priority = Priority.HIGH; StringRequest strReq = new StringRequest(Method.GET, Const.URL_STRING_REQ, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, response.toString()); msgResponse.setText(response.toString()); hideProgressDialog(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); hideProgressDialog(); } }) { @Override public Priority getPriority() { return priority; } };
Android Studio 搭配 Git 與 GitHub 管理專案的完整設定
轉載請註明出處:https://shenshanlaoyuan.com 以下流程以 Windows 為主,Mac 的使用者概念相同,只是路徑與安裝方式不同。 一、安裝本機
Android 基礎控件 Day22:CheckBox、Radio 與 Spinner 實戰
這一篇把三個「選擇類」控件放在一起講:多選的 CheckBox、單選的 RadioButton,以及下拉列表 Spinner。它們看起來簡單,但真正做出好看的交互,關鍵往
魅藍E與紅米Pro全面對比 誰更值得入手
隨著魅藍E正式發表,魅族與小米在千元機市場的對決再度升溫。不少網友拿它和前不久登場的紅米Pro做對比,那麼魅藍E和紅米Pro到底哪個更好?下面我們就從各個面向詳細比一比。
Android Async-Http 使用指南:GET、POST 與 JSON 回調
簡介 Async-Http 是一款國外開源框架,作者為 loopj,基於 Apache HttpClient 庫封裝。它能方便、高效地完成網絡數據請求、文件下載與上傳,最