AsyncTask
Android development
Android example
mobile app programming
Android tutorial

AsyncTask Android example

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

AsyncTask in Android is a framework that allows developers to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. This class is designed to be a straightforward and easy-to-use utility for handling tasks that require background processing but still need to interact with the user interface.

Basic Structure of AsyncTask

AsyncTask is an abstract class, and it needs to be subclassed to perform the actual task. It requires us to define a few methods and has specific type parameters that need to be specified.

Here is the basic structure of AsyncTask:

java
1private class MyAsyncTask extends AsyncTask<Params, Progress, Result> {
2    @Override
3    protected Result doInBackground(Params... params) {
4        // Background execution code
5        return null;
6    }
7
8    @Override
9    protected void onPreExecute() {
10        // Code to execute before background task starts
11    }
12
13    @Override
14    protected void onPostExecute(Result result) {
15        // Code to perform after the background task completes
16    }
17
18    @Override
19    protected void onProgressUpdate(Progress... values) {
20        // Code to update progress to UI
21    }
22}

Parameters

  • Params: The type of the input parameters sent to the task upon execution.
  • Progress: The type of the progress units published during the background computation.
  • Result: The type of the result of the background computation.

Key Methods

  • onPreExecute(): Invoked on the UI thread before the task is executed. This method can be used to set up the task, like showing a progress bar in the UI.
  • doInBackground(Params... params): This is the core method that is invoked on the background thread and is where the time-consuming background operations are performed. This needs to be overridden to perform the task.
  • onProgressUpdate(Progress... values): This method is invoked on the UI thread after a call to publishProgress(Progress...). This can be used to update the progress in the UI, like updating a progress bar.
  • onPostExecute(Result result): This method is invoked on the UI thread after the background computation finishes. It is used to report the results of the computation.

Example

Let's look at a simple example of AsyncTask that downloads data from the web.

java
1private class DownloadTask extends AsyncTask<String, Integer, String> {
2    @Override
3    protected void onPreExecute() {
4        super.onPreExecute();
5        // Initialize or show progress dialog
6    }
7
8    @Override
9    protected String doInBackground(String... urls) {
10        int count = urls.length;
11        StringBuilder result = new StringBuilder();
12        for (int i = 0; i < count; i++) {
13            // Simulate downloading file
14            try {
15                Thread.sleep(1000); // Sleeping for demonstration. Replace this with actual download code.
16            } catch (InterruptedException e) {
17                e.printStackTrace();
18            }
19            publishProgress((int) ((i / (float) count) * 100));
20            result.append("Downloading ").append(urls[i]).append("\n");
21        }
22        return result.toString();
23    }
24
25    @Override
26    protected void onProgressUpdate(Integer... progress) {
27        super.onProgressUpdate(progress);
28        // Update progress in your UI
29    }
30
31    @Override
32    protected void onPostExecute(String result) {
33        super.onPostExecute(result);
34        // Display result in UI and dismiss progress dialog
35    }
36}

Considerations

  1. Threading Constraints: AsyncTask must be invoked on the UI thread. This is important as the lifecycle methods of AsyncTask interact with UI components and hence must be executed on the main thread.
  2. Cancelable Tasks: AsyncTask can be canceled with the cancel(Boolean) method. After canceling, isCancelled() can be checked during the task progress to halt operations.
  3. Lifecycle Awareness: AsyncTask is not lifecycle-aware, which means it does not handle configuration changes like screen rotations. This could lead to memory leaks if the activity or fragment is recreated during a long-running task.
  4. Limited Parallelism: By default, AsyncTask uses a single worker thread, which can be a limitation in scenarios with high concurrency requirements.

Alternatives to AsyncTask

Given the limitations and after its deprecation, developers are encouraged to use other alternatives such as:

  • Java ExecutorService: For more flexible task execution, allowing various scheduling and management features.
  • HandlerThread: A simple way to perform background work on a dedicated thread with a message loop.
  • RxJava: A reactive programming library that offers a powerful means to perform asynchronous operations.
  • Android WorkManager: A high-level library for background work, recommended for tasks that require guaranteed execution.

Summary of AsyncTask Features

FeatureDescription
Background ExecutionExecutes code in a background thread.
UI Thread InteractionAllows updates on UI thread post-execution.
Progress UpdatesSupports progress updates via publish/update logic.
DeprecationDeprecated in later Android releases.
Lack of Lifecycle AwarenessNot designed for handling configuration changes.
Limited Parallel ExecutionDoes not inherently support high concurrency.

In conclusion, while AsyncTask provides a straightforward means to perform background operations in Android, its use is limited by several constraints, and developers are nudged towards more modern and powerful alternatives as it has become deprecated in favor of better solutions.


Course illustration
Course illustration

All Rights Reserved.