Updating ProgressBar status from a non-ui thread ( working thread ) using AsyncTask in Android

September 1, 2012
By

In the article titled “Updating ProgressBar status from a non-ui thread ( working thread ) using Handler in Android“, we have seen , how to manipulate  a UI thread component from a non-UI thread using Handler.

In this article, we will see, how to update the progress bar in a UI thread from a non-ui thread using AsyncTask objects.

In this application, the MainActivity screen contains a toggle button. When the toggle button is “ON”, the progress bar starts to increment and when the toggle button is “OFF”, the progress bar stops its execution.

This application is developed in Eclipse ( 4.2.0 ) with ADT plugin (20.0.3 ) and Android SDK ( R20.0.3 ).


1. Create a new Android Application Project namely “ProgressBarAsyncDemo”

New Android Application Project

Figure 1 : New Android Application Project


2. Design Application launcher icon

Design Application Launcher Icon

Figure 2 : Design Application Launcher Icon


3. Create a blank activity

Create a blank Activity

Figure 3 : Create a blank Activity


4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


5. Remove Android’s Support Library from this project, if exists

By default Eclipse ( 4.2.0) adds Android Support Library to  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.


6. Update the  file res/values/strings.xml


<resources>
    <string name="app_name">ProgressBarDemo</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">ProgressBar Demo</string>
</resources>


7. Update the layout file res/layout/activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ToggleButton
        android:id="@+id/tgl_start"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <ProgressBar
        android:id="@+id/progress_bar"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tgl_start"
        tools:context=".MainActivity" />

    <TextView
        android:id="@+id/tv_button_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/progress_bar"
        android:layout_centerHorizontal="true"
        tools:context=".MainActivity" />

</RelativeLayout>


8. Update the MainActivity class in the file src/in/wptrafficanalyzer/progressbarsyncdemo/MainActivity.java


package in.wptrafficanalyzer.progressbarasyncdemo;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

    private ProgressBar mProgressBar;
    private ToggleButton mTglStart;
    private TextView mTvButtonStatus;

    private int mProgressStatus = 0;
    private ProgressBarAsync mProgressbarAsync;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
        mTglStart = (ToggleButton) findViewById(R.id.tgl_start);
        mTvButtonStatus = (TextView) findViewById(R.id.tv_button_status);

        OnCheckedChangeListener listener = new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                /** Button is set to ON */
                if(isChecked){
                    /** Resetting progressbar to 0 */
                    if(mProgressStatus==100)
                        mProgressStatus=0;
                    /** Creating an instance of ProgressBarAsync */
                    mProgressbarAsync = new ProgressBarAsync();

                    /** ProgressBar starts its execution */
                    mProgressbarAsync.execute();

                    mTvButtonStatus.setText("Toggle Button is on");

                }else{  /** Button is set to OFF */
                    mProgressbarAsync.cancel(true);
                    mTvButtonStatus.setText("Toggle Button is off");
                }
            }
        };

        mTglStart.setOnCheckedChangeListener(listener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    private class ProgressBarAsync extends AsyncTask<Void, Integer, Void>{

        private boolean mRunning = false;

        /** This callback method is invoked, before starting the background process */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mRunning = true;
        }

        /** This callback method is invoked on calling execute() method
        * on an instance of this class */
        @Override
        protected Void doInBackground(Void...params) {
            while(mProgressStatus<100){
                try{
                    if(!mRunning)
                        break;
                    mProgressStatus++;

                    /** Invokes the callback method onProgressUpdate */
                    publishProgress(mProgressStatus);
                    Thread.sleep(100);

                }catch(Exception e){
                    Log.d("Exception", e.toString());
                }
            }
            return null;
        }

        /** This callback method is invoked when cancel() method is called
        * on an instance of this class */
        @Override
        protected void onCancelled() {
            super.onCancelled();
            mRunning = false;
        }

        /** This callback method is invoked when publishProgress()
        * method is called */
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            mProgressBar.setProgress(mProgressStatus);
            if(!mTglStart.isChecked()){
                this.cancel(true);
            }
        }

        /** This callback method is invoked when the background function
        * doInBackground() is executed completely */
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            mTglStart.setChecked(false);
        }
    }
}


9. Screenshot of the application in execution

ProgressBar in Action

Figure 5 : ProgressBar in Action


10. Download


11. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , , , , , ,

One Response to Updating ProgressBar status from a non-ui thread ( working thread ) using AsyncTask in Android

  1. Gaurav on April 11, 2016 at 7:18 pm

    Hi George Mathew.

    i need your help to solve some issue related to runOnUiThread(), how can i stop forcefully runOnUiThread() in android, i ask a question on stackoverflow but still not found any solution, stackoverflow link is –

    http://stackoverflow.com/questions/36542175/how-can-i-stop-multiple-create-runonuithread-when-activity-finish

    sir please help me.

    Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner