资讯专栏INFORMATION COLUMN

NoHttp封装--07 自定义异步任务框架

Hancock_Xu / 2167人阅读

摘要:请求网络失败拿到执行结果,直接更新核心类更新的发送结果的默认的线程池默认并发大小发送结果的的锁本地异步任务的执行器拿到默认的线程池设置默认的线程池开始执行任务发送进度更新到主线程当返回进度更新的时候发送进度执行结果到主线程当返回执行结果的

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 {
 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 {
  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(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(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 {
133 
134         private final MultiAsynctask asynctask;
135 
136         private final Update update;
137 
138         private final Result result;
139 
140         public Messager(MultiAsynctask 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      * 

164 * 线程间通信使者 165 *

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 *

189 * 任务执行器 190 *

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 }

 

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/3068.html

相关文章

  • NoHttp封装--04 缓存

    摘要:请求,缓存非标准协议,改变缓存模式为请求图片,缓存图片仅仅请求网络无论如何也只会请求网络,也不支持这种默认行为。仅仅读取缓存无论如何仅仅读取缓存,不会请求网络和其它操作。 1、Default模式,也是没有设置缓存模式时的默认模式 这个模式实现http协议中的内容,比如响应码是304时,当然还会结合E-Tag和LastModify等头。 StringRequest request = ne...

    Kerr1Gan 评论0 收藏0
  • NoHttp封装--02 定义请求

    摘要:实体类请求针对的具体在中使用处理登录结果登录接口结果处理登出结果退出接口结果请求失败可以解析所有的自定义请求但是前提是传进来的必须提供了默认实现bean实体类请求: 1.bean 1 import java.io.Serializable; 2 import com.alibaba.fastjson.annotation.JSONField; 3 4 public class U...

    TigerChain 评论0 收藏0
  • NoHttp封装--06 NoHttp之队列、队列优先级

    摘要:程序入口第一种,先进先出的队列第二种,没有顺序的队列往队列中添加请求请求是一个先进先出的队列如果方法不做比较返回,那么是无序的方法是一个阻塞的方法,每次调用会拿到队列中的第一个任务,如果队列为空,这个方法将一直阻塞,知道队列中有任务再次返回public class Main { /** * 程序入口 */ public void start() { ...

    U2FsdGVkX1x 评论0 收藏0
  • NoHttp封装--01

    摘要:登陆退出处理登录结果登录接口数据处理登出结果退出接口数据请求失败添加一个请求到请求队列上下文请求对象接受回调结果,当多个请求用同一个接受结果时,用来区分请求是否显示请求是否能被用户取消是否提示用户错误信息客户端错误客户端发生错误服务器错误服NoHttpActivity 1 public class NoHttpActivity extends Activity implements Vi...

    KnewOne 评论0 收藏0
  • Android框架 - 收藏集 - 掘金

    摘要:说好的分类集合来啦,采用标签云的方式来展示掘金阅读提示点击下文中返回到顶部有分类不合理的地方请提。反编译这个后发现其使用个优质的开源项目掘金是由的开源的一个库,用于构建可预期的和声明式的用户界面。 想不想通过一线互联网公司面试? - Android - 掘金国内一线互联网公司内部面试题库 以下面试题来自于百度、小米、乐视、美团、58、猎豹、360、新浪、搜狐内部题库 熟悉本文中列出的知...

    zengdongbao 评论0 收藏0

发表评论

0条评论

Hancock_Xu

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<