Android 输入流 互联网断开
在我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看一下这里: 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.