When ever we try to implement a background task we need to implement it properly using a async task. In this tutorial we will discuss a simple example on android asynctask.
It’s a simple example to cover the concept of android asynctask by making use of a “Log” conditions.To make it much simple for even a beginner to understand what’s happening.
Android asynctask
Let us create a sample project and add a layout for it.
activity_test.xml
Let us declare a button by which we will call a async class on button click
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center"> <Button android:id="@+id/btn_click" android:layout_width="100dp" android:layout_height="wrap_content" android:text="Async"/> </LinearLayout>
MainActivity.java
Now add the java code for android asynctask
Async Task contains four modules
- onPreExecute
- doInBackground
- onProgressUpdate(optional)
- onPostExecute
onPreExecute:
This method is invoked before android asynctask is started.We declare progress dialog here to alert user regarding the task going on in background.
doInBackground:
As per the name it does the work in background which gets executed immediately after onPreExecute.It might take some time for the computations to finish in this method. And the progress can be declared by using the third method i.e., onProgressUpdate.
onProgressUpdate(Optional):
This method gets called when publish Progress is called. It updates the user interface by showing the status in form of a progress bar or any other form while computation is running in background state.
Its again a optional method which can be used or not but its a good practice to make use of the feature and make user get to know the status of the work completed.
Example:
Downloading a song or file we might be having the use of this android asynctask because of the size of the file it might take more time and user needs to have a progress with details of the process.
onPostExecute:
This is the final step / method of async task which is invoked after completion of task i.e., background computation.
And the final result is shown to the user.
A basic implementation is show as
private final class Async extends AsyncTask<Void,Void,String>{ @Override protected void onPreExecute() { super.onPreExecute(); Log.d("async"," 1 "); } @Override protected String doInBackground(Void... voids) { Log.d("async"," 2 "); publishProgress(); return null; } @Override protected void onProgressUpdate(Void... values) { super.onProgressUpdate(values); Log.d("async"," 3 "); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Log.d("async"," 4 "); } }
Now we will see how to call this async method
Initialize the button you may also use databinding here
Button btnClick = findViewById(R.id.btn_click);
then initialize the android asynctask class and with the help of object we will call
final Async async = new Async();
calling the class as
async.execute();
btnClick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { async.execute(); } });
import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import com.abhishekapps.abhishek.mvvm.R; public class TestActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); Button btnClick = findViewById(R.id.btn_click); final Async async = new Async(); btnClick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { async.execute(); } }); } private final class Async extends AsyncTask<Void,Void,String>{ @Override protected void onPreExecute() { super.onPreExecute(); Log.d("async"," 1 "); } @Override protected String doInBackground(Void... voids) { Log.d("async"," 2 "); publishProgress(); return null; } @Override protected void onProgressUpdate(Void... values) { super.onProgressUpdate(values); Log.d("async"," 3 "); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Log.d("async"," 4 "); } } }
Output:
The output depicting android asynctask flow
If you have any query in this tutorial on android asynctask do let us know in the comment section below.If you like this tutorial do like and share us for more interesting updates.