感觉老师这个二次封装有些复杂,下面是我做的简化版本。
public abstract class VolleyListener { public abstract void onSuccess(String result); public abstract void onError(VolleyError error); public Response.Listener<String> loadingListener(){ Response.Listener<String> listener = new Response.Listener<String>() { @Override public void onResponse(String response) { onSuccess(response); } }; return listener; } public Response.ErrorListener getErrorListener(){ Response.ErrorListener errorListener = new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError error) { onError(error); } }; return errorListener; } }
Request封装
public class VolleyRequest { private static StringRequest stringRequest; //有全局RequestQueue的GET请求 public static void requestGlobalGET(String url,String tag,VolleyListener listener){ BaseApplication.getRequestQueue().cancelAll(tag); stringRequest = new StringRequest(Request.Method.GET,url,listener.loadingListener(),listener.getErrorListener()); stringRequest.setTag(tag); BaseApplication.getRequestQueue().add(stringRequest); } //有全局RequestQueue的POST请求 public static void requestGlobalPOST(String url,String tag,VolleyListener listener){ BaseApplication.getRequestQueue().cancelAll(tag); stringRequest = new StringRequest(Request.Method.POST,url,listener.loadingListener(),listener.getErrorListener()); stringRequest.setTag(tag); BaseApplication.getRequestQueue().add(stringRequest); } //无全局RequestQueue的GET请求 public static void requestGET(Context context,String url,String tag,VolleyListener listener){ RequestQueue queue = Volley.newRequestQueue(context); stringRequest = new StringRequest(Request.Method.GET,url,listener.loadingListener(),listener.getErrorListener()); stringRequest.setTag(tag); queue.add(stringRequest); } //无全局RequestQueue的GET请求 public static void requestPOST(Context context,String url,String tag,VolleyListener listener){ RequestQueue queue = Volley.newRequestQueue(context); stringRequest = new StringRequest(Request.Method.POST,url,listener.loadingListener(),listener.getErrorListener()); stringRequest.setTag(tag); queue.add(stringRequest); } }
调用
//有全局requestqueue无需加this,否则要加上下文 VolleyRequest.requestGET(this,"http://www.baidu.com","get",new VolleyListener() { @Override public void onSuccess(String result) { Log.i("TAG", result); } @Override public void onError(VolleyError error) { Log.i("TAG", error.getMessage()); } });