Android异步方法以同步方式实现
作者:落叶Ex 时间:2022-11-05 15:13:50
Android强制异步转同步方法,供大家参考,具体内容如下
Android系统中规定耗时任务需要在异步线程中进行,特别是网络请求必须在异步线程中进行否则会抛出NetworkOnMainThreadException,但是在一些特殊的情况我们需要保证在获得到网络请求结果之后在进行余下操作,这时候便需要在UiThread中进行相关操作。
这样就需要用到线程阻塞的原理,这里可以借助Callable或FutureTask来实现。
public static String getSyncBusiness(final String url){
try {
FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
@Override
public String call() throws Exception {
URL u = new URL(url);
HttpURLConnection connection = (HttpURLConnection) u.openConnection();
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.connect();
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf8"));
final StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine())!=null){
sb.append(line);
}
return sb.toString();
}
});
new Thread(task).start();
return task.get();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("网络访问错误");
}
}
FutureTask接口是一个泛型接口,可以设置需要返回的类型,并且可以看出该方法为了方便程序员的操作,巧妙的通过抛出一个总Exception来保证方法统一执行统一判断,类似于RxJava的Exception机制。并且通过源码可以看出,该接口实现了RunnableFuture<>接口,而RunnableFuture接口又继承于Runnable这也就解释了为什么可以直接在new Thread中传入Task对象。
可以理解为FuturTask通过实现Runnable对子线程进行驱动,进行异步的网络请求等操作,但是并没有进行异步并发操作,而是同时阻塞了UI线程,直到该子线程执行完毕。
除了以上还可以直接使用Callable接口,需要注意,Callable需要线程池ExecutorService才可以进行驱动。
public static String getSyncBusiness2(final String url){
try {
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws Exception {
URL u = new URL(url);
HttpURLConnection connection = (HttpURLConnection) u.openConnection();
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.connect();
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf8"));
final StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine())!=null){
sb.append(line);
}
return sb.toString();
}
};
ExecutorService exec = Executors.newFixedThreadPool(1);
Future<String> task = exec.submit(callable);
return task.get();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("网络访问错误");
}
}
由于原理终归是对UI线程进行了阻塞,所有非特别需要不推荐使用,阻塞时间过长同样会触发ANR。
来源:https://blog.csdn.net/ccw0054/article/details/70226156
标签:Android,异步,同步
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
C#手动操作DataGridView使用各种数据源填充表格实例
2023-07-20 08:30:31
![](https://img.aspxhome.com/file/2023/6/122736_0s.png)
Unity3D实现虚拟按钮控制人物移动效果
2022-06-13 04:26:26
![](https://img.aspxhome.com/file/2023/5/111085_0s.jpg)
Java将字符串String转换为整型Int的两种方式
2021-12-11 10:01:32
![](https://img.aspxhome.com/file/2023/9/86769_0s.png)
Spring注解驱动之BeanDefinitionRegistryPostProcessor原理解析
2023-11-24 23:24:21
![](https://img.aspxhome.com/file/2023/8/59758_0s.jpg)
Android手势识别功能
2022-07-23 22:04:26
Android实现简易秒表功能
2021-08-29 11:06:58
![](https://img.aspxhome.com/file/2023/6/95986_0s.jpg)
详谈Java中Object类中的方法以及finalize函数作用
2021-05-29 07:59:25
相对路径和绝对路径的写法总结
2022-06-17 07:38:47
Java常用函数式接口总结
2022-02-02 00:02:50
![](https://img.aspxhome.com/file/2023/8/68178_0s.png)
C#验证给定字符串形式日期是否合法的方法
2021-09-15 16:00:37
Android开发实现SubMenu选项菜单和子菜单示例
2022-05-31 06:32:10
![](https://img.aspxhome.com/file/2023/0/114280_0s.gif)
Java如何利用递归计算出阶乘
2023-02-08 12:43:03
![](https://img.aspxhome.com/file/2023/6/92676_0s.webp)
C# 8.0中的范围类型(Range Type)示例详解
2023-04-11 22:26:10
Java DecimalFormat 保留小数位及四舍五入的陷阱介绍
2023-11-09 04:49:33
详解java中产生死锁的原因及如何避免
2022-04-22 00:36:14
Java Thread.currentThread().getName() 和 this.getName()区别详解
2021-10-31 01:46:18
![](https://img.aspxhome.com/file/2023/4/61834_0s.png)
springboot结合maven配置不同环境的profile方式
2022-05-28 12:00:16
![](https://img.aspxhome.com/file/2023/6/63416_0s.png)
浅析c# 线程同步
2022-09-19 18:43:03
Android7.0 MTK设置默认桌面
2023-09-26 12:30:43
Java用数组实现循环队列的示例
2022-06-26 15:09:48