Android_handler (3)
In the android message mechanism, MainThread sends messages to WorkThread. (MainThread → WorkThread)
Steps:
1. Prepare logoff objects
2. Generate a handler object in the Child thread
3. Send messages in MainThread
Code:
Layout:
Activity:
Package com. away. B _08_handler03; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. logoff; import android. OS. message; import android. view. view; import android. view. view. onClickListener; import android. widget. button; public class MainActivity extends Activity {private Button button; private Handler handler; @ Overrideprotected void onCreate (Bundle savedInstanceS Tate) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); button = (Button) findViewById (R. id. buttonId); button. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {System. out. println (OnClick: + Thread. currentThread (). getName (); Message msg = handler. obtainMessage (); handler. sendMessage (msg) ;}}); WorkerThread wt = new WorkerThread (); wt. start ();} class WorkerThread extends Thread {@ Overridepublic void run () {// prepare the logoff object logoff. prepare (); // In the Workers Thread, generate a Handler object and implement handler = new Handler () {@ Overridepublic void handleMessage (Message msg) {System. out. println (WorkerThread: + Thread. currentThread (). getName (); System. out. println (message object received !!);}}; // After The logoff loop method is called, The logoff object will continuously retrieve the message object from the message queue, and then call handleMessage () of Handler () method to process the message object // if there is no object in the message queue, the thread is blocked. logoff. loop ();}}}Effect: