---
title: "Android基于volley的快速开发基类"
author: "喧嚣求静"
date: "2015-08-29T10:02:57Z"
tags: []
categories: ["移动开发"]
slug: "android-volley"
draft: false
lastmod: "2015-08-29T10:02:57Z"
id: 2238847
url: "https://913.iteye.com/blog/2238847"
---

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);
		}
	}
 
```

 

# [Android基于volley的快速开发基类《二》](http://www.apk-doc.net/android/android%E5%9F%BA%E4%BA%8Evolley%E7%9A%84%E5%BF%AB%E9%80%9F%E5%BC%80%E5%8F%91%E5%9F%BA%E7%B1%BB%E3%80%8A%E4%BA%8C%E3%80%8B.html)