android - 互联网连接丢失时不停止读取 Inputstream

标签 android android-asynctask inputstream

我正在使用异步任务下载文件。它正常工作,直到我关闭我的 android 的 wifi 连接(没有其他互联网连接),下载对话框仍然没有变化。当我查看日志时,我发现 inputstream 的函数 read() 是不停的。那么如何检查这种情况呢?这是我的代码:

URL url = new URL(this.url);
        URLConnection connection = url.openConnection();
        connection.setReadTimeout(1000);
        connection.connect();
        // this will be useful so that you can show a typical 0-100% progress bar
        int fileLength = connection.getContentLength();
        fileName = "temp.zip";

        // download the file
        InputStream input = new BufferedInputStream(connection.getInputStream());
        OutputStream output = new FileOutputStream(path+fileName);

        byte buffer[] = new byte[1024000];
        long total = 0;
        int count;
        Log.v("test download:","download in background");
        while (((count = input.read(buffer)) != -1)) {
            Log.v("test download:","read:"+count);
            total += count;
            publishProgress((int) (total * 100 / fileLength - 1));
            output.write(buffer, 0, count);
        }

最佳答案

因为您已经通过调用 setReadTimeout() 设置了超时,您应该在连接断开后不久收到 SocketTimeoutException

您的代码是否碰巧可以静默捕获此异常?

关于android - 互联网连接丢失时不停止读取 Inputstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11838849/

相关文章:

java - 直到某个特定行才能写入文件

java:检查 php 输出时出错

android - 在 android 的单声道中引用 iTextSharp Dll 时出现编译错误

android - 如何将 leap-motion 直接连接到 android

java - Android : SurfaceView, 为什么在不同的线程上绘制

android - JobSchedule 和静态匿名 AsyncTask

java - 异步任务发生异常

java - 我应该使用 AsyncTask 还是 IntentService 进行 REST API 调用?

java - 高流量时 Rest-API 响应时间增加

android - 被调用的Activity退出时如何返回结果 'in a natural way'?