Using threads and ProgressDialog


SDK Version: 
M5

This is a simple tutorial to show how to create a thread to do some work while displaying an indeterminate ProgressDialog. Click here to download the full source.

We'll calculate Pi to 800 digits while displaying the ProgressDialog. For the sake of this example I copied the "Pi" class from this site.

We start with a new Android project, only thing I needed to change was to give that TextView an id in main.xml so that I could update it in the Activity.

Because this Activity is so small I'll show you the whole thing and then discuss it at the end:

  1. public class ProgressDialogExample extends Activity implements Runnable {
  2.  
  3.         private String pi_string;
  4.         private TextView tv;
  5.         private ProgressDialog pd;
  6.  
  7.         @Override
  8.         public void onCreate(Bundle icicle) {
  9.                 super.onCreate(icicle);
  10.                 setContentView(R.layout.main);
  11.  
  12.                 tv = (TextView) this.findViewById(R.id.main);
  13.                 tv.setText("Press any key to start calculation");
  14.         }
  15.  
  16.         @Override
  17.         public boolean onKeyDown(int keyCode, KeyEvent event) {
  18.  
  19.                 pd = ProgressDialog.show(this, "Working..", "Calculating Pi", true,
  20.                                 false);
  21.  
  22.                 Thread thread = new Thread(this);
  23.                 thread.start();
  24.  
  25.                 return super.onKeyDown(keyCode, event);
  26.         }
  27.  
  28.         public void run() {
  29.                 pi_string = Pi.computePi(800).toString();
  30.                 handler.sendEmptyMessage(0);
  31.         }
  32.  
  33.         private Handler handler = new Handler() {
  34.                 @Override
  35.                 public void handleMessage(Message msg) {
  36.                         pd.dismiss();
  37.                         tv.setText(pi_string);
  38.  
  39.                 }
  40.         };
  41.  
  42. }

So we see that this Activity implements Runnable. This will allow us to create a run() function to create a thread.

In the onCreate() function on line 18 we find and initialize our TextView and set the text telling the user to press any key to start the computation.

When the user presses a key it will bring us to the onKeyDown() function on line 27. Here we create the ProgressDialog using the static ProgressDialog.show() function, and as a result the pd variable is initialized. We also create a new Thread using the current class as the Runnable object. When we run thread.start() a new thread will spawn and start executing the run() function.

In the run() function we calculate pi and save it to the String pi_string. Then we send an empty message to our Handler object on line 40.

Why use a Handler? We must use a Handler object because we cannot update most UI objects while in a separate thread. When we send a message to the Handler it will get saved into a queue and get executed by the UI thread as soon as possible.

When our Handler receives the message we can dismiss our ProgressDialog and update the TextView with the value of pi we calculated. It's that easy!

Comments

I dont think Ive seen all the angles of this subject the way youve pointed them out. Youre a true star a rock star man. Youve got so much to say and know so much about the subject that I think you should just teach a class about it David Carraway // gratis webkatalog mit pagerank

I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading what you all have to say... Darren Carrington // AAAFx Forex Broker

I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading what you all have to say... Dave Whiting // Eigene Model Homepage professionell

