MY mENU


Tuesday 13 March 2012

Asynchronous task in Android


The Handler is associated with the application's main thread. it handles and schedules messages and runnable sent from background threads to the app main thread. AsyncTask provides a simple method to handle background threads in order to update the UI without blocking it by time consuming operations. both can be used to update the UI from background threads, the difference would be in your execution scenario. 

You may consider using handler if you want to post delayed messages or send messages to the <strong> Message Queue </strong> in a specific order.

You may consider using AsyncTask if you want to exchange parameters (thus updating UI) between the app main thread and background thread in an easy convenient way.


AsyncTask is an abstract class that provides several methods managing the interaction between the UI thread and the background thread. it's implementation is by creating a sub class that extends AsyncTask and implementing the different protected methods it provides.


Creating the AsyncTask sub class: The first step in implementing AsyncTask is to create a sub class like this:
1class ProgressTask extends AsyncTask<params, progress, result>{
2}
The AsyncTask declaration has three Varargs parameters which are:
  1. Params: parameter info passed to be used by the AsyncTask.
  2. Progress: the type of progress that the task accomplishes.
  3. The result returned after the AsyncTask finishes.
These parameters are of type Varargs which provide the flexibility to pass dynamic sized arrays as parameters. In our example our class will be like this:
1class ProgressTask extends AsyncTask< Integer, Integer, void >{
2}
The parameter and the progress are of type Integer and the result is Void as our tasks does not return anything (returns null). 

The second step is overriding the protected methods defined by the AsyncTask class that handle the execution life cycle of the AsyncTask. We have five methods to implement which are:
  1. onPreExecute: the first method called in the AsyncTask, called on the UI thread.
  2. doInBackground: the method that executes the time consuming tasks and publish the task progress, executed in background thread.
  3. onProgressUpdate: method that updates the progress of the AsyncTask, run on the UI thread.
  4. onPostExecute: the final method that gets called after doInBackground finishes, here we can update the UI with the results of the AsyncTask.
  5. onCancelled: gets called if the AsyncTask.cancel() methods is called, terminating the execution of the AsyncTask.
Starting the AsyncTask: To start the AsyncTask we create an instance of it, then call the execute() method passing the initial parameters like this:
ProgressTask task=new ProgressTask();
// start progress bar with initial progress 10
task.execute(10);
Implementing the AsyncTask:
view source
print?
01class ProgressTask extends AsyncTask<Integer, Integer, Void>{
02 
03  @Override
04  protected void onPreExecute() {
05   // initialize the progress bar
06   // set maximum progress to 100.
07   progress.setMax(100);
08 
09  }
10 
11  @Override
12  protected void onCancelled() {
13   // stop the progress
14   progress.setMax(0);
15 
16  }
17 
18  @Override
19  protected Void doInBackground(Integer... params) {
20   // get the initial starting value
21   int start=params[0];
22   // increment the progress
23   for(int i=start;i<=100;i+=5){
24    try {
25     boolean cancelled=isCancelled();
26     //if async task is not cancelled, update the progress
27     if(!cancelled){
28      publishProgress(i);
29      SystemClock.sleep(1000);
30 
31     }
32 
33    catch (Exception e) {
34     Log.e("Error", e.toString());
35    }
36 
37   }
38   return null;
39  }
40 
41  @Override
42  protected void onProgressUpdate(Integer... values) {
43   // increment progress bar by progress value
44   progress.setProgress(values[0]);
45 
46  }
47 
48  @Override
49  protected void onPostExecute(Void result) {
50   // async task finished
51   Log.v("Progress""Finished");
52  }
53 
54 }
Here are the steps:
  1. onPreExecute() method first gets called initializing the maximum value of the progress bar.
  2. doInBackground(Integer... params) methods gets called by obtaining the initial start value of the progress bar then incrementing the value of the progress bar every second and publishing the progress as long as the async task is not cancelled.
  3. onProgressUpdate(Integer... values) method is called each time progress is published fromdoInBackground, thus incrementing the progress bar.
  4. onPostExecute(Void result) is called after doInBackground finished execution.
  5. void onCancelled() is called if task.cancel(true) is called from the UI thread. it may interrupt the execution preventing onPostExecute from being executed.
The onClick handler of our buttons is like this:
01@Override
02 public void onClick(View v) {
03  ProgressTask task=new ProgressTask();
04  switch(v.getId()){
05  case R.id.btn:
06   task.execute(10);
07   break;
08  case R.id.btnCancel:
09   task.cancel(true);
10   break;
11  }

No comments:

Post a Comment