Android Async Task

Android Async Task

AsyncTask is basically an abstract class provided by Android , which allows you to run long/heavy task in the background thread, without interrupting the main UI Thread.

When to use ?

Async Task are used when you need to run some heavy task in the background. For eg: If you want to download some files from the server, you will be using Async Task for the same. NOTE : For this scenario, Volley will be a better option (will discuss this in more detail in the next tutorial)

Now, as soon as it gets the result, it will update the UI Thread without interrupting the Main Thread.

How to use ?

private class FileTask extends AsyncTask<URL, Integer, Void> {

    @Override
    protected Long doInBackground(URL... url) {
       //code to download file
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        
    }

    @Override
    protected void onPostExecute(Void result) {
        //update the UI here,
    }
}
new FileTask().execute("url_to_download");

Methods

This was a very basic information on how and when to use AsnycTask in Android Apps.

Can we cancel the AsyncTask ?

Yes. A task can be cancelled at any point of time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled, instead of onPostExecute will be invoked after doInBackground returns.

Recommendation