Android Handler usage
Handler is generally used by subthreads to send messages to the main thread for the main thread to process things related to the UI. Why is it used in the subthread? If the main thread processes too much time-consuming things, it may lead to a false death. Therefore, it is generally placed in the subthread to process time-consuming things.
First look at the interface above. This is the case. simulate a time-consuming operation and close the dialog box after the download is complete.
Check the main Activity:
Package com. howlaa. lesson27_handler; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. app. activity; import android. app. progressDialog; import android. content. res. resources; import android. util. log; import android. view. menu; import android. view. view; import android. widget. button; public class MainHandler extends Activity {// declare the variable private Button b1; private Progress Dialog pd; // define the Handler object private Handler handler = new Handler () {@ Override // when a Message is sent, execute the Handler public void handleMessage (Message msg) {super. handleMessage (msg); // close the dialog box pd as long as it is executed here. dismiss () ;};@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main_handler); Resources res = this. getResources (); // view the thread name of the UI component Lo G. I ("tag", "onCreate () -->" + Thread. currentThread (). getName (); // defines the UI component b1 = (Button) findViewById (R. id. button01); // bind to the button click event listener b1.setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {// click the button to process the long-time operation processThread () ;}});} private void processThread () {// build a download progress bar pd = ProgressDialog. show (MainHandler. this, "download file", "download ...... "); Log. I ("tag", "processThread () -->" + Thread. currentThread (). getName (); new Thread () {@ Override public void run () {Log. I ("tag", "run () -->" + Thread. currentThread (). getName (); // longTimeMethod (), the method that takes long execution in the new thread; // an empty message handler is sent to handler after execution. sendEmptyMessage (0 );}}. start () ;}// simulates the time-consuming Method for downloading objects. private void longTimeMethod () {try {Log. I ("tag", "longTimeMethod -->" + Thread. currentThread (). getName (); Thread. sleep (10000);} catch (InterruptedException e) {e. printStackTrace ();}}}You do not need to paste the layout interface.