【发布时间】:2013-09-30 08:40:06
【问题描述】:
我有一个允许下载文件的异步方法。 如果在下载过程中,我将删除连接(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);
}
...
}
...
【问题讨论】:
-
这个问题之前有人问过,但不包括关于使用 wifi 的问题:stackoverflow.com/q/3163693/42962 我建议遵循这篇文章的建议:stackoverflow.com/a/7611294/42962 请调用 getReadTimeout() 和 getConnectTimeout () 甚至查看您尝试设置的值是否已被对象占用。
标签: java android timeout urlconnection connection-timeout