Some time-consuming operations are often used in applications, and users need to wait, such as loading webpage content ......
At this time, you need a prompt to tell the user that the program is being executed, and there is no false or real death ...... ......
Progressbar and progressdialog are dedicated for this purpose.
Take progressdialog as an example. Generally, the following steps are used: The progressdialog prompt is displayed before the time-consuming operation is executed, and a new thread is opened to execute time-consuming operations in the new thread, after the execution is completed, the main program is notified to end progressdialog.
The following is a demo, which is easy to use:
[Java]
View plaincopyprint?
- Package com. Android. UI;
- Import Android. App. activity;
- Import Android. App. progressdialog;
- Import Android. OS. Bundle;
- Import Android. OS. Handler;
- Import Android. OS. message;
- Import Android. View. view;
- Import Android. View. View. onclicklistener;
- Import Android. widget. Button;
- Public class mainactivity extends activity {
- Private button;
- Private progressdialog PD;
- @ Override
- Public void oncreate (bundle savedinstancestate ){
- Super. oncreate (savedinstancestate );
- Setcontentview (R. layout. Main );
- Button = (button) findviewbyid (R. Id. button1 );
- Button. setonclicklistener (New onclicklistener (){
- @ Override
- Public void onclick (view v ){
- /* Display progressdialog */
- Pd = progressdialog. Show (mainactivity. This, "title", "loading... please wait ...... ");
- /* Start a new thread and execute time-consuming methods in the new thread */
- New thread (New runnable (){
- @ Override
- Public void run (){
- Spandtimemethod (); // time-consuming Method
- Handler. sendemptymessage (0); // sends the message to handler after the time-consuming method is executed.
- }
- }). Start ();
- }
- });
- }
- Private void spandtimemethod (){
- Try {
- Thread. Sleep (5000 );
- } Catch (interruptedexception e ){
- // Todo auto-generated Catch Block
- E. printstacktrace ();
- }
- }
- Handler handler = new handler (){
- @ Override
- Public void handlemessage (Message MSG) {// handler will execute this method after receiving the message
- PD. Dismiss (); // close progressdialog
- }
- };
- }
Main. there is only one button in XML and it will not be pasted. The program should be well understood. After clicking the button, progressdialog will pop up and time-consuming operations (thread. sleep (5000);). After the execution is complete, notify handler and end progressdialog.
The running effect is as follows: