標籤:android des style blog class code
在android開發中經常會使用非同步請求資料,通常會使用handler或者AsyncTask去做,handler 配合message 使用起來比較麻煩,AsyncTask 線程池只允許128個線程工作,會有溢出的問題,(當然一般情況不會有那麼多線程同時工作的)所以寫了這個代碼,還望高手指正! [Java]代碼01 package com.xbl.task;02 03 import java.io.BufferedReader;04 import java.io.InputStream;05 import java.io.InputStreamReader;06 import java.net.URL;07 import java.util.concurrent.Executor;08 import java.util.concurrent.ExecutorService;09 import java.util.concurrent.Executors;10 11 import android.os.Bundle;12 import android.os.Handler;13 import android.os.Message;14 import android.util.Log;15 16 17 public class JQuery {18 19 private static final String KEY = "key";20 private static String TAG = "JQuery";21 private static final int N = 5;// 5個工人 22 private static final Executor worker = Executors.newFixedThreadPool(N);// 線程池23 private static final Handler handler = new Handler(){24 @Override25 public void handleMessage(Message msg) {26 TaskListener listener = (TaskListener)msg.obj;27 Object result = msg.getData();28 if(listener !=null ){29 listener.callBack(result);30 }31 destory();32 }33 };34 35 private JQuery(){ 36 }37 38 public static void execute(final String url,final TaskListener listener){39 worker.execute(new Runnable() {40 @Override41 public void run() {42 String result = null;43 try {44 result = WebUtil.get(url);45 } catch (Exception e) {46 Log.e(TAG, e.getMessage());47 }48 49 Message msg = new Message();50 Bundle data = new Bundle();51 data.putSerializable(KEY, result);52 msg.setData(data);53 msg.obj = listener;54 handler.sendMessage(msg);55 }56 });57 }58 59 //銷毀線程60 private static void destory() {61 if (worker != null && worker instanceof ExecutorService) {62 ExecutorService es = (ExecutorService) worker;63 if (!es.isShutdown()) {64 es.shutdown();65 }66 }67 } 68 69 public interface TaskListener{70 public void callBack(Object result);71 }72 /**73 *74 * 不必太在意此處代碼,只是樣本75 *76 */77 public static class WebUtil{78 79 public static String get(String url) throws Exception{80 InputStream inputStream = new URL(url).openStream();81 StringBuilder strBuilder = new StringBuilder();82 BufferedReader reader = new BufferedReader(newInputStreamReader(inputStream));83 for (String s = reader.readLine(); s != null; s = reader.readLine())84 strBuilder.append(s);85 86 inputStream.close();87 return strBuilder.toString();88 }89 }90 }[代碼] [Java]代碼01 //調用方法:02 JQuery.execute("http://weather.news.qq.com/inc/minisite_125.js", newJQuery.TaskListener() { 03 @Override04 public void callBack(Object result) {05 TextView t = new TextView(TaskDemoActivity.this);06 t.setText(String.valueOf(result));07 LinearLayout layout = (LinearLayout)findViewById(R.id.layout1);08 layout.addView(t);09 }10 });