Lawn wedding:The 21st century, a new fashion wedding ceremony has gradually replaced the traditional wedding ceremony.No, no reasoned fullness, special order not only healthy, this, the lawn wedding gradually by ancient people to accept. In the bosom of nature, the green lawn like a soft carpet, the boundless foiling bustling wedding scene with flowers and leaves, make the main arch ring out neatly, the long table was covered with flowers and meal. The glow of white dress, the bride incomparably namby-pamby dress. In this bustling will champagne atmosphere of open, beaming banquet begins as! Under the sun, in the sky for witness, such as feed on the lawn of sincere blessing to accept relatives, can lead to the green grass, and let the breeze lift up the bride scattered close-lying hair, in front of the photographer. She is the most natural The new music party in a beautiful dance, the children jumped in groups on the green grass, we lie in frolicking in the bosom of green grass enjoy nature, in cold weather, dressed in satisfiedearly waitress, shuttle in the crowd, for all guests provide delicacies.This is the lawn wedding scene, bright and full of festive atmosphere of whole memorable. Like the wedding is usually adopted the form of a buffet. The earth, the blue sky, the sun, and flowers, green grass for the romance of the wedding, let everybody to the beautiful nature wedding!Classical wedding:Warm and happy, publicity, classical Chinese wedding reflected in north Chinas wedding. Bride: FengGuan XiaPei, luxuriant adornment, festive colors, is typical of Chinese traditional style of the bride, Groom: shamao officer, more elegant, elegant and elegant. The bride and groom points by longfeng sedan by folk bands, saying, experience with umbrella account held the dancing lion to meet new.Then according to the traditional wedding ceremony is a series of folk arrangement ceremonies.Chinese wedding is lively atmosphere and red, the feeling of joy always pervaded the royal air.Rose wedding:Rose is most suitable for weddings, red roses symbolize love, with red roses paved road, happiness rose above held a grand wedding and make the most classic roses for your wedding ceremony add color and passion.The wedding tone can choose red and white. White gauze curtain, white antependium chair cover, and white flowers, candles, only the carpet and is red, grave and celebrations. Downy lamplight wedding banquet hall, veiled in the air and touching.Flowers chooses red roses, luxuriant and mysterious. In Taiwan, the flowers near the door, carpet, candlestick, ceremony table and chair are decorated rose.Holding hands round the bride, the red rose corolla composed represents the brides real life dreams.Ritual ceremony on both sides of the Taiwan: Taiwan has a small table, put a crystal vase full of roses.Wedding banquet: table, put up with a rose, the rose petal shining.may ball. Guest table of crystal menorah also decorated the red rose.Lightsome white gauze, red ribbons, rose still quietly bloomed, a loving hug a person walked towards the future.Lily wedding:The white color sacred purity, many of the bride and bridegroom all dream held a white wedding, but worry will have an elder obstruction of the compromise? Recommend a white lilies wedding, with pure and fresh flowers to decorate your wedding, meaning will make elders.Ceremony area:The white area is a ritual, the romantic world of scenes you remembered for a lifetime. White carpet has been out on both sides, carpet is ceremony, each six white gauze column on the top of the column of yarn is a round of white lily flower.At the end of the carpet is white lilies, metal shelf entangled with asparagus and hinting, each small silver thread fixed in a jar inside white lilies and a bouquet of bud silk, lily, is the direction of the trumpet, convey apple.later joy and blessing. And build a green with natural phenomenon.Banquet area:The sunset, a joy to the feast. The green lawn chairs and round, natural and optional mixed in. Plug in the white lily and white above for every guest, candles and composed by candlelight bouquet of fantasy world.Candlelight wedding:Wedding for everybody is the most romantic most unforgettable. Married life is a new means of stage, go more beautiful tomorrow.Friends are waiting quietly, looking forward, the couple are georgeously apparelled holy, hand out some romantic candlelight, ready to welcome the arrival of a new life, and friends together one of the most exciting moment. The flickering candlelight, shining two love each others heart, love is two similar nature, the feeling of harmony in infinite communion. Let your vows of love with loyalty, build a good marriage, let you of the strong tower lit with fire, with the love of your life, forever burning.This is the happiest moment, the most exciting moment, make all love you the most memorable moments. May you always remember today, for the divine love to create a beautiful and harmonious space, let this memorable moments can give you bring the joy of life.Finally, the couple will lit candles with a large scale, it is only with a hundred years, is called the candles or candle, portends we pair of lovers will forever love, good years. From today on, whenever you wedding anniversary is approaching, the candle will re-ignite, you the most sincere feeling, the eternal love forever, forever continueThe couple stood before the candlestick, relative and cry, the hands hold together, eyes gently close, in soft candlelight, you made a good in the heart of the respective wishes:In such encounters, god gave you meet on the road in love, after a long expectation, today in innumerable double eye gaze, you begin a new life with lit the candle. In romantic candlelight, reflecting the bridegroom bride appear more handsome, charming appears more delicate, you put on some moments, am quite tight love beautiful sublimation, suddenly became a love eternal themeChurch wedding:Christianity baptism in the next couple of god the wedding march is played. Then the father of the bride arm slowly to the love flowers, the girl came to your life to you, all eyes staring at you. In the sacred resounded with you over the church two pairs of love and pledge. Wear tie the knot of platinum diamond, until the priest said: you can kiss your bride

Tag: cheap dresses

Cat: bridal dresses sale

