Sunday, May 20, 2012

AsyncTask :Update UI Using AsyncTask

The characteristics of AsyncTask is the task to run outside the main thread, the callback method is executed in the main thread, which effectively avoids the use Handler trouble. Read AsyncTask source known the AsyncTask java.util.concurrent framework to manage the threads and the execution of tasks, concurrent framework is a very mature and efficient framework, after rigorous testing. This shows AsyncTask of well-designed to solve the problems of anonymous threads.

if you have any long task to do in backround.You just extend AsyncTask class in somewhrere in code.then,from the main thread, create an instance of your extended class and call the execute method of AsycTask.

Now,there are 3 kinds of data you will be pass or recive back from Asyctask in Ui Thread:
1. Params: The parameters you sent to the backgrund task,i.e. doInBackground(Params...).
2. Progress : The Background job progress units which will pass to UI thread reporting background job progress.
3. Result : The data that will be returned to Ui Thread on task Completion from Background task.

When AsyncTask is executed,it goes through from 4 steps:
A. onPreExecute() :
-Called before Background computation starts on Ui Thread.
-Use for do some setup like,dispay progress dialog.

B. doInBackground(Params...) :
-Called after onPreExecute() on Background Thread.
-Used for perfrom background Computation that can take long time.
-After Background Task Completion result are returned by this step to onPostExecute(result)
-This method invoke publishProgress(Progress... values) for publish updates on the UI Thread while background computation is still running.

C. onProgressUpdate(Progress... values):
-Run on Ui Thread after publishProgress(Progress... values) is invoked from doInBackground(Params...).

D. onPostExecute(Result result) :
-This method invoke on the Ui Thread after the background Computation finishes. the result of the Computation is passed to this step as a parameter.


Example of AsyncTask:
AsyncTaskExampleActivity.java:



package com.imrankhanandroid.AsyncTaskExample; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; public class AsyncTaskExampleActivity extends Activity { /** Called when the activity is first created. */ Button download; ProgressBar pb; TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); pb=(ProgressBar)findViewById(R.id.pb); tv=(TextView)findViewById(R.id.tv); download = (Button)findViewById(R.id.download); download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DownloadTask dTask = new DownloadTask(); dTask.execute(100); } }); } class DownloadTask extends AsyncTask{ // Behind the angle brackets are the parameters (in case the thread rest time), //progress (publishProgress the used), the return value type @Override protected void onPreExecute() { // First execution method super.onPreExecute(); } @Override protected String doInBackground(Integer... params) { // Implementation of the second method, onPreExecute () //after the implementation of the implementation of for(int i=0;i<=100;i++){ pb.setProgress(i); publishProgress(i); try { Thread.sleep(params[0]); } catch (InterruptedException e) { e.printStackTrace(); } } return "Is finished"; } @Override protected void onProgressUpdate(Integer... progress) { // This function is triggered when the doInBackground call // publishProgress call only one parameter // But here taken to be an array, so use progesss[0] to the value // N parameter with progress [n] value tv.setText(progress[0]+"%"); super.onProgressUpdate(progress); } @Override protected void onPostExecute(String result) { // return the doInBackground trigger to change the sentence words, // is doInBackground execution after trigger // where the result is above doInBackground after the execution of // the return value, so here is the finished setTitle(result); super.onPostExecute(result); } } }


main.xml:


<xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Hello , Welcome to Imran khan's Blog!"/> <Button android:id="@+id/download" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Download"/> <TextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Progress"/> <ProgressBar android:id="@+id/pb" android:layout_width="fill_parent" android:layout_height="wrap_content" style="?android:attr/progressBarStyleHorizontal"/> </LinearLayout>


Download Source Code: AsyncTaskExample








0 comments:

Post a Comment

 
Powered by Blogger