android10

  • Increase font size
  • Default font size
  • Decrease font size

ProgressBar updating using Message Handler

E-mail Print
( 1 Vote )
Share

Introduction

SDK Version: M3

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

ProgressBar Updating

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 LoadingScreen.java, 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(R.id.ProgressBar01);

 

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

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
2
3
4
5
6
7
/* Creating a message */
Message progressMsg = new Message();
 
progressMsg.arg1 = progress();
 
/* Sending the message */
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.

Comments (0)
Only registered users can write comments!
 

ANDROID10 --- TIP!!!

android10 tipIf you are writing an article and want to include your source code or a file...is pretty simple: first you save your article for first time to create it, then you edit it and at bottom of the editor, you have a button "Add Attachment"...just click it, upload your file...and that's all...too easy...
contact android10!!!