Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you have two AsyncTasks in one Activity?

I have already developed an Activity which will parse JSON data and display the results in a ListView. I am using an AsyncTask for this purpose.

What I want now is that, when I click on an item in the ListView, the file should start downloading. Can I write another AsyncTask in the same activity so that this AsyncTask will do the downloading work for me? Is there any problem with having multiple AsyncTasks in the same activity?

like image 348
Mukund Avatar asked Mar 09 '15 07:03

Mukund


People also ask

How run two Async tasks in one activity?

If you want to run multiple AsyncTasks in parallel, you can call executeOnExecutor(AsyncTask. THREAD_POOL_EXECUTOR) instead of execute() on your task. By default, AsyncTasks run in serial, first come first serve.

Can we run multiple async task at a time?

There is a limit of how many tasks can be run simultaneously. Since AsyncTask uses a thread pool executor with limited max number of worker threads (128) and the delayed tasks queue has fixed size 10, if you try to execute more than 138 your custom tasks the app will crash with java.

Why is AsyncTask deprecated?

This class was deprecated in API level 30. AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.

What is AsyncTask used for?

In Android, AsyncTask (Asynchronous Task) allows us to run the instruction in the background and then synchronize again with our main thread. This class will override at least one method i.e doInBackground(Params) and most often will override second method onPostExecute(Result).


Video Answer


2 Answers

As per from the Doc yes you can.

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.

BEst answer How is itself on stackoverflow.

like image 143
squiroid Avatar answered Oct 22 '22 16:10

squiroid


There shouldn't be any problem with multiple Asynctasks in a single activity. You should be careful to clearly define the values that each one manipulates (for example, if task B relies on a value given by task A, make sure that A must finish first), but in general, it should be fine. I have a project right now with three asynctasks running upon first install, and it's ticking along fine thus far.

like image 41
Matter Cat Avatar answered Oct 22 '22 14:10

Matter Cat