Android Asynctask Example Tutorial

By Sanjeev K. Saroj, 02 April,2017  

This tutorial is about creating AsyncTask in android applications. In this article we will discuss about what is AsyncTask, how AsyncTask works in android application and develop an example application using AsyncTask that performs an abstract AsyncTask in background.

what is AsyncTask

AsyncTask is an abstract class provided by Android which enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around thread and Handler and does not constitute a generic threading framework. An AsyncTask name implies,executes a task asynchronously. The AsyncTask is a generic class that takes 3 types of arguments. - AsyncTask <Params, Progress, Result>

Params - the type that is passed into the execute() method.

Progress - the type that is used within the task to track progress.

Result - the type that is returned by doInBackground().

The type of the arguments passed when starting the task, the type of arguments returned to the caller when reporting progress, and the type of the result.

Different AsyncTask Stages

AsyncTask will go through the following 4 stages:

onPreExecute():- It is invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface. This is also used to create dialog box and carry out initialization.

doInBackground(Params...):-The main purpose of AsyncTask is accomplished by this method. Any non-UI thread process is running in this method such as Rss Feed Reader,Image and video Uploading and Downloading. You cant handle your View in this method because this method is non-UI thread.

While any background process is running if you want to handle UI there are onProgressUpdate() method. After completion of process this method send result to OnPostExecute. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

onProgressUpdate(Progress...):- It is invoked on the UI thread after a call to publishProgress(). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

onPostExecute(Result):- It is invoked on the UI thread after the background computation finishes to process final data returned by doInBackgroundThe result of the background computation is passed to this step as a parameter.

AsyncTask LifeCycle

There is quite a misunderstanding about our AsyncTask. Developers might think that when the Activity that created the AsyncTask has been destroyed, the AsyncTask will be destroyed as well. This is not the case. The AsyncTask keeps on running, doing his doInBackground() method until it is done. Once this is done it will either go to the onCancelled(Result result) method if cancel(boolean) is invoked or the onPostExecute(Result result) method if the task has not been cancelled.

Suppose our AsyncTask was not cancelled before our Activity was destroyed. This could make our AsyncTask crash, because the view it wants to do something with, does not exist anymore. So we always have to make sure we cancel our task before our Activity is destroyed.

The cancel(boolean) method needs one parameter: a boolean called mayInterruptIfRunning. This should be true if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete. If there is a loop in our doInBackground() method, we might check the boolean isCancelled() to stop further execution. So we have to make sure the AsyncTask is always cancelled properly.

Android AsyncTask Example

Create an empty project in Android Studio. Create a class MyAsyncTask which extends AsyncTask , and override all methods. Following is the project structure.

android-asyncTask-project-strct

Defining activity_main.xml

activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.devglan.asynctask.MainActivity"> <Button android:id="@+id/btn_start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start AsyncTask" android:textAllCaps="false"/> <ImageView android:id="@+id/sourceImageView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="30dp" android:layout_below="@+id/btn_start"/> </RelativeLayout>

This activity is basically to interact with user.In this activity we have given two url to call AsyncTask.

Defining MainActivity.java

MainActivity.java
import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import java.io.InputStream; public class MainActivity extends AppCompatActivity { Button btn_start; String url = "http://www.devglan.com/image/dashboard.jpg"; String url1 = "http://i.imgur.com/jeuhNQz.png"; ImageView sourceImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn_start= (Button) findViewById(R.id.btn_start); sourceImageView= (ImageView) findViewById(R.id.sourceImageView); btn_start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new MyAsyncTask().execute(url1); } }); } private class MyAsyncTask extends AsyncTask{ ProgressDialog progressDialog; @Override protected Bitmap doInBackground(String... strings) { String urldisplay = strings[0]; Bitmap bitmap = null; publishProgress(0); try { InputStream in = new java.net.URL(urldisplay).openStream(); bitmap = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return bitmap; } @Override protected void onProgressUpdate(Integer... values) { } @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); progressDialog.dismiss(); if(bitmap != null){ sourceImageView.setImageBitmap(bitmap); } } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = ProgressDialog.show(MainActivity.this, "Downloading", "Downloading..Please Wait", true); } } }

Defining AndroidManifest.xml

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.devglan.asynctask"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
NOTE:-Don't forgot to give INTERNET permission in android studio.

Following is the final screen.

android-asynctask-example

Conclusion

I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Download Source for AsyncTask

References:

Android Developer AsyncTask References

Suggest more topics in suggestion section or write your own article and share with your colleagues.

Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.

Further Reading: