Android Background Task

Overview

Async
Android Document is very nice explanation for AsyncTask

Steps

Just 2!

  1. Create task class which extends AsyncTask
  2. Invoke execute method from main thread

Template

This is AsyncTask

public class AsyncSampleTask extends AsyncTask<Params, Progress, Result> {
}
Params Description
Params Parameters for doInBackground
Progress Task progress(implements by yourself)
Result Return value of doInBackground

Override Methods

AsyncTask has several methods you can override.

Method Description
protected void onPreExecute() Before doInBackground
protected Void doInBackground(String… params) Do background task
protected void onProgressUpdate(Void… values) Return progress
protected void onPostExecute(Void result) After backgroundtask
protected void onCancelled() Cancel
protected void onCancelled(Void result) After cancel

doInBackground(Params… params) is required. This is actual background task operation.

Parameter

To pass parameters to Task, you have 2 choices.

  • Constructor
  • Use parameter doInBackground

Parameter of doInBackground is fix-type.
That is limitation, I thought.
If you want to keep some data in this class, use constructor.
If you use data in one time, use arguments of doInBackground.

Network Programming

To use HttpClient, you can’t use main thread. Use worker thread instead.
In that case, you use client with this Async task.

UI

You cannot do any operation of UI.
If you want to manage UI, use Handler

Handler handler = new Handler();
handler.post(new Runnable() 
{
	@Override
	public void run() 
        {
                // UI Operations
		return;
	}
});

Sample

This is easy sample.
Good sample for you are in Android Developer web site.

AsyncSampleTask.java

public class AsyncSampleTask extends AsyncTask<String, Integer, Long> 
{

	@Override
	protected Long doInBackground(String... params) 
	{
		// Do background task
		return null;
	}

	@Override
	protected void onPostExecute(Long result) 
	{
		// This is task end operations
		super.onPostExecute(result);
	}

	@Override
	protected void onPreExecute() 
	{
		super.onPreExecute();
	}

	@Override
	protected void onProgressUpdate(Integer... values) 
	{
		// You can get progress here
		super.onProgressUpdate(values);
	}

	@Override
	protected void onCancelled() 
	{
		// Cancel
		super.onCancelled();
	}

	@Override
	protected void onCancelled(Long result) 
	{
		// Cancelled
		super.onCancelled(result);
	}
}

Test

new AsyncSampleTask().execute("");