the type of the parameters sent to the task upon execution.
the type of the progress units published during the background computation
the type of the result of the background computation.
AsyncTask: Serial Execution and Parallel Execution of Task
AsyncTask is an abstract Class and does not inherit the Thread class. It has an abstract method doInBackground(Params... params), which is overridden to perform the task. This method is called from AsyncTask.call().
Executor are part of java.util.concurrent package.
Moreover, AsyncTask contains 2 Executors
It uses worker threads to execute the tasks parallelly.
It executes the task serially, i.e. one by one.
Both Executors are static, hence only one THREAD_POOL_EXECUTOR and one SerialExecutor objects exist, but you can create several AsyncTask objects.
Therefore, if you try to do multiple background task with the default Executor (SerialExecutor), these task will be queue and executed serially.
If you try to do multiple background task with THREAD_POOL_EXECUTOR, then they will be executed parallelly.
Perform Click on button several times to start a task and see the result.
Task Executed in thread pool(1)
Each task takes 1000 ms to complete.
At t=36s, tasks 2, 3 and 4 are queued and started executing also because they are executing parallelly.
Comment Task Executed in thread pool (1) and uncomment Task executed Serially (2).
Perform Click on button several times to start a task and see the result.
It is executing the task serially hence every task is started after the current task completed execution.
Hence when Task 1's execution completes, only Task 2 starts running in background. Vice versa.
In Android Activities and Services, most callbacks are run on the main thread. This makes it simple to update the UI, but running processor- or I/O-heavy tasks on the main thread can cause your UI to pause and become unresponsive (official documentation on what then happens).
You can remedy this by putting these heavier tasks on a background thread.
One way to do this is using an AsyncTask, which provides a framework to facilitate easy usage of a background Thread, and also perform UI Thread tasks before, during, and after the background Thread has completed its work.
Methods that can be overridden when extending AsyncTask:
onPreExecute() : invoked on the UI thread before the task is executed
doInBackground(): invoked on the background thread immediately after onPreExecute() finishes executing.
onProgressUpdate(): invoked on the UI thread after a call to publishProgress(Progress...).
onPostExecute(): invoked on the UI thread after the background computation finishes
When defining an AsyncTask we can pass three types between < > brackets.
Defined as <Params, Progress, Result> (see Parameters section)
In the previous example we've used types <File, Void, String>:
Void is used when you want to mark a type as unused.
Note that you can't pass primitive types (i.e. int, float and 6 others) as parameters. In such cases, you should pass their wrapper classes, e.g. Integer instead of int, or Float instead of float.
The AsyncTask and Activity life cycle
AsyncTasks don't follow Activity instances' life cycle. If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes.
One subclass of Loaders is the AsyncTaskLoader. This class performs the same function as the AsyncTask, but much better. It can handle Activity configuration changes more easily, and it behaves within the life cycles of Fragments and Activities. The nice thing is that the AsyncTaskLoader can be used in any situation that the AsyncTask is being used. Anytime data needs to be loaded into memory for the Activity/Fragment to handle, The AsyncTaskLoader can do the job better.
This doesn't stop your task if it was in progress, it just sets the cancelled flag which can be checked by checking the return value of isCancelled() (assuming your code is currently running) by doing this:
If an AsyncTask is canceled while doInBackground(Params... params) is still executing then the method onPostExecute(Result result) will NOT be called after doInBackground(Params... params) returns. The AsyncTask will instead call the onCancelled(Result result) to indicate that the task was cancelled during execution.
Download Image using AsyncTask in Android
This tutorial explains how to download Image using AsyncTask in Android. The example below download image while showing progress bar while during download.
Understanding Android AsyncTask
Async task enables you to implement MultiThreading without get Hands dirty into threads. AsyncTask enables proper and easy use of the UI thread. It allows performing background operations and passing the results on the UI thread. If you are doing something isolated related to UI, for example downloading data to present in a list, go ahead and use AsyncTask.
AsyncTasks should ideally be used for short operations (a few seconds at the most.)
An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute(), doInBackground(), onProgressUpdate() and onPostExecute().
In onPreExecute() you can define code, which need to be executed before background processing starts.
doInBackground have code which needs to be executed in background, here in doInBackground() we can send results to multiple times to event thread by publishProgress() method, to notify background processing has been completed we can return results simply.
onProgressUpdate() method receives progress updates from doInBackground() method, which is published via publishProgress() method, and this method can use this progress update to update event thread
onPostExecute() method handles results returned by doInBackground() method.
The generic types used are
Params, the type of the parameters sent to the task upon execution
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
If an async task not using any types, then it can be marked as Void type.
An running async task can be cancelled by calling cancel(boolean) method.
Downloading image using Android AsyncTask
your .xml layout
Since there is currently no comment field for examples (or I haven't found it or I haven't permission for it) here is some comment about this:
This is a good example what can be done with AsyncTask.
However the example currently has problems with
possible memory leaks
app crash if there was a screen rotation shortly before the async task finished.
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.
SERIAL_EXECUTOR -> An Executor that executes tasks one at a time in
THREAD_POOL_EXECUTOR -> An Executor that can be used to execute tasks in
Pass Activity as WeakReference to avoid memory leaks
It is common for an AsyncTask to require a reference to the Activity that called it.
If the AsyncTask is an inner class of the Activity, then you can reference it and any member variables/methods directly.
If, however, the AsyncTask is not an inner class of the Activity, you will need to pass an Activity reference to the AsyncTask.
When you do this, one potential problem that may occur is that the AsyncTask will keep the reference of the Activity until the AsyncTask has completed its work in its background thread. If the Activity is finished or killed before the AsyncTask's background thread work is done, the AsyncTask will still have its reference to the Activity, and therefore it cannot be garbage collected.
As a result, this will cause a memory leak.
In order to prevent this from happening, make use of a WeakReference in the AsyncTask instead of having a direct reference to the Activity.
Here is an example AsyncTask that utilizes a WeakReference:
Calling the AsyncTask from an Activity:
Calling the AsyncTask from a Fragment:
Sometimes, we need to update the progress of the computation done by an AsyncTask. This progress could be represented by a string, an integer, etc. To do this, we have to use two functions. First, we need to set the onProgressUpdate function whose parameter type is the same as the second type parameter of our AsyncTask.
Second, we have to use the function publishProgress necessarily on the doInBackground function, and that is all, the previous method will do all the job.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0