Skip to content Skip to sidebar Skip to footer

What Is An AsyncTask (or AsyncResult) And How Is It Typically Used For Android?

Can't find much about this concept. Have already referred to https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/AsyncResult.java https://docs.

Solution 1:

Background / Theory

AsyncTask allows you to run a task on a background thread, while publishing results to the UI thread.

The user should always able to interact with the app so it is important to avoid blocking the main (UI) thread with tasks such as downloading content from the web.

This is why we use an AsyncTask.

It offers a straightforward interface by wrapping the UI thread message queue and handler that allow you to send and process runnable objects and messages from other threads.

Implementation

AsyncTask is a generic class. (It takes parameterized types in its constructor.)

It uses these three generic types:

Params - the type of the 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.

Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

private class MyTask extends AsyncTask<Void, Void, Void> { ... }

These three parameters correspond to three primary functions you can override in AsyncTask:

  • doInBackground(Params...)
  • onProgressUpdate(Progress...)
  • onPostExecute(Result)

To execute AsyncTask

call execute() with parameters to be sent to the background task.

What Happens

  1. On main/UI thread, onPreExecute() is called. (To initialize something in this thread such as show a progress bar on the user interface.)

  2. On a background thread, doInBackground(Params...) is called. (The parameters are those passed to the Execute function.)

    • Where the long-running task should happen

    • Must override at least doInBackground() to use AsyncTask.

    • Call publishProgress(Progress...) to update a display of progress in the user interface while the background computation is still executing. (e.g. animate a progress bar or show logs in a text field.)

      • This causes onProgressUpdate() to be called.
  3. On the background thread, a result is returned from doInBackground(). This triggers the next step.

  4. On main/UI thread, onPostExecute() called with the returned result.

Examples

Using again the example of the blocking task being to download something from the web,

  • Example A downloads an image and displays it in an ImageView,
  • while Example B downloads some files.

Example A

The doInBackground() method downloads the image and stores it in an object of type BitMap. The onPostExecute() method takes the bitmap and places it in the ImageView.

class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bitImage;

    public DownloadImageTask(ImageView bitImage) {
        this.bitImage = bitImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mBmp = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mBmp = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mBmp;
    }

    protected void onPostExecute(Bitmap result) {
        bitImage.setImageBitmap(result);
    }
}

Example B

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

Example B execution

new DownloadFilesTask().execute(url1, url2, url3);

Post a Comment for "What Is An AsyncTask (or AsyncResult) And How Is It Typically Used For Android?"