我有一個類似的問題 - 因爲HttpUrlConnection won't time out中下載。例如,如果您在下載時關閉wifi,我的繼續說它正在下載,卡住的比例相同。
我找到了一個解決方案,使用TimerTask連接到名爲DownloaderTask的AsyncTask。嘗試:
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);
}
};
然後在實際下載循環設置超時錯誤定時器:
_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();
如果超時,並且不會在20秒內連1K下載,它取消,而不是似乎永遠下載。
有兩件事情你考慮的IPS。如果您不想讓應用掛起,請將連接方法放在單獨的線程中。其次,你說它「完美」工作,你在做什麼來模擬不良連接? – Otra
@Otra我在使用progressdialog的單獨線程中擁有它。基本上發生的事情是,如果連接良好,那麼任務完成它的事情。但是如果連接不好,progressdialog會保持很長時間。爲了模擬一個不好的連接,我減少了超時時間。而不是給它15秒,1秒。只是爲了測試。或者那是錯的? –
HttpURLConnection.setReadTimeout(mili sec); –