asynctask in android with example - androidride.com

In this post you will learn about AsyncTask in Android. At last you can download the example too.

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, 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 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 - The Beginner's Guide : AsyncTask in Android tutorial with Example

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.

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

how to use asynctask in your application or project - androidride
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 that 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,

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.

Do not use primitive data types as parameters.

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 will perform 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 task in the background thread. It receives parameters as varargs. 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 index just like the array.
.

While performing a repetitive task, you can publish it’s progress 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 an 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 published on Main Thread. It uses handler internally bound to Main thread looper for execution. If there is lots of work in Main Thread, progress will not update smoothly.

onPostExecute(Result result)

This is also optional and runs on 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 Main thread. It invokes only when 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 exept publishProgress, they will invoke automatically by the system at 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 that 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.

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

Due to issues in parallel execution, at API level 13, execute() set back to serial execution.

Both these codes have same meaning from API level 13

Note: execute() must be invoked on UI thread and task instance must be created on UI thread

Just like threads, asynctask execute 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.

So don’t do this.

If you want to execute the same asynctask more than once, just create a new instance and call 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 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.

AsyncTask’s Status

asynctask status - Asynctask in adnroid with example - androidride.com

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.

Simple 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 button, it will trigger asynctask and textview will update in each second.

Run Now…

asynctask-example-project---asynctask-in-android---androidride


Download AsyncTask Example – androidride.com

For more about AsyncTask

Please share this post & your precious comments will help us to improve.