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