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 = 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                });

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。