7.1 Basics Android Message processing mechanism

Source: Internet
Author: User
Tags getmessage

1. Android message processing mechanism: Handler, MessageQueue, Looper, Thread

Threading Concept: When an application runs its body is called a process,
There can be multiple threads inside a process,
Resources for thread-sharing processes
Inter-thread communication

In the Android system is how to encapsulate the communication, if there are two threads A and B, if a thread to tell the B thread some messages, how to implement?

How does a process send messages? (1) Constructs the message, the message inside has the data information and the processing function (2) sends the message, these two steps are encapsulated in the Android source code as Handler

Messages are encapsulated as Message,a in Android to send a message to B, maybe B cannot handle it, so a puts the message into the message queue MessageQueue class in the B process, what does it do in the loop body of the B process?

(1), remove the message from the queue, (2) process the message, execute the message processing function, these two steps are encapsulated into Looper in the Android source code

Looper Source in Frameworks/base/core/java/android/os/looper.java

Handler source in Frameworks/base/core/java/android/os/handler.java//ctrl+shift+n in the input Handler.java to open

A. Creating MessageQueue:Looper.prepare ()
B. Using handler to construct, send a message
B.1 New Handler//Create Handler You can specify that the Looper is the message recipient and the callback callback function is the message handler function, if you do not know there must be a default looper and message processing functions
B.2 Handler.sendmessage, Sendemptymessageattime, sendmessagedelayed

C. Using the Looper loop to process messages: there is a For loop in the loop function
C.1 Remove Message,//message msg = Queue.next () from MessageQueue;
C.2 executes its handler function: Msg.target.dispatchMessage (msg)//target is the handler,dispatchmessage that invokes the handler function

  

Application Authoring:

Function Description: Create a button in the app, create a child thread, add a message processing function, and add a handler function to the button, and the main thread will monitor the button, send a message to the child thread when the button is pressed, and the child will print after receiving the message.

Import Android.view.View;

Import android.util.log;//Print imported libraries

public class Mainactivity extends appcompatactivity{

Private Button Mbutton;

Private final String TAG = "Messagetest";

private int buttoncount = 0;

Private Thread MyThread;

Private MyThread myThread2;

Private Handler Mhandler;

private int mmessagecount = 0;

Class Myrunnable:implements runable{

int count=0;

public void Run () {

for (;;) {

LOG.D (TAG, "MyThread" + (count++));

try{

Thread.Sleep (3000);

}catch (Interrupteexception e) {

E.printstacktrace ();

}

}

}

}

Class Mythread extends thread{//android only with the message processing is in Handlerthread.java, its function with how we Mythread, if not to create their own Mythread, You can use the Handlerthread class directly

public void Run () {

Super.run ();

Looper.prepare ();//Create Message Queue

Looper.loop ();//Remove the message from the message queue, call the handler for the message

}

Public Looper Getlooper () {

return Looper.mylooper ();

}

}

pretected void OnCreate (Bundle savedinstancestate) {

........

........

Mbutton = (Button) Findviewbyid (R.id.button);//Double-click the button and press SHIFT+F1 to view the help document for the class

Mbutton.setonclicklistener (New View.onclicklistener () {

public void OnClick (View v) {

LOG.D (TAG, "SendMessage" + (buttoncount++));

Message msg = new Message ();

Mhandler.sendmessage (msg);//messages are sent from the message queue, and Message Queuing is obtained from Looper when handler is created

}

});

MyThread = new Thread (new myrunnable, "Messagetestthread");//(Method of Runnable interface run is the principal function of the thread)

Mythread.start ();

MyThread2 = new MyThread ();

MyThread2. Start ();//Functions like mythread, start causes the Mythread run function to be executed, and the Run function executes Looper.prepare () to create the message queue, but this function is not necessarily executed immediately. If there is no queue when creating handler in the live process, there is a risk, so modify class MyThread extends thread{}

We now have three threads in the code, the main thread, Mythread and myThread2, to determine who the message is sent to Looper

Mhandler = new Handler (Mythread2.getlooper (), new Handler.callback () {

public boolean handlemessage (Message msg) {

LOG.D (TAG, "getMessage" + (mmessagecount++))

return false;

}

});

}

}

Modify the class MyThread extends thread{} for the risks described above, as follows:

Class MyThread extends thread{

Private Looper Mlooper;

public void Run () {

Super.run ();

Looper.prepare ();//Create Message Queue

Mlooper = Looper.mylooper ();

Notifyall ();//When the main thread calls Getlooper, it sleeps when the mlooper is empty, so it needs to wake up the dormant thread

Looper.loop ();//Remove the message from the message queue, call the handler for the message

}

Public Looper Getlooper () {

if (!isalive ()) {

return null;

}

Synchronized (this) {

while (IsAlive () && mlooper = = null) {

try{

Wait ();

}catch (Interruptedexception e) {

}

}

}

return mlooper;

}

}

Modify the code to use the system-only message processing thread:

1, Import Package: Imports Android.os.HandlerThread;

2. New in public class Mainactivity extends appcompatactivity

Private Handlerthread myThread3;

Private Handler MHandler3;

MyThread3 = new Handlerthread ("MessageTestThread3");

MyThread3. Start ();

MHandler3 = new Handler (Mythread3.getlooper ());

In the onclick function of the button, add:

Mhandler3.post (New Runnable () {

public void Run () {

LOG.D (TAG, "GetMessage for Thread3" + (mmessagecount++));

}

});

  

7.1 Basics Android Message processing mechanism

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.