【问题标题】:InputStream - Dealing with network changesInputStream - 处理网络变化
【发布时间】:2013-01-04 10:36:32
【问题描述】:

我正在使用 Java 邮件 API 下载附件,每当网络状态发生微小变化时,我的应用就会卡住,我必须重新启动它,它甚至没有崩溃。 这是代码sn-p:

InputStream is = bodyPart.getInputStream();

String fileName = MimeUtility.decodeText(bodyPart.getFileName());

// Downloading the file
File f = new File(Constants.getPath() + fileName);
try {
    FileOutputStream fos;
    fos = new FileOutputStream(f);

    byte[] buf = new byte[8*1024];
    int bytesRead;

    while ((bytesRead = is.read(buf)) != -1) {
    fos.write(buf, 0, bytesRead);
    }
    fos.close();
}

处理此问题的最佳方法是什么?谢谢。

【问题讨论】:

  • 尝试用BufferedInputStream包装输入流,看看这里是否支持skip()方法(是否抛出IOException)。如果是,那么您将能够恢复之前的下载。
  • 嗨,谢谢,它确实会抛出 IOException。您能否告诉我如何恢复之前的下载以及它与应用程序冻结的事实有何关系?
  • 如果支持skip(),则支持Resuming previous download。但是,我能想到的唯一选择是在is.read() 上设置一个超时时间,如果碰巧超过了超时时间,那么您应该终止下载并重新开始。看到这个问题:stackoverflow.com/questions/804951/…
  • @Eng.Fouad BufferedInputStream 完全支持 skip() :它不需要测试来确定;但是支持 skip() 的 BufferedInputStream 与支持恢复先前下载的 JavaMail 无关。他需要的是读取超时。我手头没有 JavaMail 文档,但它肯定支持。
  • @EJP According to the documentation, skip() throws IOException if the stream does not support seek,这就是为什么我说“如果它支持skip(),那么它将支持Resuming previous download” .

标签: java android network-programming inputstream


【解决方案1】:

您的应用程序卡住了。解决方案是设置读取超时,如this question 中所述。如果发生超时,则会抛出 SocketTimeoutException。

【讨论】:

  • 我有以下所有超时:props2.setProperty("mail.imaps.connectionpooltimeout", "3000"); props2.setProperty("mail.imaps.connectiontimeout", "3000"); props2.setProperty("mail.imap.timeout", "3000");在获取消息详细信息时仍然卡住,例如 message.getSubject()。奇怪的是,只有在从 3g 切换到 WI-FI 时才会发生这种情况。当我从 WI-FI 切换到 3g 时,它会抛出 FolderClosedException,然后我可以处理它。
  • 谢谢,我通过在 timeout 属性中将 imap 更改为 imaps 解决了这个问题。
猜你喜欢
  • 2014-08-07
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
  • 2011-08-23
  • 2018-06-13
  • 1970-01-01
  • 2013-12-14
  • 1970-01-01
相关资源
最近更新 更多