Lawn wedding:The 21st century, a new fashion wedding ceremony has gradually replaced the traditional wedding ceremony.No, no reasoned fullness, special order not only healthy, this, the lawn wedding gradually by ancient people to accept. In the bosom of nature, the green lawn like a soft carpet, the boundless foiling bustling wedding scene with flowers and leaves, make the main arch ring out neatly, the long table was covered with flowers and meal. The glow of white dress, the bride incomparably namby-pamby dress. In this bustling will champagne atmosphere of open, beaming banquet begins as! Under the sun, in the sky for witness, such as feed on the lawn of sincere blessing to accept relatives, can lead to the green grass, and let the breeze lift up the bride scattered close-lying hair, in front of the photographer. She is the most natural The new music party in a beautiful dance, the children jumped in groups on the green grass, we lie in frolicking in the bosom of green grass enjoy nature, in cold weather, dressed in satisfiedearly waitress, shuttle in the crowd, for all guests provide delicacies.This is the lawn wedding scene, bright and full of festive atmosphere of whole memorable. Like the wedding is usually adopted the form of a buffet. The earth, the blue sky, the sun, and flowers, green grass for the romance of the wedding, let everybody to the beautiful nature wedding!Classical wedding:Warm and happy, publicity, classical Chinese wedding reflected in north Chinas wedding. Bride: FengGuan XiaPei, luxuriant adornment, festive colors, is typical of Chinese traditional style of the bride, Groom: shamao officer, more elegant, elegant and elegant. The bride and groom points by longfeng sedan by folk bands, saying, experience with umbrella account held the dancing lion to meet new.Then according to the traditional wedding ceremony is a series of folk arrangement ceremonies.Chinese wedding is lively atmosphere and red, the feeling of joy always pervaded the royal air.Rose wedding:Rose is most suitable for weddings, red roses symbolize love, with red roses paved road, happiness rose above held a grand wedding and make the most classic roses for your wedding ceremony add color and passion.The wedding tone can choose red and white. White gauze curtain, white antependium chair cover, and white flowers, candles, only the carpet and is red, grave and celebrations. Downy lamplight wedding banquet hall, veiled in the air and touching.Flowers chooses red roses, luxuriant and mysterious. In Taiwan, the flowers near the door, carpet, candlestick, ceremony table and chair are decorated rose.Holding hands round the bride, the red rose corolla composed represents the brides real life dreams.Ritual ceremony on both sides of the Taiwan: Taiwan has a small table, put a crystal vase full of roses.Wedding banquet: table, put up with a rose, the rose petal shining.may ball. Guest table of crystal menorah also decorated the red rose.Lightsome white gauze, red ribbons, rose still quietly bloomed, a loving hug a person walked towards the future.Lily wedding:The white color sacred purity, many of the bride and bridegroom all dream held a white wedding, but worry will have an elder obstruction of the compromise? Recommend a white lilies wedding, with pure and fresh flowers to decorate your wedding, meaning will make elders.Ceremony area:The white area is a ritual, the romantic world of scenes you remembered for a lifetime. White carpet has been out on both sides, carpet is ceremony, each six white gauze column on the top of the column of yarn is a round of white lily flower.At the end of the carpet is white lilies, metal shelf entangled with asparagus and hinting, each small silver thread fixed in a jar inside white lilies and a bouquet of bud silk, lily, is the direction of the trumpet, convey apple.later joy and blessing. And build a green with natural phenomenon.Banquet area:The sunset, a joy to the feast. The green lawn chairs and round, natural and optional mixed in. Plug in the white lily and white above for every guest, candles and composed by candlelight bouquet of fantasy world.Candlelight wedding:Wedding for everybody is the most romantic most unforgettable. Married life is a new means of stage, go more beautiful tomorrow.Friends are waiting quietly, looking forward, the couple are georgeously apparelled holy, hand out some romantic candlelight, ready to welcome the arrival of a new life, and friends together one of the most exciting moment. The flickering candlelight, shining two love each others heart, love is two similar nature, the feeling of harmony in infinite communion. Let your vows of love with loyalty, build a good marriage, let you of the strong tower lit with fire, with the love of your life, forever burning.This is the happiest moment, the most exciting moment, make all love you the most memorable moments. May you always remember today, for the divine love to create a beautiful and harmonious space, let this memorable moments can give you bring the joy of life.Finally, the couple will lit candles with a large scale, it is only with a hundred years, is called the candles or candle, portends we pair of lovers will forever love, good years. From today on, whenever you wedding anniversary is approaching, the candle will re-ignite, you the most sincere feeling, the eternal love forever, forever continueThe couple stood before the candlestick, relative and cry, the hands hold together, eyes gently close, in soft candlelight, you made a good in the heart of the respective wishes:In such encounters, god gave you meet on the road in love, after a long expectation, today in innumerable double eye gaze, you begin a new life with lit the candle. In romantic candlelight, reflecting the bridegroom bride appear more handsome, charming appears more delicate, you put on some moments, am quite tight love beautiful sublimation, suddenly became a love eternal themeChurch wedding:Christianity baptism in the next couple of god the wedding march is played. Then the father of the bride arm slowly to the love flowers, the girl came to your life to you, all eyes staring at you. In the sacred resounded with you over the church two pairs of love and pledge. Wear tie the knot of platinum diamond, until the priest said: you can kiss your bride

