Retrofit2遇到android.os.NetworkOnMainThreadException异常

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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值