Retrofit2遇到android.os.NetworkOnMainThreadException异常
来源:互联网 发布:php拍卖系统源码 编辑:程序博客网 时间:2024/06/05 16:03
APP中使用Retrofit2,在做下载功能时,惊喜的发现这个android.os.NetworkOnMainThreadException异常,抓到子线程去跑结果还是存在,后面试着把
@Streaming这个针对大文件下载的注解去掉后,功能正常,然后我还是想用@Streaming这个注解,但是又还存在这个异常,只能再度找度娘,最终总算解决了,看代码吧,肯定懂
private void Downs(){ new Thread(new Runnable() { @Override public void run() { Call<ResponseBody> call = mResonServer.DownloadPic(list.get(positions)); try { Response<ResponseBody> response = call.execute();//同步请求 File file = null; if (response.isSuccessful()) { try { InputStream is = response.body().byteStream(); if (!appDir.exists()) { appDir.mkdir(); } String fileName = "Pic" + System.currentTimeMillis() + ".png"; file = new File(appDir, fileName); FileOutputStream fos = new FileOutputStream(file); BufferedInputStream bis = new BufferedInputStream(is); byte[] buffer = new byte[1024]; int len; while ((len = bis.read(buffer)) != -1) { fos.write(buffer, 0, len); fos.flush(); } fos.close(); bis.close(); is.close(); sendMsg("已保存到目录"+file.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); sendMsg("保存失败"); } } else { sendMsg("保存失败"); } call.cancel(); } catch (IOException e) { e.printStackTrace(); sendMsg("保存失败"); } } }).start();}//更新通知
private void sendMsg(String info){ msg = new Message(); b = new Bundle(); b.putString("info", info); msg.setData(b); handler.sendMessage(msg);}
这里的请求不是使用call.异步请求,而是使用同步请求,同时handler更新ui
阅读全文
0 0
- Retrofit2遇到android.os.NetworkOnMainThreadException异常
- android.os.NetworkOnMainThreadException异常
- 异常:android.os.NetworkOnMainThreadException
- android.os.NetworkOnMainThreadException异常
- 异常:android.os.NetworkOnMainThreadException
- 异常android.os.NetworkOnMainThreadException
- 异常:android.os.NetworkOnMainThreadException
- 异常:android.os.NetworkOnMainThreadException
- android.os.NetworkOnMainThreadException异常
- 异常:android.os.NetworkOnMainThreadException
- 异常:android.os.NetworkOnMainThreadException
- android.os.NetworkOnMainThreadException异常
- 异常:android.os.NetworkOnMainThreadException
- android.os.NetworkOnMainThreadException异常
- android.os.NetworkOnMainThreadException异常
- android.os.NetworkOnMainThreadException异常
- 异常:android.os.NetworkOnMainThreadException
- android.os.NetworkOnMainThreadException异常
- 搭建可通过外网访问的内网服务器
- %s格式化输出
- ext6.2分页给加额外参数用Ext.data.Store的extraParams
- 《柒个我》全集百度云网盘资源
- springboot学习--《二》
- Retrofit2遇到android.os.NetworkOnMainThreadException异常
- 路由表 转发表(FIB) 快速转发表 简介与分析
- shell的多行注释
- 记录开发一个简历导出为Word格式的流程
- linux系统目录结构
- 第八天实训!!!!!
- Java实现混合高斯聚类
- 图像的熵
- dump FSDB波形