AsyncTask in Android: A Guide to Background Processing
Learn how to use Android AsyncTask to perform heavy tasks in the background and keep your app responsive. In this tutorial, we will show you step-by-step how to implement AsyncTask and relieve your user interface. Dive into the world of efficient background processing for Android apps!
What is Android AsyncTask?
Android AsyncTask is an abstract class that allows us to perform heavy tasks in the background while keeping the UI thread light and responsive. Android applications run on a single thread, which means that time-consuming tasks can cause the application to become unresponsive. To avoid this, we use AsyncTask to perform these tasks in the background and return the results to the UI thread.
Key Methods of the AsyncTask Class
- doInBackground(): Here the code is executed that should run in the background. The
publishProgress()
method can be used to send results to the UI thread multiple times. - onPreExecute(): This method is executed before the background processing begins.
- onPostExecute(): This method is called after the background processing is completed and receives the result from
doInBackground()
. - onProgressUpdate(): This method receives progress updates from
doInBackground()
, published throughpublishProgress()
.
Generic Types of the AsyncTask Class
- Params: Type of the parameters sent to the task during execution.
- Progress: Type of the progress units published during background computation.
- Result: Type of the result of the background computation.
Example of an AsyncTask Application
To start an AsyncTask, the following code must be present in the MainActivity
class:
MyTask myTask = new MyTask();
myTask.execute();
In this example, we have used a sample class that extends AsyncTask
, and the execute
method is used to start the background thread. Note:
- The AsyncTask instance must be created and called on the UI thread.
- The methods overridden in the AsyncTask class should never be called manually; they are called automatically.
- AsyncTask can only be called once; a subsequent call will result in an exception.
Project Structure
The XML layout is defined in activity_main.xml
and looks like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/tv_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10pt"
android:textColor="#444444"
android:layout_alignParentLeft="true"
android:layout_marginRight="9dip"
android:layout_marginTop="20dip"
android:layout_marginLeft="10dip"
android:text="Sleep time in Seconds:"/>
<EditText
android:id="@+id/in_time"
android:layout_width="150dip"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"
android:layout_toRightOf="@id/tv_time"
android:layout_alignTop="@id/tv_time"
android:inputType="number"
/>
<Button
android:id="@+id/btn_run"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Run Async task"
android:layout_below="@+id/in_time"
android:layout_centerHorizontal="true"
android:layout_marginTop="64dp" />
<TextView
android:id="@+id/tv_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="7pt"
android:layout_below="@+id/btn_run"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Java Code for MainActivity
package com.journaldev.asynctask;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText time;
private TextView finalResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time = (EditText) findViewById(R.id.in_time);
button = (Button) findViewById(R.id.btn_run);
finalResult = (TextView) findViewById(R.id.tv_result);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AsyncTaskRunner runner = new AsyncTaskRunner();
String sleepTime = time.getText().toString();
runner.execute(sleepTime);
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
ProgressDialog progressDialog;
@Override
protected String doInBackground(String... params) {
publishProgress("Sleeping..."); // Calls onProgressUpdate()
try {
int time = Integer.parseInt(params[0])*1000;
Thread.sleep(time);
resp = "Slept for " + params[0] + " seconds";
} catch (InterruptedException e) {
e.printStackTrace();
resp = e.getMessage();
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
@Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
finalResult.setText(result);
}
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,
"ProgressDialog",
"Wait for "+time.getText().toString()+ " seconds");
}
@Override
protected void onProgressUpdate(String... text) {
finalResult.setText(text[0]);
}
}
}
Conclusion
The AsyncTask class allows Android developers to perform time-consuming tasks in the background while keeping the user interface responsive. The example above shows a simple implementation where a task pauses for a specified time and reports progress to the user interface.