首页 > 代码库 > Android简单封装类似JQuery异步请求

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

在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            @Override
25            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                @Override
41                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 = http://www.mamicode.com/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                    @Override
04                    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                });

 

<iframe id="google_ads_frame2" vspace="0" height="250" marginHeight="0" src="http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-3447371224873639&output=html&h=250&slotname=8660799060&adk=1970350646&w=300&lmt=1399312767&flash=0&url=http%3A%2F%2Fwww.cnblogs.com%2Fxiaochao1234%2Fp%2F3709073.html&dt=1399312771836&shv=r20140429&cbv=r20140417&saldr=sb&prev_slotnames=4356862740&correlator=1399312771265&frm=20&ga_vid=429972749.1397695120&ga_sid=1399310453&ga_hid=1231983664&ga_fc=1&u_tz=480&u_his=34&u_java=1&u_h=768&u_w=1364&u_ah=740&u_aw=1364&u_cd=16&u_nplug=0&u_nmime=0&dff=verdana&dfs=16&adx=0&ady=2706&biw=314&bih=74&eid=317150304&oid=3&rx=0&eae=0&docm=9&vis=0&fu=0&ifi=2&xpc=4IC8hElKl0&p=http%3A//www.cnblogs.com&dtd=43" frameBorder="0" width="300" allowTransparency="true" name="google_ads_frame2" marginWidth="0" scrolling="no" hspace="0"></iframe><iframe id="google_ads_frame3" vspace="0" height="250" marginHeight="0" src="http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-3447371224873639&output=html&h=250&slotname=8660799060&adk=1970350646&w=300&lmt=1399312767&flash=0&url=http%3A%2F%2Fwww.cnblogs.com%2Fxiaochao1234%2Fp%2F3709073.html&dt=1399312771886&shv=r20140429&cbv=r20140417&saldr=sb&prev_slotnames=4356862740%2C8660799060&correlator=1399312771265&frm=20&ga_vid=429972749.1397695120&ga_sid=1399310453&ga_hid=1231983664&ga_fc=1&u_tz=480&u_his=34&u_java=1&u_h=768&u_w=1364&u_ah=740&u_aw=1364&u_cd=16&u_nplug=0&u_nmime=0&dff=verdana&dfs=16&adx=306&ady=2956&biw=314&bih=74&eid=317150304&oid=3&rx=0&eae=0&docm=9&vis=0&fu=0&ifi=3&xpc=z5uhWGaUjW&p=http%3A//www.cnblogs.com&dtd=42" frameBorder="0" width="300" allowTransparency="true" name="google_ads_frame3" marginWidth="0" scrolling="no" hspace="0"></iframe>