I had a similar problem - because the HttpUrlConnection won't time out mid-download. For example, if you turn off wifi when download is going, mine continued to say it is downloading, stuck at the same percentage.
I found a solution, using a TimerTask, connected to a AsyncTask named DownloaderTask. Try:
class Timeout extends TimerTask {
private DownloaderTask _task;
public Timeout(DownloaderTask task) {
_task = task;
}
@Override
public void run() {
Log.w(TAG,"Timed out while downloading.");
_task.cancel(false);
}
};
Then in the actual download loop set a timer for timeout-error:
_outFile.createNewFile();
FileOutputStream file = new FileOutputStream(_outFile);
out = new BufferedOutputStream(file);
byte[] data = new byte[1024];
int count;
_timer = new Timer();
// Read in chunks, much more efficient than byte by byte, lower cpu usage.
while((count = in.read(data, 0, 1024)) != -1 && !isCancelled()) {
out.write(data,0,count);
downloaded+=count;
publishProgress((int) ((downloaded/ (float)contentLength)*100));
_timer.cancel();
_timer = new Timer();
_timer.schedule(new Timeout(this), 1000*20);
}
_timer.cancel();
out.flush();
If it times out, and won't download even 1K in 20 seconds, it cancels instead of appearing to be forever downloading.