2

I have an async task in my project like the one below.

@SuppressLint("NewApi")

private void callTask() {

    new Task() {

      @Override
      protected void doInBackground(String... params) {

      }
     }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                string1,string2 );
   }

and I call this callTask() method inside a for loop for 10 times.

My tasks are getting executed parallely and it works fine. I want to stop all the task at one point of time. How can I achieve this?

Hariharan
  • 24,741
  • 6
  • 50
  • 54
ydnas
  • 519
  • 1
  • 12
  • 29
  • I have seen some posts related. [Not being Cancelled](http://stackoverflow.com/questions/11165860/asynctask-oncancelled-not-being-called-after-canceltrue) and [Ideal Way to cancel asynctask](http://stackoverflow.com/questions/2735102/ideal-way-to-cancel-an-executing-asynctask) – UrielUVD Apr 29 '14 at 05:19

1 Answers1

6

You need to save the instance of the each Task (Asynchronous Task) in a ArrayList or any other structure and add your Task object to it

please check following code :

private ArrayList<Task> array_task = new ArrayList<Task>();
private void callTask() {
    Task task = new Task() {
        @Override
        protected void doInBackground(String... params) {

        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                string1,string2 );
    array_task.add(task);
}

And after when you want to cancel all task you need a for loop again to cancel all check following code

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.cancel_all_task:
            callCancel_AllAsyncTask();
            break;

    }
}

private void callCancel_AllAsyncTask()
{
    for(int i=0;i<array_task.size();i++)
    {
        array_task.get(i).cancel(true);
    }
}
Gary Chen
  • 248
  • 2
  • 14
Sandy
  • 985
  • 5
  • 13