【问题标题】:read of Inputstream non stop when internet connection lost互联网连接丢失时不间断读取输入流
【发布时间】:2012-08-04 01:08:58
【问题描述】:

我正在使用异步任务下载文件。它正常工作,直到我关闭我的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);
        }

【问题讨论】:

  • 如果你尝试使用更小的缓冲区(和更多的读取请求)有什么不同吗?
  • 不,总是遇到同样的问题。

标签: android android-asynctask inputstream


【解决方案1】:

你的文件下载缓冲区太大byte buffer[] = new byte[1024];够了

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

【讨论】:

    【解决方案2】:

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

    您的代码是否会静默捕获此异常?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-09
      • 2013-03-28
      • 2017-06-18
      相关资源
      最近更新 更多