In this post, you will learn about AsyncTask with a simple Android AsyncTask example. At last, you can download it too.
Contents
- Introduction
- What is AsyncTask in Android?
- How to use AsyncTask in your project
- Create a subclass of AsyncTask>
- Override doInBackground() and other methods.
- onPreExecute()
- doInBackground(Params… params)
- publishProgress()
- onProgressUpdate(Progress… progress)
- onCancelled(Result result) and onCancelled()
- Make an instance of AsyncTask subclass & call execute()
- How to cancel AsyncTask
- AsyncTask’s Status
- Android AsyncTask Example
Introduction
Have you ever feel your app or downloaded one
- Lazy to perform
- Not responding to user inputs
- No smooth UI update
And at last, leads to Application not responding (ANR) dialog ???
Why is this happening?
As a matter of fact, Your application performs a too much intensive task on UI thread, at the same time it takes time to complete. For the sake of user convenience, the Android system will show you ANR dialog and stop your app forcefully.
In more detail, When the app gets started execution, Main thread or UI thread gets created. By default, all lifecycle methods like onCreate(,onStart(), and onClick, UI update works are serially done by UI thread. But When app developer put complex operations like
-
- Network operations.
- Disk I/O tasks.
- Database Queries.
- Other CPU intensive actions.
The app needs more time to perform. So at that time UI thread can’t update or repaint user interface. App freezes, operations exceeds the definite time fixed by the Android system. finally, the system decides to kill the application to make the device available to the user for other acts.
For making a neat and smart app, you should avoid all complex scenarios performing on UI thread.
Then what to do??
Where do we put our code to gets executed ??
You can use threads.
While performing these operations, You should notify the user through UI that something is happening behind. Otherwise, the user doesn’t know what is happening in your app. But you can’t perform any UI updations from your threads, that job is done by one and only Main Thread or UI thread. Then how could we use the main thread to notify the user?
Hello, is there any solution?
Yes, For beginners, use AsyncTask.
What ??
AsyncTask.
Full name, please??
Android.os.AsyncTask
nice name.. Carry on.
AsyncTask is just like a side road, while large-slowly moving truck makes traffic problem on the main road, Asynctask keeps those away to make a better path for other traffic.
For beginners, It’s the first and one of the best option for performing difficult work.
Okay… find out more about AsyncTask.
- Ultimate Guide: RecyclerView In Android
- 4 Ways to make Android TextView Bold
- 9 Android WebView Example Tutorials that had gone way too far
- What is layout in Android?
What is AsyncTask in android?
AsyncTask name came from the asynchronous task. It is an abstract class and you can find it on Android SDK. It helps Android app developers to execute operations like
- Downloading and uploading files like JSON, XML, images, and small size other files.
.
You can’t perform network operations on main thread since Honeycomb – API level 11. The system will throw android.os.NetworkOnMainThreadException. However, you must use AsyncTask or threads to perform network tasks. - Storing and reading data from large text files.
- All Database CRUD(create,read,update,delete) operations.
- Other CPU intensive operations.
In background or worker thread. Same time helps to update UI on UI thread. Asynctask makes use of UI thread in a better manner.
It eases the tension of developers from
- Thread creation and termination.
- UI thread synchronization and management.
How to use AsyncTask in your project
In this part, I will explain in more detail.
First of all, If you
- do not know how much time needed for your task or task takes a long time
- Want to perform an infinite loop work
AsyncTask is not a better option for you. AsyncTask mostly used for short operations(a few seconds at the most)
To make AsyncTask do work, we want to do 3 most important things.
1)Create a subclass of AsyncTask
2)Override doInBackground() and other methods.
3) Make an instance of AsyncTask subclass & call execute().
1)Create a subclass of AsyncTask
For performing different types of data operations, AsyncTask uses generics. So while making a subclass of AsyncTask, you must specify 3 generic data types.
Params, Progress, Result
1)Params: data used to start background thread execution.
For example, AsyncTask downloading an image file using URL, then specify URL as params.
2) Progress: data that used to notify progress of the task.
While downloading an image, You want to show the user how much percentage of the image has been downloaded. So you can use Integer as Progress.
3)Result : data that return from doInBackground() after execution.
For the same image downloading example, you can use Bitmap if doInBackground() code returns an image.
e.g:
Class Subclass_Name extends Asynctask
In real,
Class MyTask extends AsyncTask
What if you do not want to
- Pass parameters to doInBackground()?
- Show progress to the user?
- Return any result?
You can use Void data type just like other.
Class MyTask extends AsyncTask
Do not use primitive data types as parameters.
Class MyTask extends AsyncTask
This is wrong.
2) Override doInBackground() and other methods
onPreExecute()
Optional. It calls before task executes on the background thread and you can use it to set up a task. It runs on UI thread, so you can access UI elements here. In most cases, the app performs the animation or set visible ProgressBar or ProgressDialog.
doInbackground(Params… params)
Most important method in AsyncTask, After the successful completion of onPreExecute() it leads to doInBackground(). It does all intensive tasks in the background thread. It receives parameters as var args. Varargs means a variable number of arguments(like an array of elements), it can receive a number of parameters. You can access each element using an index just like the array.
.
While performing a repetitive task, you can publish it progresses through onProgressUpdate using publishProgress(). Which data type returns from doInBackground(), that type must be the parameter of onPostExecute().
If you use AsyncTask only for implementing doInBackground(), Use java threads.
publishProgress()
This method is used to connect and pass data from doInbackground() to onProgressUpdate(). Just like a bridge.
onProgressUpdate(Progress… progress)
Optional. It also uses varargs as parameters. It runs on UI thread, so you can use this method to notify task’s progress.
For example. If your app downloading lots of images. There may be a chance to user gets bored. So you can publish each photo to the user through onProgressUpdate(). That must be a great relief to the user.
The progress won’t directly be published on Main Thread. It uses handler internally bound to Main thread looper for execution. If there is lots of work in the Main Thread, progress will not update smoothly.
onPostExecute(Result result)
This is also optional and runs on the Main thread. It’s the most used second method in Asynctask. After successful completion of doInBackground, onpostExecute() starts with result from doInBackground. In some cases, this method uses to stop animation or hide progress bar that you started in onPreExecute().
onCancelled(Result result)
Optional and runs on the Main thread. It invokes only when the cancel() method is called with the instance of AsyncTask subclass. It will not invoke if doInBackground completes. After its completion, it will assign control to onCancelled() with no parameters. Override onCancelled() when nothing returns from doInBackground(). Use this to avoid checking data is null or not.
You can make different UI appearance for successful and fail completion by using onPostExecute() and onCancelled().
Note: Do not call these methods manually, you can. But don’t.
These methods are callbacks except publishProgress, they will invoke automatically by the system at an appropriate time.
3)Make an instance of AsyncTask subclass & call execute()
Android provides 2 methods to start AsyncTask.
1) execute (Params… params)
2) executeOnExecutor (Executor exec, Params… params), added in API level 11.
Call these methods using an instance of the AsyncTask subclass. doInBackground get their parameter data from these methods.
When AsyncTask added at first, execute method preferred serial execution. Later, means API level 4 android engineers change their decision to execute in parallel and it continues to level 12. With the introduction of executeOnExecutor() at API level 11, they give concurrency control to the developer. The app developer can decide how to execute our task in serial or parallel.
Two Executor parameter determines concurrency:
1.SERIAL_EXECUTOR: This executor parameter uses for performing a serial execution, they start each task after completing one by one. They promise that each task will complete in the order they were started or added. Just like a Queue.
Asynctask_subclass_instance.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR,Params);
2.THREAD_POOL_EXECUTOR: You can pass this executor object to perform a parallel execution, they do not give you any guarantee to complete the task in the order they were started. Asynctask will start as soon as possible when they get a thread from the thread pool
Asynctask_subclass_instance.executeOnExecutor(Asynctask.THREAD_POOL_EXECUTOR,params);
Due to issues in parallel execution, at API level 13, execute() set back to serial execution.
Both these codes have the same meaning from API level 13
Asynctask_subclass_instance.execute(Params ..) Asynctask_subclass_instance.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR,Params params)
Note: execute() must be invoked on the UI thread and task instance must be created on UI thread
Just like threads, AsyncTask executes only once. If you try to execute more than once with the same reference to AsyncTask subclass you will end with an exception with message Cannot execute task: the task has already been executed (a task can be executed only once)
If you try to execute the same task with the same reference to AsyncTask subclass while it running another exception will be thrown with the message “ Cannot execute task: the task is already running.
MyTask myTask=new MyTask(); myTask.execute(); myTask.execute();
So don’t do this.
If you want to execute the same AsyncTask more than once, just create a new instance and call execute.
new MyTask().execute();
How to cancel AsyncTask
What if the user selected a wrong option and want to cancel a running task?
AsyncTask provides a better cancellation strategy, to terminate currently running task.
cancel(boolean mayInterruptIfitRunning)
myTask.cancel(false)- It makes isCancelled returns true. Helps to cancel the task.
myTask.cancel(true) – It also makes isCancelled() returns true, interrupt the background thread and relieves resources .
It is considered as an arrogant way, If there is any thread.sleep() method performing in the background thread, cancel(true) will interrupt background thread at that time. But cancel(false) will wait for it and cancel task when that method completes.
If you invoke cancel() and doInBackground() hasn’t begun execute yet. onCancelled() will invoke.
After invoking cancel(…) you should check value returned by isCancelled() on doInbackground() periodically. just like shown below.
protected Object doInBackground(Params… params) { while (condition) { ... if (isCancelled()) break; } return null; }
AsyncTask’s Status
Asynctask tells their current state by giving below status.
1. PENDING: In this state, AsyncTask is not started, execute or executeOnExecutor() is not invoked. But you have created an AsyncTask instance.
2. RUNNING: Asynctask started their job, it will remain in this state from onPreExecute to onPostExecute or onCancelled.
3. FINISHED : This state will set when onPostExecute() or onCancelled() is completed.
you can check these statuses by calling getStatus() method using asynctask instance.
Android AsyncTask Example
Let’s make an application and familiar with Asynctask.
Step 1
Create a new project
In Android Studio, File->New Project
Application Name: AsyncTaskEx
Company Domain: androidride.com
Click Next
Step 2
Select the form factors and minimum SDK
tick the phone and tablet checkbox and choose API 15: Android 4.0.3(IceCream Sandwich) and click Next
Step 3
Select Empty Activity template
For this project, we just need an empty activity template. So just select the empty activity template and click Next.
Step 4
Create a new empty activity and layout
Next screen prompt for making an activity class file and its layout.
Activity Name: MainActivity
Tick the generate the layout checkbox if it’s not checked. Click finish.
Step 5
open activity_main.xml and put the code shown below.
The layout code will add a button and textview, button executes AsyncTask.
Step 6
open MainActivity.java and put the code shown below
When you click on the button, it will trigger AsyncTask and TextView will update in each second.
package com.androidride.asynctaskex; import android.os.AsyncTask; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { Button button; TextView textview; String messages[]={"Hi","Hellooooo..","How are you","Heyyyy","Why didn't you reply to me"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //initializing Button and TextView button=(Button)findViewById(R.id.button); textview=(TextView)findViewById(R.id.textview); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //create instance of asynctask subclass MyTask myTask= new MyTask(); //start asynctask myTask.execute(1000); } }); } class MyTask extends AsyncTask<Integer,String,Boolean> { /* Params: 1000 : Integer Progress: message content : String Result: true : Boolean */ @Override protected void onPreExecute() { //setting text textview.setText("Chatting started"); } @Override protected Boolean doInBackground(Integer... params) { for(int i=0;i<5;i++) { //sending data to onProgressUpdate() publishProgress(messages[i]); //background thread sleep for 1 second SystemClock.sleep(params[0]); } return true; } @Override protected void onProgressUpdate(String... progress) { //setting text textview.setText(progress[0]); } @Override protected void onPostExecute(Boolean result) { //checking result is true or not if(result) textview.setText("blocked"); } } }
Run Now…
Download Android AsyncTask Example – androidride.com
Please share this post & your precious comments will help us to improve.