ProgressBar updating using Message Handler

SDK Version: 

You're going to learn how to make a progressbar, which gives you a feedback what's going on in the background.

Let say you have a LoadingScreen activity (loadingscreen.xml layout), and a Main activity (main.xml).

You'd like to do some job in the Main activity, and update the progressbar status at the same time. To do this, we are going to use Messages. Although, you can update you're progressbar by sending the progressbar instance itself to your Main activity, but that's obviously not the prettiest solution.

What we going to do is:

1. Declaring a progressbar instance in LoadingScreen Activity:

So in your, after Oncreate(), you should add something like this line to your codeline: (don't forget to add a progressbar to your layout first!)

  1.   ProgressBar pb = (ProgressBar)findViewById(;

2. Setting up a Handler to handle Messages from outside:

These few line go right after declaring the progressbar. We are also declaring "progress" variable, and update it's value from the Message we get.

Now that we know the progress status, simply just update the progressbar with it. (It has to be an int number, value: 0-100.)

  1.           /* Setting up handler for ProgressBar */
  2.          pbHandle = new Handler(){
  3.               @Override</font>
  4.                 public void handleMessage(Message msg) {
  5.                  /* get the value from the Message */
  6.                  int progress = msg.arg1;
  7.                  pb.setProgress(progress);
  8.                 }
  9.                };

Okay, we finished message handling, now let's send some messages from another (in this case Main) activity.

3. Creating and Sending Messages

Please notice that in the 3rd line, we put the progress value (it depends on your project) into the Message's arg1 variable.

Go to your Main(or any other) activity, and paste the following where you need to send the message about the progress.

  1.  /* Creating a message */
  2. Message progressMsg = new Message();
  3.                  progressMsg.arg1 = progress();
  4.                  /* Sending the message */
  5.                  pbHandle.sendMessage(progressMsg);

That's it.

One more thing: you should not use the same message twice, in the same cycle. If you want to send 2 messages in a cycle, you should create a new message with another instance name, Otherwise your app will be crashed.