我正在尝试从 URL 下载文件。如果下载失败(不管是什么原因),我希望应用程序在一个小时后重试。
由于下载是在它自己的线程中(不是主线程),我似乎无法启动一个新的 CountDownTimer。
我不想阻止下载线程,所以我正在尝试使用 CountDownTimer。
还有另一种方法可以做到这一点吗?
提前致谢!
private class Downloader extends AsyncTask<Object, Void, File>
{
@Override
protected File doInBackground(Object... params)
{
Context context = (Context) params[0];
String strUrl = (String) params[1];
String strFileName = (String) params[2];
return download(context, strUrl, strFileName);
}
/**
* Downloads files in a separate thread. Adds notification of download to status bar.
*/
public File download(final Context context, final String url, final String fileName)
{
boolean isVideoLoaded=false;
try
{
URL urlObj = new URL(url);
URLConnection con = urlObj.openConnection();
BufferedInputStream bis = new BufferedInputStream(con.getInputStream(), BUFFER_SIZE);
FileOutputStream fos = new FileOutputStream(retFile);
byte[] bArray = new byte[BUFFER_SIZE];
int current = 0;
int read = 0;
while(current != -1)
{
fos.write(bArray,0,current);
current = bis.read(bArray, 0, BUFFER_SIZE);
read = read + current;
}
fos.close();
bis.close();
isVideoLoaded = true;
strFileName = retFile.getAbsolutePath();
}
catch(Exception ioe)
{
Log.d("Downloader.download", "Error: " + ioe.toString(), ioe);
}
}
if (!isVideoLoaded) // if video is still not loaded
{
// sleep then try again
new CountDownTimer(15000, 2000)
{
public void onFinish()
{
Downloader dh = new Downloader();
Object params[] = new Object[3];
params[0] = context;
params[1] = url;
params[2] = fileName;*/
dh.execute(params);
}
@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
}
}.start();
}
return retFile;
}
protected void onPostExecute(File file) {
// display downloaded file
}