0

so I am coming across a weird problem I cant find an explaination for. I have an async task in which in its doBackground method does a wait until a certain variable is set then the "wait" is notified

private class TestAsyncTask extends AsyncTask<Void, Object, Boolean> {


        @Override
        protected void onPreExecute() {
              Log.d("Test1");
        }

        @Override
        protected Boolean doInBackground(Void... params) {
               Log.d("Test2");
               while (nextCardToPlay == null) {
        wait();             
       }
               Log.d("Test3");
       }
}

Activity A:

protected void onCreate(){
     a = new TestAsyncTask().execute();
}

protected void onPause(){
    a.cancel()
}

So as you can see when the activity starts, the asyncTask is started. When activity is closed the asyncTask is supposed to be cancelled.

What I noticed is that if I open the activity, close it, and reopen it again then the asynctask is created and in wait mode (never cancelled). No problem. Whats confusing is that when I start the activity (while the stale asyncTask is there), then it seems a new asyncTask is started ( because the logs from OnPreExecute are called) however the doInBackground in the nextAsyncTask is not executed because the Test2 log is not showing.

Any idea why?

Snake
  • 14,228
  • 27
  • 117
  • 250

1 Answers1

0

This behavior is not at all weird if you look at the documentation, which states the AsyncTasks run on a single background thread, i.e. sequentially. If you really want your tasks to run on parallel worker threads, then use the executeOnExecutor() method instead of a simple execute() and pass it the AsyncTask.THREAD_POOL_EXECUTOR parameter.

Egor
  • 39,695
  • 10
  • 113
  • 130
  • You are the best. PERFECT answer. I will try that. Now my other problem is cancelling the asynctask. I can just never make sure it is cancelled when my activity closes – Snake Mar 23 '14 at 00:36
  • Ego btw if I make use your methods, will the pool of asynctask stay at 5? so asynctask can get reusable or is there a downside for executeOnExecuter – Snake Mar 23 '14 at 01:08
  • @Snake, Regarding cancelling, refer to the Cancelling a task section of that article to see how you can optimize this procedure. – Egor Mar 23 '14 at 14:16