The handler mechanism is a very common way to implement communication between threads, which is often used.
Packagecom.lab.activity;Importandroid.app.Activity;ImportAndroid.app.Dialog;ImportAndroid.app.ProgressDialog;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button; Public classProgressdialogtestextendsActivity {//The program simulates populating an array with a length of 100 Private int[] data =New int[100]; intHasData = 0; //define the identity of the progress dialog box Final intProgress_dialog = 0x112; //percent Complete of recording progress dialog box intProgressstatus = 0; ProgressDialog PD; //define a handler that is responsible for the progress of the updateHandler Handler; Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.main); Button EXECBN=(Button) Findviewbyid (r.id.exec); Execbn.setonclicklistener (NewOnclicklistener () { Public voidOnClick (View source) {ShowDialog (progress_dialog); } }); //Handler Message ProcessingHandler =NewHandler () { Public voidhandlemessage (Message msg) {if(Msg.what = =Progress_dialog) {pd.setprogress (progressstatus); } }; }; } @Override PublicDialog Oncreatedialog (intID, Bundle status) {System.out.println ("Create"); Switch(ID) { CaseProgress_dialog://Create Progress dialog boxPD =NewProgressDialog ( This); Pd.setmax (100); //setting the caption of a dialog boxPd.settitle (% Task complete)); //setting what the dialog box displaysPd.setmessage ("percent complete for time-consuming tasks"); //The Settings dialog box cannot be closed with the Cancel buttonPd.setcancelable (false); //set the progress bar style of the dialog boxPd.setprogressstyle (progressdialog.style_horizontal); //sets whether the progress bar of the dialog box shows ProgressPd.setindeterminate (false); Break; } returnPD;} //The method will be recalled after the Oncreatedialog method call@Override Public voidOnpreparedialog (intID, Dialog Dialog) {System.out.println ("Prepare"); Super. Onpreparedialog (ID, Dialog); Switch(ID) { CaseProgress_dialog://dialog box Progress clear 0Pd.incrementprogressby (-pd.getprogress ()); NewThread () { Public voidrun () { while(Progressstatus < 100) { //get percent complete for time-consuming operationsProgressstatus =doWork (); //send message to HandlerMessage message =Handler.obtainmessage (); Message.what=Progress_dialog; Handler.sendmessage (message); } //if the task is completed if(Progressstatus >= 100) { //Close the dialog boxPd.dismiss (); }}}.start (); Break; } } //simulates a time-consuming operation. Public intdoWork () {//Assigning a value to an array elementdata[hasdata++] = (int) (Math.random () * 100); Try{Thread.Sleep (100); } Catch(interruptedexception e) {e.printstacktrace (); } returnhasData;}}
An example of the Android handler mechanism