博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
NoHttp封装--07 自定义异步任务框架
阅读量:6237 次
发布时间:2019-06-22

本文共 7019 字,大约阅读时间需要 23 分钟。

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         @Override13         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 @Override10 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 @Override39 public void onResult(String result) {
// 拿到执行结果,直接更新UI40 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 update106 */107 protected void onUpdate(Update update) {108 }109 110 /**111 * 发送进度执行结果到主线程112 * 113 * @param result114 */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 result127 */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 @Override177 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 @Override204 public void run() {205 Result result = onExecuteTask(params);206 onPostResult(result);207 }208 }209 210 }

 

转载于:https://www.cnblogs.com/ganchuanpu/p/9038801.html

你可能感兴趣的文章
oracle 11g jdbc jar包在哪个文件目录
查看>>
软件架构是软件功能在技术域上的投影
查看>>
python中的lxml模块
查看>>
分布式强化学习基础概念(Distributional RL )
查看>>
.NET Core单文件发布静态编译AOT CoreRT
查看>>
RChain节点通信机制
查看>>
【python下使用OpenCV实现计算机视觉读书笔记2】图像与字节的变换
查看>>
关于metaclass,我原以为我是懂的
查看>>
Trait的使用
查看>>
obj-fit
查看>>
安装zoom
查看>>
【转】不要做聪明人
查看>>
Redis进阶实践之十四 Redis-cli命令行工具使用详解第一部分
查看>>
Linux之文件系统各种符号说明
查看>>
论文即思路
查看>>
【亲测可用,亦可配置同一平台的不同账号,例如阿里云的两个不同账号】Windows下Git多账号配置,同一电脑多个ssh-key的管理...
查看>>
Apache Cordova
查看>>
python urllib和urllib3包
查看>>
谈谈在.NET Core中使用Redis和Memcached的序列化问题
查看>>
父节点递归查询和子节点递归查询函数
查看>>