Tenho um método utilizando HttpURLConnection para baixar um arquivo via url, o download leva cerca de 10 segundos ±, porem fiz uns testes, se eu cortar a internet quando o download é iniciado o processo fica perdido, ele é ececutado via AsyncTask com progressDialog. Como posso fazer para que o processo de tempo em tempo verifica se realmente está banxaindo ou se a internet caiu?
public boolean DownloadToURL(String fileURL, String saveDir) throws IOException {
try
{
//Monta url de conexão
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
//Time Out
//httpConn.setConnectTimeout(3000);
//httpConn.setReadTimeout(120000);
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
httpConn.disconnect();
return true;
} else {
httpConn.disconnect();
PRI_Erro = "ERRO012: Método DownloadToURL()";
return false;
}
}catch (Exception e) {
PRI_Erro = "ERRO013: Método DownloadToURL(): " + e.getMessage();
return false;
}
}