I am trying to download a 600 MB file using an AsyncTask. If I execute my code on a real-world device, it works, but only if I "keep an eye on it" by not allowing the screen to remain off for any length of time, however, if I do not do this and just leave the device on its own, when I go to check on it a few minutes later, the progress dialog is gone and the file it has downloaded is only a fraction of the size it should be. My guess it that it has something to do with the phone putting WiFi to sleep after the screen's being off for a certain amount of time.
How do I fix this?
Here is the relevant code:
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/file.zip");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}