Thursday 3 May 2012

How to make a progress dialog In Android

The first thing you have to do is, making your progress dialog accessible from the entire Main class.
So, how do we do that? easy!
Define the progress dialog in the name space as so:

1
private ProgressDialog progressDialog;
Now we want to create a functions which will be holding our Thread and ProgressDialog.
We can do this by adding the following code:

01
private void runDialog(final int seconds)
02 {
03         progressDialog = ProgressDialog.show(this"Please wait....""Here your message");
04
05         new Thread(new Runnable(){
06             public void run(){
07                 try {
08                             Thread.sleep(seconds * 1000);
09                     progressDialog.dismiss();
10                 catch (InterruptedException e) {
11                     e.printStackTrace();
12                 }
13             }
14         }).start();
15 }
So what does that piece of code do exactly? Lets go over this code 1 step at a time.

1
progressDialog = ProgressDialog.show(this"Please wait....""Here your message");
The following code create's and starts the ProgressDialog.

01
new Thread(new Runnable(){
02     public void run(){
03         try {
04             Thread.sleep(seconds * 1000);
05             progressDialog.dismiss();
06         catch (InterruptedException e) {
07             e.printStackTrace();
08         }
09     }
10 }).start();
This piece of code create a "Thread" a thread runs in the background of your applications, which lets your GUI (Graphical User Interface) run without interference. If you would do this without a Thread, you GUI would freeze / lock untill the process is completed.
Lets move to the next piece:

1
Thread.sleep(seconds * 1000);
After the thread starts to run it's code, when it reaches the thread.sleep() command it's waits for a given amount of time and the continues to execute the rest of the code. So in our case it waits for 5 seconds before running the following command:

1
progressDialog.dismiss();
This piece of code dismisses / stops the progress dialog.
A thread is most commonly used for background (service) operations, for example....you create aThread (worker) which checks if you receive any message's or, checks your battery status, play music, and the list goes on and on.

No comments:

Post a Comment