问题描述
我怀疑在 Android 应用程序中重复 AsyncTask 的可能性.我想重复一些操作,例如从服务器下载文件,如果由于某些原因无法下载文件n次.有没有一种快速的方法可以做到这一点?
I have a doubt about the possibility of repeating an AsyncTask in an application for Android. I would like to repeat some operations, the download of a file from a server for example, n times if it is impossible for some reasons download the file. There is a quick way to do this?
推荐答案
您不能重复 AsyncTask 但您可以重复它执行的操作.
You cannot repeat an AsyncTask but you could repeat the operations it executes.
我已经制作了这个小助手类,您可能想要扩展它来代替 AsyncTask,唯一的大区别是您将使用 repeatInBackground 而不是 doInBackground 并且 onPostExecute 将有一个新参数,最终抛出的异常.
I've made this little helper class that you might want to extend in place of AsyncTask, the only big difference is that you will use repeatInBackground instead of doInBackground and that onPostExecute will have a new parameter, the eventual Exception thrown.
repeatInBackground 中的任何内容都会自动重复,直到结果与 null 不同/不抛出异常并且小于 maxTries.
Anything inside repeatInBackground will be repeated automatically until result is different from null / exception is not thrown and there are been less than maxTries.
循环内最后抛出的异常会在onPostExecute(Result, Exception)中返回.
The last exception thrown inside the loop will be returned in the onPostExecute(Result, Exception).
您可以使用 RepeatableAsyncTask(int retries) 构造函数设置最大尝试次数.
You can set max tries using the RepeatableAsyncTask(int retries) constructor.
public abstract class RepeatableAsyncTask<A, B, C> extends AsyncTask<A, B, C> {
private static final String TAG = "RepeatableAsyncTask";
public static final int DEFAULT_MAX_RETRY = 5;
private int mMaxRetries = DEFAULT_MAX_RETRY;
private Exception mException = null;
/**
* Default constructor
*/
public RepeatableAsyncTask() {
super();
}
/**
* Constructs an AsyncTask that will repeate itself for max Retries
* @param retries Max Retries.
*/
public RepeatableAsyncTask(int retries) {
super();
mMaxRetries = retries;
}
/**
* Will be repeated for max retries while the result is null or an exception is thrown.
* @param inputs Same as AsyncTask's
* @return Same as AsyncTask's
*/
protected abstract C repeatInBackground(A...inputs);
@Override
protected final C doInBackground(A...inputs) {
int tries = 0;
C result = null;
/* This is the main loop, repeatInBackground will be repeated until result will not be null */
while(tries++ < mMaxRetries && result == null) {
try {
result = repeatInBackground(inputs);
} catch (Exception exception) {
/* You might want to log the exception everytime, do it here. */
mException = exception;
}
}
return result;
}
/**
* Like onPostExecute but will return an eventual Exception
* @param c Result same as AsyncTask
* @param exception Exception thrown in the loop, even if the result is not null.
*/
protected abstract void onPostExecute(C c, Exception exception);
@Override
protected final void onPostExecute(C c) {
super.onPostExecute(c);
onPostExecute(c, mException);
}
}
这篇关于重复异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!