Android_handler (3)

Source: Internet
Author: User

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:

 


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.