package com.android.volley.control; import android.content.Context; import android.text.TextUtils; import com.android.volley.Cache; import com.android.volley.Cache.Entry; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; import com.android.volley.VolleyError; import com.android.volley.core.VolleyConfiguration; import com.android.volley.json.JsonConvertFactory; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.io.UnsupportedEncodingException; /** * volley版本:1.0.15 2015.03.18 * volley管理类,带5MB缓存,不使用volley的imageloader(Description) Google官网推荐使用 volley提供的功能: * 1、json、图片(异步) 2、网络请求的排序 3、网络请求的优先级处理 4、缓存 5、多级别的取消请求 6、与activity生命周期联动 * <p> * 关于缓存的问题,如果http请求数据的时候,如果被请求的页面如果带有 Cache-Control: cache-directive * response.setHeader("Cache-Control","no-cache"); * response.setHeader("Cache-Control","no-store"); 这样的标签的话,那么这个请求是不能够缓存到本地的。 */ public class VolleyHelper { private volatile static VolleyHelper mInstance; private RequestQueue mRequestQueue; private VolleyConfiguration mConfiguration; // 这两个变量不能保存到单例里面,在当activity销毁的时候,request 和 // mAction的实例都会保存在里面,不能够销毁,会造成系统的内存泄露 // private StringRequest request; // private IHelperAction mAction; private VolleyHelper() { } // @Deprecated // private VolleyHelper(Context context) { // mContext = context; // mRequestQueue = getRequestQueue(); // } public static VolleyHelper getInstance() { if (mInstance == null) { synchronized (VolleyHelper.class) { if (mInstance == null) { mInstance = new VolleyHelper(); } } } return mInstance; } // @Deprecated // public static VolleyHelper getInstance(Context context) { // if (mInstance == null) { // synchronized (VolleyHelper.class) { // if (mInstance == null) { // mInstance = new VolleyHelper(context); // } // } // } // return mInstance; // // } public synchronized void init(Context context) { if (context == null) { throw new RuntimeException("context is null!~~"); } mConfiguration = new VolleyConfiguration.Builder(context).build(); mRequestQueue = getRequestQueue(); } public synchronized void init(VolleyConfiguration configuration) { if (configuration == null) { throw new RuntimeException("configuration is null!~~"); } this.mConfiguration = configuration; mRequestQueue = getRequestQueue(); } /** * 创建一个queue * * @return */ public RequestQueue getRequestQueue() { if (mRequestQueue == null) { L.d("mRequestQueue onCreate......."); mRequestQueue = Volley.newRequestQueue(mConfiguration.httpStack, mConfiguration.cachePath,mConfiguration.cacheSize); } return mRequestQueue; } public <T> void addToRequestQueue(Request<T> req) { getRequestQueue().add(req); } /** * 加载数据 * * @param method 请求方式 * @param action 动作受体 * @param urlString 访问地址 * @param netWorkNum 访问序号 * @return */ public StringRequest loadData(int method, final IHelperAction action, final String urlString, final int netWorkNum) { L.d("url is : " + urlString); // mAction = action; final StringRequest request = new StringRequest(method, urlString, new Listener<String>() { @Override public void onResponse(String response) { L.d("Loading data is succeed , data is :" + response); action.onDataLoaded(true, response, netWorkNum, null); } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { L.e(error); if (VolleyConfiguration.hasNoHttpConnectCache) { String cache = getCache(error.url);// action.onDataLoaded(!TextUtils.isEmpty(cache), cache, netWorkNum, error); } else { action.onDataLoaded(false, null, netWorkNum, error); } } }); request.setTag(urlString); action.setLoadParams(request, netWorkNum); addToRequestQueue(request); return request; } /** * 加载数据,解析json,返回对象 * * @param method 请求方式 * @param action 动作受体 * @param urlString 请求路径 * @param cls 对象 * @param netWorkNum 访问网络序号 * @param <T> 泛型对象 * @return */ public <T> JsonConvertRequest loadData(int method, final IHelperAction action, final String urlString, final Class<T> cls, final int netWorkNum) { L.d("url is : " + urlString); JsonConvertRequest<T> request = new JsonConvertRequest<T>(method, urlString, cls, new Response.Listener<T>() { @Override public void onResponse(T response) { L.d("Loading data is succeed , data is :" + response.toString()); action.onDataLoaded(true, response, netWorkNum, null); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { L.e(error); if (VolleyConfiguration.hasNoHttpConnectCache) { String cache = getCache(error.url); boolean isHaveCache = false; T response = null; if (!TextUtils.isEmpty(cache)) { isHaveCache = true; try { response = mConfiguration.jsonConvertFactory.fromJson(cache, cls); } catch (Exception e) { L.e(e); isHaveCache = false; //action.onDataLoaded(false, null, netWorkNum, error); } } action.onDataLoaded(isHaveCache, response, netWorkNum, error); } else { action.onDataLoaded(false, null, netWorkNum, error); } } }); request.setTag(urlString); request.setJsonConvertFactory(mConfiguration.jsonConvertFactory); action.setLoadParams(request, netWorkNum); addToRequestQueue(request); return request; } /** * 获得缓存 * * @param urlString * @return */ public String getCache(String urlString) { Cache cache = getRequestQueue().getCache(); Entry entry = cache.get(urlString); if (entry != null) { try { String data = new String(entry.data, "UTF-8"); L.d("have Data in the cache "); if (data.equals("[]")) { return ""; } return data; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { L.d("no Data in the cache"); } return ""; } /** * Deleting cache for particular URL * * @param urlString */ public void removeCache(String urlString) { getRequestQueue().getCache().remove(urlString); } /** * Deleting all the cache */ public void clearCache() { getRequestQueue().getCache().clear(); } /** * cancel request 如果现在的Set<Request<?>> mCurrentRequests = new * HashSet<Request<?>>();里面有的话就删除 */ public void cancel(String string) { getRequestQueue().cancelAll(string); } /** * 获得jsonConvertFactory */ public JsonConvertFactory getJsonConvertFactory() { return mConfiguration.jsonConvertFactory; } }