Reputation: 2482
I have an activity in android that is getting data from server using AsyncTask, I'm running the task like the following:
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? or as another soultion how can I check if there are any background tasks running in activity?
Upvotes: 1
Views: 1326
Reputation: 1543
Have a list of your Tasks and when you want to cancel them just iterate through list and call .cancel() on every task :
private ArrayList<Task> mTasks = new ArrayList<>();
Each time you want to execute your AsyncTask, add the instance to your list :
mTasks.add(new Task.exectue());
At the end of your onPostExecute() method of your Task, remove it from your list :
@protected void onPostExecute(Long result) {
...
mTasks.remove(this);
}
Finally in your onDestroy() method, cancel all running AsyncTask :
@Override
onDestroy() {
for(Task task : mTasks) {
if(task.getStatus().equals(AsyncTask.Status.RUNNING)) {
task.cancel(true);
}
}
}
Upvotes: 1
Reputation: 3260
By Default AsyncTask
executes many tasks serially. 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.
Upvotes: 2
Reputation: 1672
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);
Upvotes: 1