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 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!)
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.)
/* 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.
/* 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.