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

August 31, 2012
By

UI thread is the thread in which the components of an application will be executed by default. But there are some tasks which are usually executed in background ( eg : downloading files ). These background tasks are run with the help of threads in Android. These threads are called non-ui threads.

An important rule associated with UI thread and Non-UI thread is that, do not do any manipulation on UI from a non UI thread. In order to overcome this problem, we will use Handler in this application. The Handler will manage the communication from non-ui thread ( working thread ) to ui thread.

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.

The same application, but implemented using AsyncTask object is discussed in the article titled “Updating ProgressBar status from a non-ui thread ( working thread ) using AsyncTask in Android“.

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


1. Create a new Android application project namely “ProgressBarDemo”

New Android Application Project namely ProgressBarDemo

Figure 1 : New Android Application Project namely ProgressBarDemo


2. Design application launcher icon

Design Application Launcher Icon

Figure 2 : Design Application Launcher Icon


3. Create a blank activity to create a MainActivity class

Create a blank Activity

Figure 3 : Create a blank Activity


4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


5. Remove the 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 class MainActivity in the file src/in/wptrafficanalyzer/progressbardemo/MainActivity.java


package in.wptrafficanalyzer.progressbardemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
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 Handler mHandler = new Handler();
    private ToggleButton mTglStart;
    private TextView mTvButtonStatus;

    private int mProgressStatus = 0;
    private Thread mThread;
    private Runnable mRunnable;
    private int mBtnStatus=0;

    @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);

        mTglStart.setChecked(false);
        mTvButtonStatus.setText("Toggle Button is off");

        mRunnable = new Runnable() {
            @Override
            public void run() {
                while(mProgressStatus<100){
                    try{
                        /** Exit current thread, if button status is off */
                        if(mBtnStatus==0 ){
                            break;
                        }

                        /** Increment progressbar status by 1 */
                        mProgressStatus++;

                        /** Sleep this thread for 100 ms */
                        Thread.sleep(100);

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

                    /** For every increment, sent a message to UI thread to increment the progressbar */
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            mProgressBar.setProgress(mProgressStatus);
                        }
                    }
                );
                }

                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mTglStart.setChecked(false);
                    }
                }
            );
            }
        };

        OnCheckedChangeListener listener = new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                /** Button is set to ON */
                if(isChecked){
                    /** Button is on */
                    mBtnStatus=1;

                    /** Create a new thread */
                    mThread = new Thread(mRunnable);

                    if(mProgressStatus==100)
                        mProgressStatus=0;

                    /** Starts the new thread */
                    mThread.start();

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

                }else{    /** Button is set to OFF */

                    /** Button is OFF */
                    mBtnStatus=0;

                    mTvButtonStatus.setText("Toggle Button is off");
                }
            }
        };

        /** Setting an event handler for button on and off */
        mTglStart.setOnCheckedChangeListener(listener);
    }

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


9. Screenshot of the application in execution

Progress bar in execution

Figure 5 : Progress bar in execution


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: , , , , , , ,

2 Responses to Updating ProgressBar status from a non-ui thread ( working thread ) using Handler in Android

  1. vipul on January 1, 2015 at 7:44 am

    Greetings,

    I am refering the tutorial of yours from this link……http://wptrafficanalyzer.in/blog/updating-progressbar-status-from-a-non-ui-thread-working-thread-using-handler-in-android/

    I have a problem. soon after the progress touches 100, the bar disappears.!! what can i do.

    Thank you sir.

    • George Mathew on January 1, 2015 at 9:57 am

      Happy New Year.

      We have not coded to hide the progress bar in the article. Please check it out.

      Thank you.

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