Volley框架至2013面试以来,已经普及了很多android项目,在实际项目开发中,我们总想扩展为一个公用的类,在项目中简洁,方便的使用,尽量做到低耦合,高内聚。
Volley由一个请求队列维护网络请求的执行,结果会回调两个响应接口,一个成功,一个失败,在基于这种模式下,我们自己人为封装了一层回调,这样就可以做到更方便,上代码
/**
* 初始Volley
*
* @param context
*/
public static void init(Context context) {
//mQueue = Volley.newRequestQueue(context,new HttpClientStack(httpclient));
mQueue = Volley.newRequestQueue(context.getApplicationContext());
}
private static RequestQueue getQueue() {
synchronized (VolleyUtils.class) {
if (mQueue == null) {
throw new RuntimeException("Please init VolleyUtils in your Application");
}
return mQueue;
}
}
自己扩展的一个内部接口,主要是实现自己的结果封装分发
public interface ResultWatcher {
void onStartRequest(int taskId);
void onStopRequest(int taskId);
void onResopnse(int taskId, String response);
void onErrorResponse(int taskId, String errorMsg);
}
结合接口,进行构造的方法
public static void doPostStringRequest(Context context, String url, final Map<String, String> params,
final ResultWatcher watcher, final int taskId) {
StringRequest request = newPostStringRequest(url, params, watcher, taskId);
request.setSequence(taskId);
request.setTag(context);
sendRequest(context, request);
EasyAndApp.getApp().logger.d(TAG,
"[ REQ taskid=" + taskId + "] post method,params\n " + CollectionUtils.transMapToString(params));
if (watcher != null) {
watcher.onStartRequest(taskId);
}
}