Android----thread+handler thread message loop (reprint)

Source: Internet
Author: User
Tags message queue

Recently found some information about the communication between Android threads, organized and learned a bit, and made a simple example.

Andriod provides Handler and Looper to meet the communication between threads. For example, a sub-thread downloads a picture from the network and sends a message to the main thread when it is downloaded, and this message is passed by binding to the handler of the main thread.

On Android, where threads are divided into message loop threads and no message loops, threads that have a message loop will generally have a new concept of looper, the thing about Android. Our main thread (the UI thread) is the one that threads the message loop. For this kind of message loop mechanism, we introduce a new mechanism handle, we have the message loop, we must send the corresponding message in the message loop, the custom message will have its own corresponding processing, the message is sent and purged, the processing of the message, these are encapsulated in the handle inside, Note that handle is only for those threads that have looper, whether it's the UI thread or the child thread, as long as you have looper, I can add something to your message queue and handle it accordingly.
But here's another point, as long as it is about UI-related things, it cannot be placed in a child thread, because the child thread cannot manipulate the UI, only the data, the system and other non-UI operations.
On Android, where threads are divided into message loops and no message loops, threads with message loops generally have a looper, a new concept for Android. Our main thread (the UI thread) is the one that threads the message loop. For this kind of message loop mechanism, we introduce a new mechanism handler, we have the message loop, we must send the corresponding message in the message loop, the custom message will have its own corresponding processing, the message is sent and cleared, these are encapsulated in the handler inside, Note that handler is only for those threads that have looper, whether it's the UI thread or the child thread, as long as you have looper, I can add something to your message queue and handle it accordingly.

But here's another point, as long as it is about UI-related things, it cannot be placed in a child thread, because the child thread cannot manipulate the UI, only the data, the system and other non-UI operations.


The creation of a handler will be bound to the message queue of this thread, if it is created on the primary thread, there is no need to write code to create the message queue, the default message queue will be created on the main thread. However, if you are on a child thread, you must initialize the thread's message queue before creating the handler. As in the following code:

Java code
  1. Class Childthread extends Thread {
  2. public Void Run () {
  3. /* 
  4. * Initialize Looper before creating handler.
  5. */
  6. Looper.prepare ();
  7. /* 
  8. * Handler is created on a child thread, so it is bound to a child thread in the message queue
  9. *
  10. */
  11. Mchildhandler = New Handler () {
  12. public void Handlemessage (Message msg) {
  13. /* 
  14. * Do some expensive operations there.
  15. */
  16. }
  17. };
  18. /* 
  19. * Start Message Queuing for this thread
  20. */
  21. Looper.loop ();
  22. }
  23. }





When handler receives the message, it runs Handlemessage (...). callback function, you can do some time-consuming operations inside.




Finally completes the operation to end the child thread, remember to call quit () to end the message loop queue.

Mchildhandler.getlooper (). Quit ();



Here is a small example of a communication between threads:

Java code
  1. /**
  2. *
  3. * @author Allin.dev
  4. * http://allin.cnblogs.com
  5. *
  6. */
  7. Public class Mainthread extends Activity {
  8. private static final String TAG = "Mainthread";
  9. private Handler Mmainhandler, Mchildhandler;
  10. private TextView info;
  11. private Button msgbtn;
  12. @Override
  13. public void OnCreate (Bundle savedinstancestate) {
  14. super.oncreate (savedinstancestate);
  15. Setcontentview (R.layout.main);
  16. info = (TextView) Findviewbyid (r.id.info);
  17. MSGBTN = (Button) Findviewbyid (R.ID.MSGBTN);
  18. Mmainhandler = New Handler () {
  19. @Override
  20. public void Handlemessage (Message msg) {
  21. LOG.I (TAG, "Got an incoming a message from the child thread-"
  22. + (String) msg.obj);
  23. //Receive messages for child threads
  24. Info.settext ((String) msg.obj);
  25. }
  26. };
  27. new Childthread (). Start ();
  28. Msgbtn.setonclicklistener (new Onclicklistener () {
  29. @Override
  30. public void OnClick (View v) {
  31. if (mchildhandler! = null) {
  32. //Send message to child thread
  33. Message childmsg = Mchildhandler.obtainmessage ();
  34. Childmsg.obj = Mmainhandler.getlooper (). GetThread (). GetName () + "says Hello";
  35. Mchildhandler.sendmessage (CHILDMSG);
  36. LOG.I (TAG, "Send a message to the child thread-" + (String) childmsg.obj);
  37. }
  38. }
  39. });
  40. }
  41. public void OnDestroy () {
  42.       Super.ondestroy ();
  43. LOG.I (TAG, "Stop looping the child thread ' s Message queue");
  44. Mchildhandler.getlooper (). Quit ();
  45. }
  46. class Childthread extends Thread {
  47. private static final String Child_tag = "Childthread";
  48. public Void Run () {
  49. this.setname ("Childthread");
  50. //Initialize the message loop queue and need to be before handler is created
  51. Looper.prepare ();
  52. Mchildhandler = New Handler () {
  53. @Override
  54. public void Handlemessage (Message msg) {
  55. LOG.I (Child_tag, "Got a incoming message from the main thread-" + (String) msg.obj);
  56. try {
  57. //Can do some time-consuming work in a child thread
  58. Sleep (100);
  59. Message Tomain = Mmainhandler.obtainmessage ();
  60. Tomain.obj = "This is" + this.getlooper (). GetThread (). GetName () +
  61. ". Did you send me \ "" + (String) msg.obj + "\"? ";
  62. Mmainhandler.sendmessage (Tomain);
  63. LOG.I (Child_tag, "Send a message to the main thread-" + (String) tomain.obj);
  64. } catch (Interruptedexception e) {
  65. //TODO auto-generated catch block
  66. E.printstacktrace ();
  67. }
  68. }
  69. };
  70. LOG.I (Child_tag, "Child handler was bound to-" + mchildhandler.getlooper (). GetThread (). GetName ());
  71. //Start child thread message loop queue
  72. Looper.loop ();
  73. }
  74. }
  75. }

Android----thread+handler thread message loop (reprint)

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.