Search code examples
androidmultithreadingthreadpoolthreadpoolexecutor

How to stop the task running in a Thread Pool Executor Android


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?


Solution

  • 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);
        }
    }