In one activity I have three AsyncTask objects AsyncTask

 final ContentLoadTask initializeAct = new ContentLoadTask(this); initializeAct.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); final GetImagesUrlTask imagesUrlTask = new GetImagesUrlTask(this); imagesUrlTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); final GetComments getCommentsTask = new GetComments(this); getCommentsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); 

one of which calls the function

 public void RetrieveImages(String... urls) { for (String url : urls) { PhotoRetrieveTask task = new PhotoRetrieveTask(this); task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, url); } } 

Is it possible to do that? Is this technically correct? And the third getCommentsTask does not execute doInBackground

Plus, I read that cancel() does not always work correctly, but since I understand, you need to terminate the thread manually after it does what I need. And then the threads limit will be released and the last, third thread will be executed.

    1 answer 1

    Call the task in the task is not worth it. Tasks are designed to work outside the UI stream. And there is no point in launching a task from a task in this regard. Most likely there are problems.

    In most cases, you do not need to manually complete the task yourself. If you have a lot of things that need to be iteratively and sequentially performed outside the UI stream, then you better take out all this in the IntentService and call the onHandleIntent Service method instead of calling several tasks.

    so you do not have to deal with the nuances of the outdated AsyncTask-a + you can easily stop all processes if you correctly configure the distribution of intents for the service.

    • That is, now practice 'intentService' more than 'AsyncTask' and you can safely switch to it? Will there be problems with older versions of Android? API 15 for example - Herrgott
    • In general, it is better to forget about async. services are needed more for tasks when it is necessary to work without activi. try loaders to use. In your case, AsyncTaskLoader will work - andreich
    • @andreich, with my loaders in my experience, too, the trouble ... I did not manage to figure out all the nuances) As a result, I use RoboSpice or IntentService. Well, AsyncTask for simple tasks, scoring on the turns of the screen and relying on the caching of query results on your own. - Yuriy SPb
    • And something I could not find the pre and post functions in the UI stream for intentService to output progress bars - Herrgott
    • @Herrgott, well, here you can somehow pervert through rxJava or EventBus or Otto. Well, or really try to pick AsyncTaskLoader. Also, using the service, the progress bar you can even show in the notification, instead of the UI .. - YuriSPb