離線緩存就是在網(wǎng)絡(luò)暢通的情況下將從服務(wù)器收到的數(shù)據(jù)保存到本地,當(dāng)網(wǎng)絡(luò)斷開之后直接讀取本地文件中的數(shù)據(jù)。如Json 數(shù)據(jù)緩存到本地,在斷網(wǎng)的狀態(tài)下啟動(dòng)APP時(shí)讀取本地緩存數(shù)據(jù)顯示在界面上,常用的APP(網(wǎng)易新聞、知乎等等)都是支持離線緩存的,這樣帶來了更好的用戶體驗(yàn)。
如果能夠在調(diào)用網(wǎng)絡(luò)接口后自動(dòng)緩存返回的Json數(shù)據(jù),下次在斷網(wǎng)狀態(tài)下調(diào)用這個(gè)接口獲取到緩存的Json數(shù)據(jù)的話,那該多好呢?Volley做到了這一點(diǎn)。
因此,今天這篇文章介紹的就是使用Volley自帶的數(shù)據(jù)緩存,配合Universal-ImageLoader的圖片緩存,實(shí)現(xiàn)斷網(wǎng)狀態(tài)下的圖文顯示。
實(shí)現(xiàn)效果

如何實(shí)現(xiàn)?
1.使用Volley訪問網(wǎng)絡(luò)接口
/*** 獲取網(wǎng)絡(luò)數(shù)據(jù)*/private void getData() {StringRequest stringRequest = new StringRequest(Request.Method.POST, TEST_API, new Response.Listener<String>() {@Overridepublic void onResponse(String s) {textView.setText("data from Internet: " + s);try {JSONObject jsonObject = new JSONObject(s);JSONArray resultList = jsonObject.getJSONArray("resultList");JSONObject JSONObject = (org.json.JSONObject) resultList.opt(0);String head_img = JSONObject.getString("head_img");ImageLoader.getInstance().displayImage(head_img, imageView);} catch (JSONException e) {e.printStackTrace();}}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError volleyError) {}}) {@Overrideprotected Map<String, String> getParams() throws AuthFailureError {Map<String, String> map = new HashMap<String, String>();map.put("phone", "15962203803");map.put("password", "123456");return map;}};queue.add(stringRequest);}當(dāng)接口訪問成功以后,Volley會(huì)自動(dòng)緩存此次紀(jì)錄在/data/data/{package name}/cache/volley文件夾中。
 
打開上面的文件,可以發(fā)現(xiàn)接口的路徑和返回值都被保存在該文件里面了。
 
當(dāng)在斷網(wǎng)狀態(tài)時(shí),如何獲取到該接口的緩存的返回值呢? 
使用RequestQueue提供的getCache()方法查詢?cè)摻涌诘木彺鏀?shù)據(jù)
if (queue.getCache().get(TEST_API) != null) {String cachedResponse = new String(queue.getCache().get(TEST_API).data);2.使用Universal-ImageLoader加載圖片
ImageLoader.getInstance().displayImage(head_img, imageView);
注意點(diǎn)
1.觀察上面的緩存文件可以發(fā)現(xiàn),Volley只緩存了接口路徑,并沒有緩存接口的傳入?yún)?shù),因此如果做分頁查詢的話,使用此方法是不妥的。 
2.在測(cè)試過程中,依然發(fā)現(xiàn)有的時(shí)候獲取不到緩存數(shù)據(jù),有的時(shí)候卻可以獲取到。對(duì)獲取緩存的代碼延遲加載能夠有效解決這個(gè)問題。 
3.如果考慮到緩存的過期策略,可以使用更好的ASimpleCache框架輔助開發(fā)。對(duì)緩存有更高要求的APP,依然應(yīng)該使用文件緩存或數(shù)據(jù)庫緩存。
以上內(nèi)容是小編給大家介紹的Android實(shí)現(xiàn)離線緩存的方法,希望對(duì)大家有所幫助!
新聞熱點(diǎn)
疑難解答
圖片精選