Tag: cheap dresses

Cat: bridal dresses sale

Its not the case that reader must be completely agreed with author's views about article. So this is what happened with me, anyways its a good effort, I appreciate it. Thanks

Pinnacle Security

The post is absolutely fantastic! Lots of great information and inspiration

salesjobsinlondon

I was looking for this information in search engines and thank god I got this information here. Thanks a lot. SEO USA

They are items of great interest and importance, thanks for the information in your blog. Diseño Web Valencia

We start with a new Android project, only thing I needed to change was to give that TextView an id in main.xml so that I could update it in the Activity.
casse amplificate|casse attive

If you understand them you can help deliver pages that will impress and illuminate your readers. A successful Web design is paramount to a successful business.

samsung rv510

We start with a new Android project, only thing I needed to change was to give that TextView an id in main.xml so that I could update it in the Activity.
Personal Finance Blogs

I did previous to. Your blog seriously brought some items to light which i never would have believed about ahead of reading through it Brad Michaels /

Sign Directory

These post are always impressive and I prefer to read quality content so I am happy to find many good points here in the post, writing is simply excellent. Was will ich werden

This information was very helpful and sad at the same time. I am really interested in Haiti this and you have really helped me learn more about that. Hopefully I can get a chance to read more about.

free cell phone spy

We start with a new Android project, only thing I needed to change was to give that TextView an id in main.xml so that I could update it in the Activity.
djstools

Very interesting articles. Good work done
batik clothing

That is genuinely helpful. I would like to ask if it would be Okay if I mentioned some of that on my own blog. Of course I would credit you and link back here also. Mike Round // Free Online Games

Web design is exciting, it changes day by day. These changes will reflect your company's complete product and service presentation. Web Design has always been made up of some basic premises, and if you understand them you can help deliver pages that will impress and illuminate your readers. A successful Web design is paramount to a successful business.

All the contents you mentioned in post is too good and can be very useful. I will keep it in mind thanks for sharing the information keep updating looking forward for more posts. Thanks. Stan Redworth // Hotelbewertungen

Thank you for the sensible critique. Me and my neighbor were just preparing to do some research about this. We got a grab a book from our local library but I think I learned more from this post. I am very glad to see such great information being shared freely out there. Kevin Wright // Urlaub in Polen

Thanks for the post and information! I think education is important for us so we must prepare the best education for our generation by sharing such great information with eachother!
crazy taxi

Excellent post. I was checking continuously this blog and I’m impressed! Very useful info particularly the last part :) I care for such information a lot. I was looking for this particular information for a very long time. Thank you and best of luck.

It's quite hard to find a good site. And I think I am lucky enough to have come here. The posts are doing great and full of good insights. I would be glad to keep on coming back here to check for updates! Sean Hough // Promotieartikelen

Thanks for this guestbook mate. Well this is my first visit to your site! But I admire the precious time and effort you put into it. keep it up! Dan Grafton // Speeltoestellen

ProgressDialog.show() function, and as a result the pd variable is initialized. We also create a new Thread using the current class as the Runnable object. When we run thread.start() a new thread w
van insurance

I know so a great deal a lot more about this than I did previous to. Your blog seriously brought some items to light which i never would have believed about ahead of reading through it Brad Michaels // autel maxidas ds708

Some things in here I have not thought about before.Thanks for making such a cool post which is really very well written.will be referring a lot of friends about this.Keep blogging. Blair Jenkins // Lanterns

