Android的InputStream的网络断开连接 [英] Android InputStream Internet Disconnect

查看:392
本文介绍了Android的InputStream的网络断开连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Andr​​oid程序,我有一些code表示下载文件。这工作得很好,但由于在手机上,你可以随时断开,我需要去改变它做重新连接和恢复时,你是中途,有人呼叫/你失去细胞接收/等下载。我无法弄清楚如何检测的InputStream已停止工作。请参见下面的code:

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)

然后我的程序只是挂在同时((LEN1 =等我需要使它所以当网络断开连接我等待互联网再次连接,然后重新下载。

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.

推荐答案

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

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

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.

另一种方法是不使用的HttpURLConnection和处理,你需要你的自我位。

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

这篇关于Android的InputStream的网络断开连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