Android简单封装类似JQuery异步请求代码

http://www.wuphone.com/3737

http://caiwb1990.iteye.com/blog/1478276

android开发中经常会使用异步请求数据,通常会使用handler或者AsyncTask去做,handler 配合message 使用起来比较麻烦,AsyncTask 线程池只允许128个线程工作,会有溢出的问题,(当然一般情况不会有那么多线程同时工作的)所以写了这个代码,还望高手指正!

package com.xbl.task;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class JQuery {

	private static final String KEY = "key";
	private static String TAG = "JQuery";
	private static final int N = 5;// 5个工人
	private static final Executor worker = Executors.newFixedThreadPool(N);// 线程池
	private static final Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			TaskListener listener = (TaskListener)msg.obj;
			Object result = msg.getData();
			if(listener !=null ){
				listener.callBack(result);
			}
			destory();
		}
	};

	private JQuery(){
	}

	public static void execute(final String url,final TaskListener listener){
		worker.execute(new Runnable() {
			@Override
			public void run() {
				String result = null;
				try {
					result = WebUtil.get(url);
				} catch (Exception e) {
					Log.e(TAG, e.getMessage());
				}

				Message msg = new Message();
				Bundle data = new Bundle();
				data.putSerializable(KEY, result);
				msg.setData(data);
				msg.obj = listener;
				handler.sendMessage(msg);
			}
		});
	}

	//销毁线程
	private static void destory() {
		if (worker != null && worker instanceof ExecutorService) {
			ExecutorService es = (ExecutorService) worker;
			if (!es.isShutdown()) {
				es.shutdown();
			}
		}
	}	

	public interface TaskListener{
		public void callBack(Object result);
	}
	/**
	 *
	 * 不必太在意此处代码,只是示例
	 *
	 */
	public static class WebUtil{

		public static String get(String url) throws Exception{
			InputStream inputStream = new URL(url).openStream();
			StringBuilder strBuilder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
			for (String s = reader.readLine(); s != null; s = reader.readLine())
				strBuilder.append(s);

			inputStream.close();
			return strBuilder.toString();
		}
	}
}

//调用方法:
JQuery.execute("http://weather.news.qq.com/inc/minisite_125.js", new JQuery.TaskListener() {
				@Override
				public void callBack(Object result) {
					TextView t = new TextView(TaskDemoActivity.this);
					t.setText(String.valueOf(result));
					LinearLayout layout = (LinearLayout)findViewById(R.id.layout1);
					layout.addView(t);
				}
			});


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值