[英]How to check if there is any background task running?
I have an activity in android that is getting data from server using AsyncTask, I'm running the task like the following: 我在android中有一个活动,该活动使用AsyncTask从服务器获取数据,我正在运行以下任务:
new Task.exectue();
The problem is there are multiple calls to this AsyncTask and I want to cancel all of them when onDestroy
or onBackPressed
called, how can I achieve that? 问题是有多个对此AsyncTask的调用,当
onBackPressed
调用onDestroy
或onBackPressed
时,我想取消所有这些调用,如何实现呢? or as another soultion how can I check if there are any background tasks running in activity? 还是作为另一个灵魂,我如何检查活动中是否正在运行任何后台任务?
By Default AsyncTask
executes many tasks serially. 默认情况下,
AsyncTask
串行执行许多任务。 That means that when the first task finishes it starts the next one and so on. 这意味着当第一个任务完成时,它将开始下一个任务,依此类推。 What you can do is
你能做的是
Global Variable: 全局变量:
private Task myTask;
Method: 方法:
public void accessWebService(){
myTask = new Task().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "Param 1");
}
and then in onDestroy
cancel the Task. 然后在
onDestroy
取消任务。
how can I check if there are any background tasks running in activity? 如何检查活动中是否正在运行任何后台任务? :
:
boolean isTaskRunning = asyncTaskObj.getStatus().equals(AsyncTask.Status.RUNNING) ;
If you want to cancel that task then use below code : 如果要取消该任务,请使用以下代码:
asyncTaskObj.cancel(true);
Have a list of your Tasks and when you want to cancel them just iterate through list and call .cancel() on every task : 列出您的任务,要取消它们,只需遍历list并在每个任务上调用.cancel()即可:
private ArrayList<Task> mTasks = new ArrayList<>();
Each time you want to execute your AsyncTask, add the instance to your list : 每次您要执行AsyncTask时,请将实例添加到列表中:
mTasks.add(new Task.exectue());
At the end of your onPostExecute() method of your Task, remove it from your list : 在Task的onPostExecute()方法末尾,将其从列表中删除:
@protected void onPostExecute(Long result) {
...
mTasks.remove(this);
}
Finally in your onDestroy() method, cancel all running AsyncTask : 最后,在您的onDestroy()方法中,取消所有正在运行的AsyncTask:
@Override
onDestroy() {
for(Task task : mTasks) {
if(task.getStatus().equals(AsyncTask.Status.RUNNING)) {
task.cancel(true);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.