Android 输入流 互联网断开

发布于 2024-07-13 19:18:37 字数 679 浏览 2 评论 0原文

在我的 Android 程序中,我有一些下载文件的代码。 这工作正常,但由于在手机上,您可以随时断开连接,我需要更改它,当您中途有人打电话/您失去手机接收/等时,它会重新连接并恢复下载。 我不知道如何检测 InputStream 已停止工作。 请参阅下面的代码:

InputStream in = c.getInputStream();

    byte[] buffer = new byte[8024];
    int len1 = 0;

    while ( (len1 = in.read(buffer)) > 0 ) {
        Log("-"+len1+"- Downloaded.");
        f.write(buffer,0, len1);
        Thread.sleep(50);
    }

当我失去互联网连接时,我的日志显示:

Log: -8024- Downloaded.
Log: -8024- Downloaded.
Log: -8024- Downloaded.
Log: -8024- Downloaded.
Log: -6024- Downloaded. (some lower number)

然后我的程序就挂在 while( (len1 = 等。我需要这样做,以便当互联网断开连接时我等待互联网再次连接然后继续下载。

In my Android program, I have some code that downloads a file. This works fine, but since on a cell phone, you can be disconnected at any time, I need to change it do it reconnects and resumes the download when you are halfway through and somebody calls/you lose cell reception/etc. I cannot figure out how to detect the InputStream has stopped working. See the code below:

InputStream in = c.getInputStream();

    byte[] buffer = new byte[8024];
    int len1 = 0;

    while ( (len1 = in.read(buffer)) > 0 ) {
        Log("-"+len1+"- Downloaded.");
        f.write(buffer,0, len1);
        Thread.sleep(50);
    }

When I lose internet connection, My log shows:

Log: -8024- Downloaded.
Log: -8024- Downloaded.
Log: -8024- Downloaded.
Log: -8024- Downloaded.
Log: -6024- Downloaded. (some lower number)

And then my program just hangs on the while( (len1 = etc. I need to make it so when the internet gets disconnected I wait for the internet to be connected again and then resume the download.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青柠芒果 2024-07-20 19:18:37

看一下这里: ​​http://developer.android.com/reference /java/nio/channels/SocketChannel.html

编辑(基于评论):
http://www.jguru.com/faq/view.jsp?EID= 72378

因此,基于上述的想法......您可以将读取放入线程中,并定期检查线程是否已停止读取数据(可能更新共享变量)。 如果它已终止连接和线程并根据需要进行处理。

另一种选择是不使用 HTTPURLConnection 并自行处理您需要的位。

Take a look here: http://developer.android.com/reference/java/nio/channels/SocketChannel.html

EDIT (based on comment):
http://www.jguru.com/faq/view.jsp?EID=72378

So thoughts based on the above.... you might put the reading in a thread and periodically check to see if the thread has stopped reading data (update a shared variable probably). If it has kill the connection and the thread and deal with it however you need to.

Another alternative is to not use the HTTPURLConnection and deal with the bits you need your self.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文