当互联网连接丢失时,读取Inputstream不停止

时间:2012-08-07 03:28:05

标签: android android-asynctask inputstream

我正在使用asynctask来下载文件。它正常工作,直到我关闭我的Android的wifi连接(没有其他互联网连接),仍然没有更改下载对话框。当我通过日志检查时,我发现输入流的函数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);
        }

2 个答案:

答案 0 :(得分:7)

由于您已经通过调用setReadTimeout()设置了超时,因此您应该在连接断开后立即获得SocketTimeoutException

您的代码是否可能会以静默方式捕获此异常?

答案 1 :(得分:0)

您的文件下载缓冲区大小太多byte buffer[] = new byte[1024];就足够了

当我用asynctask尝试这个Download a file with Android, and showing the progress in a ProgressDialog(顶部答案)时,工作正常,没有得到那个问题