Basic Usage

suggest change

In Android Activities and Services, most callbacks are run on the main thread. This makes it simple to update the UI, but running processor- or I/O-heavy tasks on the main thread can cause your UI to pause and become unresponsive (official documentation on what then happens).

You can remedy this by putting these heavier tasks on a background thread.

One way to do this is using an AsyncTask, which provides a framework to facilitate easy usage of a background Thread, and also perform UI Thread tasks before, during, and after the background Thread has completed its work.

Methods that can be overridden when extending AsyncTask****:

Example

public class MyCustomAsyncTask extends AsyncTask<File, Void, String> {

    private final Activity activity;

    public MyCustomAsyncTask(Activity activity) {
        this.activity = activity;
    }

    @Override
    protected void onPreExecute(){
        // This runs on the UI thread before the background thread executes.
        super.onPreExecute();
        // Do pre-thread tasks such as initializing variables. 
        Log.v("myBackgroundTask", "Starting Background Task");  
    }

    @Override
    protected String doInBackground(File... params) {
        // Disk-intensive work. This runs on a background thread.
        // Search through a file for the first line that contains "Hello", and return
        // that line.
        try (Scanner scanner = new Scanner(params[0])) {
            while (scanner.hasNextLine()) {
                final String line = scanner.nextLine();
                publishProgress(); // tell the UI thread we made progress

                if (line.contains("Hello")) {
                    return line;
                }
            }
            return null;
        } catch (FileNotFoundException e) {
            return null;
        }
    }

    @Override
    protected void onProgressUpdate(Void... p) {
        // Runs on the UI thread after publishProgress is invoked.
        Log.v("myBackgroundTask", "Read another line!");
    }

    @Override
    protected void onPostExecute(String s) {
        // This runs on the UI thread after complete execution of the doInBackground() method
        // This function receives result(String s) returned from the doInBackground() method.
        // Update UI with the found string.
        TextView view = (TextView) activity.findViewById(R.id.found_string);
        if (s != null) {
            view.setText(s);
        } else {
            view.setText("Match not found.");
        }
    }

}

Usage:

MyCustomAsyncTask asyncTask = new MyCustomAsyncTask(this);
// Run the task with a user-supplied filename.
asyncTask.execute(userSuppliedFilename);

or simply:

new MyCustomAsyncTask(this).execute(userSuppliedFilename);

Note

When defining an AsyncTask we can pass three types between < > brackets.

Defined as <Params, Progress, Result> (see Parameters section)

The previous example uses <File, Void, String>:

AsyncTask<File, Void, String>
// Params has type File
// Progress has unused type
// Result has type String

Void is used when you want to mark a type as unused.

You cannot pass a primitive type such as int or float as a parameter. Pass the wrapper class instead, for example Integer instead of int, or Float instead of float.

The AsyncTask and Activity life cycle

AsyncTask does not follow an activity instance's life cycle. If you start an AsyncTask inside an activity and rotate the device, the activity is destroyed and a new instance is created. The AsyncTask keeps running until it completes. The example above holds the old activity, so a running task can leak that activity.

Solution: AsyncTaskLoader

One subclass of Loaders is AsyncTaskLoader. It does the same kind of background work as AsyncTask and handles activity configuration changes more easily, within the life cycles of fragments and activities. Whenever data needs to be loaded for an activity or fragment, AsyncTaskLoader is the better fit.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents