AsyncTask with Progress Bar
Class Overview
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.
AsyncTask is designed to be a helper class around 
Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called 
Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground,onProgressUpdate and onPostExecute.The 4 steps
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked 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...), invoked on the background thread immediately afteronPreExecute()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 usepublishProgress(Progress...)to publish one or more units of progress. These values are published on the UI thread, in theonProgressUpdate(Progress...)step.onProgressUpdate(Progress...), invoked on the UI thread after a call topublishProgress(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), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
here our example 
MainActivity.java
package
com.itdeveloper.asynctask;
import
android.app.Activity;
import
android.os.AsyncTask;
import android.os.Bundle;
import
android.os.SystemClock;
import android.view.View;
import
android.widget.Button;
import
android.widget.ProgressBar;
import
android.widget.Toast;
public class MainActivity extends Activity {
       ProgressBar
progressBar;
       Button
StartProgressBtn;
       /** Called when the
activity is first created. */
       @Override
       public void onCreate(Bundle
savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              StartProgressBtn = (Button)
findViewById(R.id.startprogress);
              progressBar = (ProgressBar)
findViewById(R.id.progressbar_Horizontal);
              StartProgressBtn.setOnClickListener(new
Button.OnClickListener() {
                     @Override
                     public void onClick(View v) {
                           new
BackgroundAsyncTask().execute();
                           /**
                            * just disable button click so user wont be
able to click again
                            * and again till task end
                            */
                           StartProgressBtn.setClickable(false);
                     }
              });
       }
       public class BackgroundAsyncTask extends AsyncTask<Void,
Integer, Void> {
              int myProgressCount;
              @Override
              protected void onPreExecute() {
                     Toast.makeText(MainActivity.this,
                                  "onPreExecute
Start Progress Bar", Toast.LENGTH_LONG)
                                  .show();
                     progressBar.setProgress(0);
                     myProgressCount = 0;
              }
              @Override
              protected Void
doInBackground(Void... params) {
                     // TODO Auto-generated
method stub
                     while (myProgressCount < 100) {
                           myProgressCount++;
                           /**
                            * Runs on the UI thread after
publishProgress(Progress...) is
                            * invoked. The specified values are the values
passed to
                            * publishProgress(Progress...).
                            * 
                            * Parameters values The values indicating
progress.
                            */
                           publishProgress(myProgressCount);
                           SystemClock.sleep(100);
                     }
                     return null;
              }
              /**
               * This method can be invoked from
doInBackground(Params...) to publish
               * updates on the UI thread while the
background computation is still
               * running. Each call to this method will
trigger the execution of
               * onProgressUpdate(Progress...) on the UI
thread.
               * 
               * onProgressUpdate(Progress...) will not be
called if the task has been
               * canceled.
               * 
               * Parameters values The progress values to
update the UI with.
               */
              @Override
              protected void
onProgressUpdate(Integer... values) {
                     // TODO Auto-generated
method stub
                     progressBar.setProgress(values[0]);
              }
              @Override
              protected void onPostExecute(Void
result) {
                     Toast.makeText(MainActivity.this, "onPostExecute
End Progress Bar",
                                  Toast.LENGTH_LONG).show();
                     /**
                      * enable Button back so user can click again 
                      */
                     StartProgressBtn.setClickable(true);
              }
       }
}
activity_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" >
   
<ProgressBar
        android:id="@+id/progressbar_Horizontal"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:max="100" />
   
<Button
        android:id="@+id/startprogress"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:text="Start Progress bar" />
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0"
encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.itdeveloper.asynctask"
    android:versionCode="1"
    android:versionName="1.0" >
   
<uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
   
<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
       
<activity
            android:name="com.itdeveloper.asynctask.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN"
/>
                <category android:name="android.intent.category.LAUNCHER"
/>
            </intent-filter>
       
</activity>
   
</application>
</manifest>
You can download Complete Example here
Happy Coddddding :) 


No comments:
Post a Comment