zoukankan      html  css  js  c++  java
  • NoHttp封装--07 自定义异步任务框架

    MainActivity:

     1 public class MainActivity extends Activity implements View.OnClickListener {
     2 
     3     ....
     4 
     5     @Override
     6     public void onClick(View v) {
     7         MultiAsynctaskNetwork network = new MultiAsynctaskNetwork(networkInterface);
     8         network.execute();
     9     }
    10 
    11     private NetworkInterface networkInterface = new NetworkInterface() {
    12         @Override
    13         public void onResult(String result) {
    14             mTvResult.setText(result);
    15         }
    16     };
    17 
    18 }

    NetworkInterface:

    1 public interface NetworkInterface {
    2 
    3     void onResult(String result);
    4 
    5 }

    MultiAsynctaskNetwork:

     1 public class MultiAsynctaskNetwork extends MultiAsynctask<Void, Integer, String> {
     2 
     3     private NetworkInterface mInterface;
     4 
     5     public MultiAsynctaskNetwork(NetworkInterface networkInterface) {
     6         this.mInterface = networkInterface;
     7     }
     8 
     9     @Override
    10     protected String onExecuteTask(Void... params) {
    11         HttpURLConnection connection = null;
    12         try {
    13             URL url = new URL("http://blog.csdn.net/yanzhenjie1003");
    14             connection = (HttpURLConnection) url.openConnection();
    15             int responseCode = connection.getResponseCode();
    16             if (responseCode == 200) {
    17                 int len = 0;
    18                 byte[] buffer = new byte[1024];
    19                 ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
    20                 InputStream inputStream = new BufferedInputStream(connection.getInputStream());
    21                 while ((len = inputStream.read(buffer)) != -1) {
    22                     arrayOutputStream.write(buffer, 0, len);
    23                 }
    24                 inputStream.close();
    25                 arrayOutputStream.flush();
    26                 inputStream.close();
    27                 return new String(arrayOutputStream.toByteArray());
    28             }
    29         } catch (Exception e) {
    30             e.printStackTrace();
    31         } finally {
    32             if (connection != null)
    33                 connection.disconnect();
    34         }
    35         return "请求网络失败";
    36     }
    37 
    38     @Override
    39     public void onResult(String result) {// 拿到执行结果,直接更新UI
    40         mInterface.onResult(result);
    41     }
    42 
    43 }

    核心类MultiAsynctask:

      1 public abstract class MultiAsynctask<Param, Update, Result> {
      2 
      3     /**
      4      * 更新的what
      5      */
      6     private static final int WHAT_UPDATE = 0x01;
      7 
      8     /**
      9      * 发送结果的what
     10      */
     11     private static final int WHAT_RESULT = 0x02;
     12 
     13     /**
     14      * 默认的线程池
     15      */
     16     private static ExecutorService sExecutorService;
     17 
     18     /**
     19      * 默认并发大小
     20      */
     21     private static final int DEFAULT_POOL_SIZE = 5;
     22 
     23     /**
     24      * 发送结果的Handler
     25      */
     26     private static Handler sHandler;
     27 
     28     /**
     29      * Handler的锁
     30      */
     31     private static Object HANDLER_LOCK = new Object();
     32 
     33     /**
     34      * 本地异步任务的执行器
     35      */
     36     private ExecutorService mExecutorService = null;
     37 
     38     public MultiAsynctask() {
     39         this(getDufaultExecutor());
     40     }
     41 
     42     public MultiAsynctask(ExecutorService executorService) {
     43         mExecutorService = executorService;
     44     }
     45 
     46     /**
     47      * 拿到默认的线程池
     48      * 
     49      * @return
     50      */
     51     private static ExecutorService getDufaultExecutor() {
     52         synchronized (MultiAsynctask.class) {
     53             if (sExecutorService == null)
     54                 sExecutorService = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE);
     55             return sExecutorService;
     56         }
     57     }
     58 
     59     /**
     60      * 设置默认的线程池
     61      * 
     62      * @param executorService
     63      */
     64     public static void setDefaultExecutor(ExecutorService executorService) {
     65         synchronized (MultiAsynctask.class) {
     66             sExecutorService = executorService;
     67         }
     68     }
     69 
     70     public static Handler getDefaultPoster() {
     71         synchronized (HANDLER_LOCK) {
     72             if (sHandler == null)
     73                 sHandler = new Poster();
     74             return sHandler;
     75         }
     76     }
     77 
     78     /**
     79      * 开始执行任务
     80      * 
     81      * @param params
     82      */
     83     public final void execute(Param... params) {
     84         mExecutorService.execute(new Tasker(params));
     85     }
     86 
     87     protected abstract Result onExecuteTask(Param... params);
     88 
     89     /**
     90      * 发送进度更新到主线程
     91      * 
     92      * @param update
     93      */
     94     public final void onPostUpdate(Update update) {
     95         Message.obtain();
     96         Message message = getDefaultPoster().obtainMessage();
     97         message.what = WHAT_UPDATE;
     98         message.obj = new Messager<Param, Update, Result>(this, update, null);
     99         message.sendToTarget();
    100     }
    101 
    102     /**
    103      * 当返回进度更新的时候
    104      * 
    105      * @param update
    106      */
    107     protected void onUpdate(Update update) {
    108     }
    109 
    110     /**
    111      * 发送进度执行结果到主线程
    112      * 
    113      * @param result
    114      */
    115     public final void onPostResult(Result result) {
    116         Message.obtain();
    117         Message message = getDefaultPoster().obtainMessage();
    118         message.what = WHAT_RESULT;
    119         message.obj = new Messager<Param, Update, Result>(this, null, result);
    120         message.sendToTarget();
    121     }
    122 
    123     /**
    124      * 当返回执行结果的时候
    125      * 
    126      * @param result
    127      */
    128     protected void onResult(Result result) {
    129 
    130     }
    131 
    132     private static class Messager<Param, Update, Result> {
    133 
    134         private final MultiAsynctask<Param, Update, Result> asynctask;
    135 
    136         private final Update update;
    137 
    138         private final Result result;
    139 
    140         public Messager(MultiAsynctask<Param, Update, Result> asynctask, Update update, Result result) {
    141             this.asynctask = asynctask;
    142             this.update = update;
    143             this.result = result;
    144         }
    145 
    146         /**
    147          * 调用当前MultiAsynctask的主线程更新方法
    148          */
    149         public void onUpdate() {
    150             asynctask.onUpdate(update);
    151         }
    152 
    153         /**
    154          * 调用当前MultiAsynctask的主线程结果方法
    155          */
    156         public void onResult() {
    157             asynctask.onResult(result);
    158         }
    159 
    160     }
    161 
    162     /**
    163      * <p>
    164      * 线程间通信使者
    165      * </p>
    166      * Created in Mar 27, 2016 10:00:03 PM.
    167      * 
    168      * @author Yolanda;
    169      */
    170     private static class Poster extends Handler {
    171 
    172         public Poster() {
    173             super(Looper.getMainLooper());
    174         }
    175 
    176         @Override
    177         public void handleMessage(Message msg) {
    178             Messager<?, ?, ?> messageer = (Messager<?, ?, ?>) msg.obj;
    179             if (msg.what == WHAT_RESULT) {
    180                 messageer.onResult();
    181             } else if (msg.what == WHAT_UPDATE) {
    182                 messageer.onUpdate();
    183             }
    184         }
    185     }
    186 
    187     /**
    188      * <p>
    189      * 任务执行器
    190      * </p>
    191      * Created in Mar 27, 2016 10:03:44 PM.
    192      * 
    193      * @author Yolanda;
    194      */
    195     private class Tasker implements Runnable {
    196 
    197         private Param[] params;
    198 
    199         public Tasker(Param... params) {
    200             this.params = params;
    201         }
    202 
    203         @Override
    204         public void run() {
    205             Result result = onExecuteTask(params);
    206             onPostResult(result);
    207         }
    208     }
    209 
    210 }
  • 相关阅读:
    将微信小程序上传到公司的账号下
    当HBuilderX运行时打不开微信开发者工具时
    vue路径中去掉#
    初次快速使用git
    小米商城应用效果(阴影效果)
    如何使用hover点击一个元素使另一个颜色变色
    Open browser failed!! Please check if you have installed the browser correct
    vue中解决跨域问题
    vue中如何实现点击动态切换样式
    es5中数组的迭代方法 forEach,map,filter,some,every
  • 原文地址:https://www.cnblogs.com/ganchuanpu/p/9038801.html
Copyright © 2011-2022 走看看