An example analysis of the message mechanism of Android programming _android

Source: Internet
Author: User
Tags message queue

This example describes the messaging mechanism for Android programming. Share to everyone for your reference, specific as follows:

I. Description of the role

1.Looper: A thread can produce a Looper object that manages the message queue Chengri this line.

2.Handler: You can construct Handler objects to communicate with Looper in order to push new messages into message queue, or to receive messages sent by Looper (removed from message queue).

3. Message queue: A message that is used to store threads in.

4. Thread: UI thread is usually the main thread, and Android launches a message Queue for the program.

Each thread can contain a Looper object and a MessageQueue data structure. In your application, you can define subcategories of handler to receive messages sent by Looper.

In your Android program, when a new thread is born, or executes (thread), it does not automatically create its message Loop.

There is no global message queue data structure in Android, for example, objects in different apk cannot exchange messages through the massage queue.

For example, a handler object of thread A can pass messages to other threads, allowing other threads such as B or C to send messages to thread A (in the message queue of a).

Message queue in thread A, only the object that thread a belongs to can be handled.

Use Looper.mylooper to get the Looper object for the current thread.

Use Mhandler = new Eevnthandler (Looper.mylooper ()); The handler object that can be used to construct the current thread, where Eevnthandler is a subcategory of the implemented handler.

Use Mhandler = new Eevnthandler (Looper.getmainlooper ()); A handler object that can be used to process a main thread, where Eevnthandler is a subcategory of a handler that has been implemented.

This description may be too similar, and here are a few practical examples to illustrate:

Second, for example

1. Message delivery between different components within the same thread

The Looper class is used to manage the exchange of messages between objects within a particular thread (message exchange). Your application can produce a number of threads. A thread can have many components, and these components often need to exchange messages with each other. If this is necessary, you can construct a Looper object for the thread to manage the exchange of messages. The Looper object creates a MessageQueue data structure that holds messages from each object (including UI events or system events, etc.).

Each thread can contain a Looper object and a MessageQueue data structure. In your application, you can define subcategories of handler to receive messages sent by Looper.

Message delivery between different components of the same thread:

public class Activity1 extends activity implements onclicklistener{button button = null;
  TextView text = null;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (r.layout.activity1);
    Button = (button) Findviewbyid (R.ID.BTN);
    Button.setonclicklistener (this);
  Text = (TextView) Findviewbyid (r.id.content); public void OnClick (View v) {switch (V.getid ()) {case R.id.btn:looper looper = Looper.mylooper ();//Get The Looper MyHandler of the current line Chengri Mhandler = new MyHandler (looper);//construct a handler that can be used with looper communication//buton components can pass messages to Lo by Mhandler
      Oper, and then into the MessageQueue, Mhandler can also accept from Looper message mhandler.removemessages (0);
      String msgstr = "Main thread different component communication: Message from Button"; Message m = mhandler.obtainmessage (1, 1, 1, MSGSTR);//construct messages to be passed Mhandler.sendmessage (m); Send message: The system automatically invokes the Handlemessage method
    to handle message break; } private class MyHandler extends handler{public MyHandler (Looper LoOper) {super (Looper);
    @Override public void Handlemessage (message msg) {//Processing messages Text.settext (msg.obj.toString ());

 }
  }
}

Description

When this program starts, the current thread (that is, the main thread, main thread) has a Looper object and has a MessageQueue data structure.

Copy Code code as follows:
Looper = Looper.mylooper ();

Call the static Mylooper () function of the Looper category to get the Looper object for the current line Chengri.
Copy Code code as follows:
Mhandler = new MyHandler (looper);

Construct a MyHandler object to communicate with Looper. Objects such as activity can pass messages to Looper by MyHandler objects and then into MessageQueue; MyHandler objects also play the role of listener to receive messages from Looper objects.
Copy Code code as follows:
Message m = mhandler.obtainmessage (1, 1, 1, obj);

Construct a Message object and deposit the data in the object.
Copy Code code as follows:
Mhandler.sendmessage (m);

Pass the message m to the Looper through the Mhandler object and then into the MessageQueue.

At this point, the Looper object sees the message m in the MessageQueue, broadcasts it, and mhandler the object to its handlemessage () function when it receives the message, and then outputs "This my message!" On the screen,
Role Overview (Review):

(1) UI thread is usually the main thread, and Android launches the program to create a MessageQueue for it.
(2) Of course, a Looper object is needed to manage the MessageQueue.
(3) We can construct handler objects to push new messages into message queue, or receive messages sent by Looper (removed from message queue).
(4) Thread A's handler object can be passed to other threads, allowing other threads such as B or C to send messages to thread A (in the message queue of a).
(5) Message queue of thread A, only the object that thread a belongs to can be handled.

Child thread passes message to main thread

public class Activity2 extends activity implements onclicklistener{button button = null;
  TextView text = null;
  MyHandler mhandler = null;
  Thread thread;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);  
    Setcontentview (r.layout.activity1);
    Button = (button) Findviewbyid (R.ID.BTN);
    Button.setonclicklistener (this);
  Text = (TextView) Findviewbyid (r.id.content);
      public void OnClick (View v) {switch (V.getid ()) {Case r.id.btn:thread = new Mythread ();
      Thread.Start ();
    Break
    } private class MyHandler extends handler{public MyHandler (Looper looper) {super (Looper);
    @Override public void Handlemessage (message msg) {//Processing messages Text.settext (msg.obj.toString ()); } private class Mythread extends thread{@Override public void Run () {Looper curlooper = looper.my
      Looper (); Looper Mainlooper = Looper.getmainlooPer ();
      String msg;
       if (curlooper==null) {Mhandler = new MyHandler (mainlooper);
      msg = "Curlooper is null";
       }else{Mhandler = new MyHandler (curlooper);
      msg = "This is Curlooper";
      } mhandler.removemessages (0);
      Message m = mhandler.obtainmessage (1, 1, 1, msg);
    Mhandler.sendmessage (m);

 }
  }
}

Description

Android automatically creates a message Queue for the main thread. In this strand Chengri does not establish a message Queue. Therefore, the Mylooper value is null, while the mainlooper points to the looper of the mainline Chengri. So, execute to:

Copy Code code as follows:
Mhandler = new MyHandler (mainlooper);

This mhandler belongs to the main thread.
Copy Code code as follows:
Mhandler.sendmessage (m);

The M message is deposited into the main thread's messages queue. Mainlooper sees messages in the message queue, it handles them, and the main thread executes to Mhandler's handlemessage () to process the message.

I hope this article will help you with the Android program.

Related Article

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.