在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 <P>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(); } } }
[Java]代码
//调用方法: 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); } });