下面列出了android.os.AsyncTask#getStatus ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 如果任务未执行完毕,则取消任务
*
* @param clazz Activity Class
*/
public void unregisterAsyncTask(Class<? extends BaseActivity> clazz) {
ArrayList<AsyncTask> tasks = new ArrayList<>(mTasks.removeAll(clazz));
int size = tasks.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
AsyncTask task = tasks.get(i);
//you may call the cancel() method but if it is not handled in doInBackground() method
if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) {
task.cancel(true);
}
}
}
}
/**
* Try to execute the supplied async task.
*
* @param asyncTask The async task to be executed.
*
* @see AsyncTask#execute(Object[])
*/
@SuppressWarnings("unchecked")
public static void executeTask(@Nullable AsyncTask asyncTask) {
try {
if (asyncTask != null && asyncTask.getStatus() != AsyncTask.Status.RUNNING) {
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[]) null);
}
} catch (Exception ignored) {
}
}
/**
* Try to cancel the supplied async task.
*
* @param asyncTask The async task to be cancelled.
*
* @see AsyncTask#cancel(boolean)
*/
public static void cancelTask(@Nullable AsyncTask asyncTask) {
try {
if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) {
asyncTask.cancel(true);
}
} catch (Exception ignored) {
}
}
public boolean addTask(String key, AsyncTask<?, ?, ?> task) {
synchronized (lock) {
if (runningTasks.containsKey(key)) {
AsyncTask<?, ?, ?> tempTask = runningTasks.get(key);
if (tempTask != null && tempTask.getStatus() != Status.FINISHED)
return false;
}
runningTasks.put(key, task);
return true;
}
}
/**
* Cancel an {@link AsyncTask}.
*
* @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
* task should be interrupted; otherwise, in-progress tasks are allowed
* to complete.
*/
public static void cancelTask(AsyncTask<?, ?, ?> task, boolean mayInterruptIfRunning) {
if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) {
task.cancel(mayInterruptIfRunning);
}
}