我有一个允许下载文件的异步方法。如果在下载过程中,我将删除连接(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);
}
...
}
...