zoukankan      html  css  js  c++  java
  • 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                });
  • 相关阅读:
    千千静听被拖到桌面之外的解决办法
    Excel学习(二)快速添充单元格
    tomcat中的server.xml中关于虚拟目录的设定
    配置SVN
    DataTable.Select() 方法的简单用法
    Excel学习(一) 单元格显示下拉列表框
    Excel学习(三)添加打印预览按钮
    打造自己的资料库
    APAHCE基于IP端口的虚拟主机的设定
    反射
  • 原文地址:https://www.cnblogs.com/xiaochao1234/p/3671215.html
Copyright © 2011-2022 走看看