Pr.Pg Next Pg

Async Task Class tutorials

Introduction

  • AsyncTask enables proper and easy use of the UI thread.

  • This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

  • The AsyncTask class encapsulates the creation of a background process and the synchronization with the main thread.

  • It also supports reporting progress of the running tasks.

How to use

  • To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are the following AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue>

  • The three types used by an asynchronous task are the following:

  • Params, the type of the parameters sent to the task upon execution.

  • Progress, the type of the progress units published during the background computation.

  • Result, the type of the result of the background computation.

  • Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

  •  private class MyTask extends AsyncTask<Void, Void, Void> { ... }

Main Methods

  • AsyncTask has 4 main methods:

    1. onPreExecute() 

    2. doInBackground()

    3. onProgressUpdate()

    4. onPostExecute() 

important Rules

  • The AsyncTask instance must be created in UI thread. 

  • execute(Params...) must be invoked on the UI thread.

  • DonotcallonPreExecute(),onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.

  • The AsyncTask can be executed only once (an exception will be thrown if a second execution is attempted.)

  •  The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).).

 

onPreExecute()

  • Isinvoked on the UI thread before the task is executed.

  • This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

 

doInBackground(Params...),

  • Is invoked on the background thread immediately after onPreExecute() finishes executing.

  • This step is used to perform background computation that can take a long time.

  • The parameters of the asynchronous task are passed to this step.

  • The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress.

  • These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

 

onProgressUpdate(Progress...)

  • Is invoked on the UI thread after a call to publishProgress(Progress...).

  • The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing.

  • For instance, it can be used to animate a progress bar or show logs in a text field.

 

onPostExecute(Result)

  • Is invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

  • Parallel Execution of several Async Tasks

  • Android executes AsyncTask tasks before Android 1.6 and again as of Android 3.0 in sequence by default.

  • You can tell Android to run it in parallel with the usage of the executeOnExecutor() method, specifyingAsyncTask.THREAD_POOL_EXECUTOR as first parameter.

 

Application Example

  • We will now execute the same application as above, i.e the IOStream example using the AsyncTask class.

  • It will have the same Layout and the output will also be the same.

  • We just modify the class as follows.

 

FileIOStream.java

 

package com.example.helloandroid;

 

importjava.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

 

import android.app.Activity;

import android.app.ProgressDialog;

import android.content.Context;

import android.content.SharedPreferences;

import android.os.AsyncTask;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

 

public class IOStream extends Activity implements OnClickListener {

Button bload;

Button bsave;

EditText etData;

TextView tvData;

String filename = "MyFile";

FileOutputStream fos;

 

@Override

protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

setContentView(R.layout.sharedprefs);

setupVars();

 

}

 

private void setupVars() {

// TODO Auto-generated method stub

bload = (Button) findViewById(R.id.bLoadData);

bsave = (Button) findViewById(R.id.bSaveData);

etData = (EditText) findViewById(R.id.etData);

tvData = (TextView) findViewById(R.id.tvData);

bload.setOnClickListener(this);

bsave.setOnClickListener(this);

 

}

 

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

switch (v.getId()) {

case R.id.bSaveData:

String stringData = etData.getText().toString();

try {

fos = openFileOutput(filename, Context.MODE_PRIVATE);

fos.write(stringData.getBytes());

fos.close();

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

break;

case R.id.bLoadData:

new AsyncTaskExample().execute(filename);

break;

}

}

 

public class AsyncTaskExample extends AsyncTask<String, Integer, String> {

 

ProgressDialog dialog;

@Override

protected void onPreExecute() {

// TODO Auto-generated method stub

super.onPreExecute();

// you can initialize some variables in here

dialog = new ProgressDialog(IOStream.this);

dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

dialog.setMax(100);

dialog.show();

}

 

@Override

protected String doInBackground(String... params) {

// TODO Auto-generated method stub

String returnedData = "Data not available";

FileInputStream fin = null;

int i=0;

while(i<10){

publishProgress(10);

try {

Thread.sleep(500);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

i++;

}

dialog.dismiss();

try {

fin = openFileInput(filename);

byte[] ourByteArray = newbyte[fin.available()];

while (fin.read(ourByteArray) != -1) {

returnedData = new String(ourByteArray);

}

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

try {

fin.close();

return returnedData;

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}catch(NullPointerException e){

e.printStackTrace();

return "Data not available";

}

}

return null;

}

 

@Override

protected void onProgressUpdate(Integer... values) {

// TODO Auto-generated method stub

super.onProgressUpdate(values);

dialog.incrementProgressBy(values[0]);

}

 

@Override

protected void onPostExecute(String result) {

// TODO Auto-generated method stub

super.onPostExecute(result);

tvData.setText(result);

}

 

}

}

 

 

  • We have made a class that extends AsyncTask class and overrides its methods.

  • We make a reference to this class by calling the execute method.

  • We pass the parameters, which we would to the class. In this case we have passed the String which contains the filename.

  • We run the entire code processing stuff, i.e the function to be performed in the doInBackground() method.

  • In the preExecute() method we can initialize the variables.

  • onProgressUpdate() method is used to display the progress.

  • We make a ProgressDialog object in the preExecute().

  • We also set the style in which the progress has to be displayed.

  • The setMax() method sets the maximum value of the progress bar.

  • In the doInBackground() method we publish the progress in multiples of 10 and let the loop run 10 times, i.e the progress bar will fill upto 100 in multiples of 10.

  • The call to publishProgress() method will make a call to the onProgressUpdate() method with the parameters.

  • The Integerůvalues means an array of Integers.

  • We also make the Thead sleep so that we can make out the progress update.

  • We use the onProgressUpdate() method to increment the progress.

 

Description: H:\Pictures\Screenshots\Screenshot_2013-06-18-13-11-26.png

Pr.Pg border                                              Next Pg