Android基于volley的快速开发基类

本文介绍如何对Volley框架进行封装以实现更简洁高效的网络请求处理。通过自定义回调接口和扩展请求方法,实现了任务ID跟踪及结果统一处理,提高了项目的可维护性和扩展性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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的快速开发基类《二》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值