I enjoy your weblog and will sign up to your feed so I will not miss anything. Fantastic content. Jess Wilcox // Limited gründen Österreich

Superb range of javea villas for sale, a wide selection of villas for sale in Javea from 2 bedroom semi detached to 6 bedroom luxury with sea views.

Easily the post is really the greatest on this laudable topic. I concur with your conclusions and will thirstily look forward to your future updates. Saying thanks will not just be sufficient for the fantastic c lucidity in your writing. I will instantly grab your rss feed to stay privy of any updates. Solid work and much success in your business enterprise! Jack McQuade // Wedding Photographer Essex

Im glad to have found this post as its such an interesting one! I am always on the lookout for quality posts and articles so i suppose im lucky to have found this! I hope you will be adding more in the future... Lily Connely // online classified ads

I think I could disagree with the main ideas. I won't share it with my friends.. You should think of other ways to express your ideas. Alex Hill // leaflet printing

I think I will become a great follower.Just want to say your article is striking. The clarity in your post is simply striking and i can take for granted you are an expert on this subject. Steven Bants // Network Marketing

I really appreciate the kind of topics you post here. Thanks for sharing information that is actually helpful. Good day! Michael Hough // Khosrow Semnani

Substantially the article is really the best on this laudable topic. I concur with your conclusions and will eagerly look forward to your future updates.Just saying thank you will not just be enough for the wonderful lucidity in your writing. James Lawrence // s oliver

Well I am so excited that I have found your post because I have been searching for some information on this for almost three hours! You've helped me a lot indeed and by reading this article I have found many new and useful information about this subject! John Green // erectile dysfunction treatment

Its really wonderful and watchable. I like to share it with all my friends and hope they will like it

My blog : Web Design Miami | Miami Web Design

Thanks for the amazing content on your blog I am very interested in this article and you have really helped me. I have just told a few of my friends about this on FaceBook and they love your content just as much as I do. John Martin // Khosrow Semnani

Woah this is just an insane amount of information must of taken ages to compile so thank you so much for just sharing it with all of us. If your ever in any need of related info perhaps a bit of coaching seduction techniques or just general tips just check out my own site!
Bruno, from Android News

Thanks dude for giving code to use threads while ProgressDialog. That is really great! I hope this would be useful for all. Thanks!

joomla website development | Joomla Development Companies | register domain in india | Hire Joomla Developers

This article gives the light in which we can observe the reality. this is very nice one and gives in-depth information. thanks for this nice article Charlotte Cooper // electrician Brea

Fommy.com - One Stop online store for all your Casio GzOne Commando C771 Accessories, GzOne Commando C771 Accessories need like GzOne Commando C771 Batteries, GzOne Commando C771 Bluetooth Car Kits, GzOne Commando C771 Cables, GzOne Commando C771 Cases, GzOne Commando C771 Chargers, GzOne Commando C771 Headphones, GzOne Commando C771 Headsets, GzOne Commando C771 Memory Cards, GzOne Commando C771 Miscellaneous, GzOne Commando C771 Screen Protectors, GzOne Commando C771 Speakers, GzOne Commando C771 Stylus, GzOne Commando C771 Vehicle Mounts and more.

For more details, visit here href="http://www.fommy.com/casio-gzone-commando-c771.htm" title="Casio G'zOne Commando Accessories" rel="dofollow">Casio G'zOne Commando Accessories | href="http://www.fommy.com/accessories.php?make=Casio&model=Casio+GzOne+Commando+C771&cat=Cases" title="Casio GzOne Commando Case" rel="dofollow">Casio GzOne Commando Case | href="http://www.fommy.com/accessories.php?make=Casio&model=Casio+GzOne+Commando+C771&cat=Screen+Protectors" title="Casio GzOne Commando Screen Protector" rel="dofollow">Casio GzOne Commando Screen Protector

Easily the post is really the greatest on this laudable topic. I concur with your conclusions and will thirstily look forward to your future updates. Saying thanks will not just be sufficient for the fantastic c lucidity in your writing. I will instantly grab your rss feed to stay privy of any updates. Solid work and much success in your business enterprise! Tim Whicher // Apple News

Thanks for posting this informative article. I haven't any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us. Skye Konah // Khosrow Semnani

This is such an informative article and very clearly written. Every single thought and idea is direct to the point. Perfectly laid out. Thank you for taking your time sharing this to you readers. David Hardy // Holzterrasse