
如何实现?
1.使用Volley访问网络接口
/*** 获取网络数据*/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);}当接口访问成功以后,Volley会自动缓存此次纪录在/data/data/{package name}/cache/volley文件夹中。
打开上面的文件,可以发现接口的路径和返回值都被保存在该文件里面了。
当在断网状态时,如何获取到该接口的缓存的返回值呢?
使用RequestQueue提供的getCache()方法查询该接口的缓存数据
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);注意点