您不能重复执行 AsyncTaskbut您可以重复它执行的操作。
我已经制作了这个小帮助程序类,您可能希望扩展它来代替 AsyncTask,唯一的大区别是您将使用 RepeatInBackground 而不是 doInBackground,并且 onPostExecute 将有一个新参数,最终抛出异常。
RepeatInBackground 中的任何内容都将自动重复,直到结果不同于 null / 不抛出异常并且少于 maxTries。
循环内抛出的最后一个异常将在 onPostExecute(Result, Exception) 中返回。
您可以使用 RepeatableAsyncTask(int retries) 构造函数设置最大尝试次数。
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);
}
}