Thursday, July 28, 2011

Android Aync task

I am working on some android applications and thought I'd share how Async task works with a simple example.

Android applications are designed to be responsive. When unresponsive the android OS uses the tough love approach and offloads the app i.e the ANR(App not responding exception). When we do network calls off the mainthread these will block since network connections are relatively slow . To avoid this problem we will need to offload this network call to another worker thread.
This can be achieved using the AsyncTask

Methods we care about in AsyncTask
*onPreExecute()-
Runs on UI Thread before handing over to worker thread

*doInBackground()
Workhorse runs in background
*publishProgress()
inform UI about progrèss called from doInBackground()
*onProgressUpdate()
runs on UI thread and updates progressBar
*onPostExecute
runs in UI thread once worker thread is done

ProgressActivity has a button which will update a progress bar when hit.


package com.foo;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class ProgressBarActivity extends Activity implements OnClickListener {
private ProgressBar progressBar;
private Button start;

public class BackgroundAsyncTask extends AsyncTask {

int myProgress;

@Override
protected void onPostExecute(Void result) {
Toast.makeText(ProgressBarActivity.this, "onPostExecute all done back in UI",
Toast.LENGTH_LONG).show();
}

@Override
protected void onPreExecute() {
Toast.makeText(ProgressBarActivity.this,
"preexecute -before back ground processing starts",
Toast.LENGTH_LONG).show();
myProgress = 0;
}

@Override
protected Void doInBackground(Void... params) {

while (myProgress < 100) {
myProgress++;
publishProgress(myProgress);
SystemClock.sleep(20);
}
return null;
}

@Override
protected void onProgressUpdate(Integer... values) {

progressBar.setProgress(values[0]);// called by the publishProgress
// method to update progress bar
}

}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

start = (Button) findViewById(R.id.startprogress);
progressBar = (ProgressBar) findViewById(R.id.progressbar_Horizontal);
progressBar.setProgress(0);

start.setOnClickListener(this);

}

@Override
public void onClick(View v) {
new BackgroundAsyncTask().execute();

}
}