3G转WIFI如何处理? UrlConnection TimeOut 不会抛出异常

发布于 2024-10-02 16:13:11 字数 790 浏览 3 评论 0原文

我的应用程序需要下载一些大文件。我使用下载服务并在通知中显示进度。问题是在下载期间用户可以从 3g 切换到 WIFI。在这种情况下,进度会停止,但不会引发异常。 我该如何正确处理这种情况?

URL url = new URL(myurl);
URLConnection conexion = url.openConnection();
conexion.setReadTimeout(10000);
conexion.setConnectTimeout(10000);
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(targetFilePath);

byte data[] = new byte[1024];

long total = 0;
while ((count = input.read(data)) != -1) {
    total += count;
    // publishing the progress....
    updateProgress(downloadNM, downloadNotification, (int)total*100/lenghtOfFile);
    output.write(data, 0, count);
}
output.flush();
output.close();
input.close();

My application needs to download some big Files. I use a service for the download an show the progress in a notification. The problem is that during that download time the user can switch from 3g to WIFI. In that case the progress stops but no exception is thrown.
How do I handle this situation properly?

URL url = new URL(myurl);
URLConnection conexion = url.openConnection();
conexion.setReadTimeout(10000);
conexion.setConnectTimeout(10000);
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(targetFilePath);

byte data[] = new byte[1024];

long total = 0;
while ((count = input.read(data)) != -1) {
    total += count;
    // publishing the progress....
    updateProgress(downloadNM, downloadNotification, (int)total*100/lenghtOfFile);
    output.write(data, 0, count);
}
output.flush();
output.close();
input.close();

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

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

发布评论

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

评论(1

莳間冲淡了誓言ζ 2024-10-09 16:13:12

看一下 HttpClient-Library。它提供了比 URL 类更多的选项,并且可能会帮助您解决问题。

http://developer.android.com/reference/org/apache /http/client/HttpClient.html

Take a look at the HttpClient-Library. It provides much more options than the URL class, and might help you with your problem.

http://developer.android.com/reference/org/apache/http/client/HttpClient.html

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