0

我有一个允许下载文件的异步方法。如果在下载过程中,我将删除连接(wifi 或 3g)永远不会发生超时。

始终停留在等待返回连接的下一个循环中:

while ((count = input.read(data)) != -1) {
        System.out.println("state 5");
        total += count;
        publishProgress((int) (total * 100 / fileLength));
        output.write(data, 0, count);
}

我愿意:

  private class DownloaderFile extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
            ...
            try{
                URLConnection connection = urlFinal.openConnection();
                connection.setConnectTimeout(TIMEOUT_VALUE);
                connection.setReadTimeout(TIMEOUT_VALUE);
                connection.connect();
                int fileLength = connection.getContentLength();

                InputStream input = new BufferedInputStream(urlFinal.openStream());

                OutputStream output = new FileOutputStream(folder + params[0]);

                byte data[] = new byte[1024];
                long total = 0;
                int count;

                while ((count = input.read(data)) != -1) {
//always wait here
                    System.out.println("state 5");
                    total += count;
                    publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
            } catch (SocketTimeoutException e) {
                System.out.println("TIMEOUT!!! " + TIMEOUT_VALUE + " elapsed.");
                callback.onDownloadEnd(DOWNLOAD_ERROR);
            }
            ...
        }
        ...
4

3 回答 3

1

这不是一个很好的解决方案,但它有效。当我想到另一个解决方案时......

while ((count = input.read(data)) != -1) {
     if (!isInternet(context)){
        callback.onDownloadEnd(DOWNLOAD_ERROR);
         return "error";
     }
     total += count;
     publishProgress((int) (total * 100 / fileLength));
     output.write(data, 0, count);
}
于 2013-09-24T23:45:47.153 回答
0

我怀疑 SocketTimeoutException 是要查找的错误异常,因为在您的测试中建立了正确的连接,如果您将其更改为异常怎么办?只是看看这是否有帮助。

我可以从:How to set HttpResponse timeout for Android in Java我错了。

从我链接的信息中,我发现您可能需要设置:

  // Set the default socket timeout (SO_TIMEOUT) 
  // in milliseconds which is the timeout for waiting for data.
  int timeoutSocket = 5000;
  HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
于 2013-09-24T22:49:58.823 回答
0

不管是什么原因,我猜当 3g/wifi 不再可用时,从套接字读取的线程被阻塞了。

您可以在此处采用的一种方法是在单独的线程上执行套接字读取,并使用Thread.join(long millis)方法等待最多毫秒以完成。

Thread t = new Thread(new Runnable() {
             void run() {
               ...
               while ((count = input.read(data)) != -1) {
                 ...
               }
               ...
             }
           }).start();

t.join(TIMEOUT_VALUE); // will wait here until either the thread t is done or times out
于 2013-09-24T22:59:40.173 回答