gpt4 book ai didi

android - 重复异步任务

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:40:42 24 4
gpt4 key购买 nike

我怀疑在 Android 应用程序中重复 AsyncTask 的可能性。我想重复一些操作,例如从服务器下载文件,如果由于某些原因无法下载文件,则重复 n 次。有快速的方法吗?

最佳答案

您不能重复 AsyncTask 您可以重复它执行的操作。

我制作了这个您可能想要扩展的小助手类来代替 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);
}
}

关于android - 重复异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18359039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com