Android Threading → Android Handler – Update ProgressBar – Camposha

Android Threading

Android Threading

Android Handler – Update ProgressBar

Android Handler and ProgressBar Update Tutorial and Examples

In this tutorial we want to see how to post updates from a background thread to the user interface thread using a Handler.

We click a button and simulate doing heavy work in the background. Meanwhile we are able to update our progressbar as the work continues.

Video Tutorial(ProgrammingWizards TV Channel)

Well we have a video tutorial as an alternative to this. If you prefer tutorials like this one then it would be good you subscribe to our YouTube channel. Basically we have a TV for programming where do daily tutorials especially android.

(a). MainActivity.java

This is the main activity. We derive from the AppCompatActivity. One of the imports we add is the Handler from the android.os package.

...
import android.os.Handler;
...

We will maintain three instance fields:

  1. Handler – a class defined in the android.os package through which we can send and process Message and Runnable objects associated with a thread’s MessageQueue.
  2. ProgressBar – a widget that allows us to show progress.
  3. Button – an action button.

Here’s the full code:

package info.camposha.mrhandler;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

    private Handler mHandler;
    private ProgressBar mProgressBar;
    private Button mStartButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mHandler = new Handler();
        mProgressBar = findViewById(R.id.mProgressBar);
        mStartButton = findViewById(R.id.startBtn);
        mStartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                performStuff();
            }
        });
    }
    private void performStuff() {
        //Simulate Heavy task in background thread
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <= 30; i++) {
                    final int currentProgressCount = i;
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                //Post updates to the User Interface
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            mProgressBar.setProgress(currentProgressCount);
                        }
                    });
                }
            }
        }).start();
    }
}

(b). activity_main.xml

This is the main activity layout. At the root we have a LinearLayout. This element allows us to arrange it’s children linearly either horizontally or vertically. We also have TextView to display the header text of our app. Also we have a progressbar to display progress. We have also a button that when clicked will start the thread to perform our work in the background thread.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    
    android_gravity="center"
    android_orientation="vertical"
    tools_context=".MainActivity">

    <TextView
        android_id="@+id/headerLabel"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_layout_alignParentTop="true"
        android_layout_centerHorizontal="true"
        android_fontFamily="casual"
        android_text="Handler ProgressBar"
        android_textAllCaps="true"
        android_textSize="24sp"
        android_textStyle="bold" />

    <ProgressBar
        android_id="@+id/mProgressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android_layout_width="match_parent"
        android_layout_height="wrap_content"
        android_layout_margin="10dp"
        android_indeterminate="false"
        android_max="10" />

    <Button
        android_id="@+id/startBtn"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_text="Start" />
</LinearLayout>

Leave a Reply

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

Rating

Not enough ratings to display
Join Us
X