Synthesis: http://blog.csdn.net/dadoneo/article/details/7667726 and http://android.tgbus.com/Android/androidnews/201204/421642.shtml
I. Introduction and use of common classes of message mechanisms
In the case of Android programs, messages are often used when interacting between threads or within threads, and if we are familiar with these basics and their internal principles, it will make our Android development easier and more architecture-ready. Before learning about the Android messaging mechanism, let's look at a few classes related to messages: The message mechanism for Android mainly involves three main classes, namely handler, message, Looper;
1.Message
A Message object, as the name implies, is the class that records message information. There are several more important fields for this class:
A.arg1 and Arg2: We can use two fields to hold the integer value we need to pass, and in the service we can store the service ID.
B.obj: This field is an object type, and we can let the field pass a number of items to the recipient of the message.
C.what: This field can be said to be a message flag, in the message processing, we can according to the different values of this field to do different processing, similar to when we handle the button event, through switch (V.getid ()) to determine which button is clicked.
When using the message, we can create a message instance from the new message (), but Android recommends that we pass Message.obtain () or handler.obtainmessage () Gets the message object. This is not necessarily a straightforward creation of a new instance, but rather a message instance that is immediately available from the pool of messages, and is then fetched and returned to this instance. Conversely, if there is no message instance available in the pool, a new message object is given according to the parameter. By analyzing the source, it is known that the Android system instantiates 10 message objects in a messaging pool by default.
2.MessageQueue
Message Queuing, which holds the data structure of the message object and stores the message according to the "FIFO" principle. Storage is not a meaningful save, but instead the message object is concatenated in a linked list. MessageQueue objects do not need to be created by ourselves, but have looper objects to manage them, and a thread can have at most one MessageQueue. We can get the MessageQueue in the current thread through Looper.myqueue ().
3.Looper
MessageQueue manager, in a thread, if there is a Looper object, there must be a MessageQueue object, and there is only one Looper object and one MessageQueue object. In Android, except the main thread has the default Looper object, other threads have no Looper object by default. If you want our newly created thread to have a Looper object, we should first call the Looper.prepare () method and then call the Looper.loop () method. Typical usage is as follows:
Class Looperthread extends Thread
{
Public Handler Mhandler;
public void Run ()
{
Looper.prepare ();
Other operations that need to be handled
Looper.loop ();
}
}
4.Handler
Handler has two main uses: The first is the ability to process or distribute messages on a timed basis, followed by the ability to add an execution that executes in other threads,
For the method in handler, you can choose the action you care about to overwrite it, handle the specific business operation, the common is that the processing of the message can overwrite the public voidhandlemessage (parameter) method, You can choose whether or not this message needs to be handled according to the parameters, which are related to the specific parameters.
The processor of the message. Through the handler object we can encapsulate the message object and then add the message object to the MessageQueue through SendMessage (msg), and when MessageQueue loops to the message, The Handlemessage () method of the handler object corresponding to the message object is called to process it. Because the messages are processed in the Handlemessage () method, we should write a class that inherits from handler and then handles the operations we need in Handlemessage ().
Below we analyze how messages are handled in Android by tracking code. First put the test code:
public class Messageservice extends Service
{
private static final String TAG = "Messageservice";
private static final int KUKA = 0;
Private Looper Looper;
Private Servicehandler handler;
/**
* Because processing messages is in Handler's Handlemessage () method, we need to write our own class
* Inherit from the handler class, then write the function code we need in Handlemessage ()
* @author Coolszy
*
*/
Private Final class Servicehandler extends Handler
{
Public Servicehandler (Looper Looper)
{
Super (Looper);
}
@Override
public void Handlemessage (Message msg)
{
Determine which message is based on what field
Switch (msg.what)
{
Case KUKA:
Gets the obj field of the MSG. We can write the function code we need here.
LOG.I (TAG, "The obj field of msg:" + msg.obj);
Break
Other cases
Default
Break
}
If our service has completed the task, stop the service
Stopself (MSG.ARG1);
}
}
@Override
public void OnCreate ()
{
LOG.I (TAG, "messageservice-->oncreate ()");
Service is run in the main thread by default, and services are typically time consuming, if
In the main thread, it will affect the interaction between the program and the user, so the service
Put in a separate thread to execute
Handlerthread thread = new Handlerthread ("Messagedemothread", Process.thread_priority_background);
Thread.Start ();
Gets the Looper object in the current thread
Looper = Thread.getlooper ();
Create a handler object and pass the Looper over to make handler,
Looper and MessageQueue Connect
Handler = new Servicehandler (looper);
}
@Override
public int Onstartcommand (Intent Intent, int flags, int startid)
{
LOG.I (TAG, "Messageservice-->onstartcommand ()");
Get a message instance from the messaging pool
Message msg = Handler.obtainmessage ();
Arg1 the ID of the save thread in the Handlemessage () method
We can stop the service by Stopself (Startid) method
MSG.ARG1 = Startid;
The Flag of MSG
Msg.what = KUKA;
Here I create a Date object that assigns a value to the obj field
In practice we can pass the object we need to handle through obj
Date date = new Date ();
Msg.obj = date;
Add MSG to the MessageQueue
Handler.sendmessage (msg);
return start_sticky;
}
@Override
public void OnDestroy ()
{
LOG.I (TAG, "Messageservice-->ondestroy ()");
}
@Override
Public IBinder Onbind (Intent Intent)
{
return null;
}
}
Below we analyze the running process of the program:
1.onCreate ()
Starting the service first invokes the OnCreate () method, in which we new a Handlerthread object that provides the name and priority of the thread.
Immediately after we call the start () method, executing the method will invoke the run () method of the Handlerthread object:
public void Run () {
Mtid = Process.mytid ();
Looper.prepare ();
Synchronized (this) {
Mlooper = Looper.mylooper ();
Notifyall ();
}
Process.setthreadpriority (mpriority);
Onlooperprepared ();
Looper.loop ();
Mtid =-1;
}
In the Run () method, the system adds a looper to the thread and calls the Looper loop () method:
public static final void loop () {
Looper me = Mylooper ();
MessageQueue queue = Me.mqueue;
while (true) {
Message msg = Queue.next (); Might block
if (!me.mrun) {
Break
//}
if (msg! = null) {
if (Msg.target = = null) {
No Target is a magic identifier for the quit message.
Return
}
if (me.mlogging!= null) me.mLogging.println ("dispatching to" + Msg.target + "" + Msg.callback + ":" + msg.what);
Msg.target.dispatchMessage (msg);
if (me.mlogging!= null) me.mLogging.println ("finished to" + Msg.target + "" + msg.callback);
Msg.recycle ();
}
}
}
Through the source we can see that the loop () method is a dead loop, will continue to get the message object from the MessageQueue object, if there is no message object in the MessageQueue object, then the loop is closed, and then the loop continues; If there is a Message object, the Msg.target.dispatchMessage (msg) is executed, but what is the value of the. Target field of this msg? We'll stop tracking the source code and return to the OnCreate () method. After the thread finishes executing the start () method, we can get the thread's Looper object and then new a Servicehandler object, and we'll pass the Looper object to the Servicehandler constructor to make the handler, Looper and MessageQueue to establish contact.
2.onStartCommand ()
After you finish executing the OnStart () method, the Onstartcommand () method is executed. First we get a message instance from the messaging pool, and then assign values to the arg1, what, and obj three fields of the messages object. Immediately following the call to the SendMessage (msg) method, we trace the source code, the method will call the sendmessagedelayed (MSG, 0) method, and Sendmessagedelayed () The method also calls the Sendmessageattime (msg, systemclock.uptimemillis () + Delaymillis) method, in which we want to notice that the code of the sentence Msg.target = this, The target of MSG points to this, and this is the Servicehandler object, so the target field of MSG points to the Servicehandler object, and the method calls MessageQueue Enqueuemessage (msg, Uptimemillis) method:
Final Boolean enqueuemessage (Message msg, long when) {
if (Msg.when! = 0) {
throw New Androidruntimeexception (msg
+ "This message is already.");
}
if (Msg.target = = null &&!mquitallowed) {
throw new RuntimeException ("Main thread not allowed to quit");
}
Synchronized (this) {
if (mquiting) {
RuntimeException e = new RuntimeException (
Msg.target + "Sending message to a Handler on a dead thread");
LOG.W ("MessageQueue", E.getmessage (), E);
return false;
} else if (Msg.target = = null) {
Mquiting = true;
}
Msg.when = when;
LOG.D ("MessageQueue", "enqueing:" + msg);
Message p = mmessages;
if (p = = NULL | | when = = 0 | | When < p.when) {
Msg.next = p;
Mmessages = msg;
This.notify ();
} else {
Message prev = null;
while (P! = null && p.when <= when) {
prev = p;
p = p.next;
}
Msg.next = Prev.next;
Prev.next = msg;
This.notify ();
}
}
return true;
}
The main task of this method is to add the message object to the MessageQueue (the most basic thing of the data structure, the drawing comprehension).
Handler.sendmessage ()-->handler.sendmessagedelayed ()-->handler.sendmessageattime ()-->msg.target = this; Queue.enqueuemessage==> adding MSG to the message queue
3.handleMessage (msg)
Onstartcommand () After the execution of the method in our service is finished, then Handlemessage () is how to invoke it? In the loop () method that we analyzed earlier, we didn't know what the Target field code of MSG was, By analyzing the above, we now know that it represents the Servicehandler object, Msg.target.dispatchMessage (msg), which means the DispatchMessage () method in the Servicehandler object is executed:
public void DispatchMessage (Message msg) {
if (msg.callback! = null) {
Handlecallback (msg);
}
else {
if (mcallback! = null) {
if (Mcallback.handlemessage (msg)) {
Return
}
}
Handlemessage (msg);
}
}
The method first determines whether callback is empty, we do not see it assigned in the process of tracking, so the callback field is empty, so the Handlemessage () method will eventually be executed, that is, the method of replication in our Servicehandler class. The method will determine what code to execute based on the value of the What field.
So far, we see, a message through the handler send, MessageQueue the queue, Looper extraction, and again back to the arms of handler. And the circle around it just helps us turn the synchronous operation into an asynchronous operation.
Second, how is the message mechanism of Android implemented?
1, why to use the message mechanism is mainly to ensure that the security between the threads, and do not need to care about the specific message receiver, so that the message itself and the thread stripping open, so that it is convenient to implement timing, asynchronous and other operations.
2. Message mechanism principle:
Activity <---------------> ehandler<-----> looper<-----> MessageQueue
Intentreceiver <-----> Ehandler <-----> looper<-----> MessageQueue
Figure 1
3, how to achieve? (The process of describing the message flow)
Implementation of the message mechanism requires handler, message, Looper three interaction between the implementation; When thread A needs to send a message to thread B, thread B uses its own looper to instantiate the handler class, which is when the handler object is constructed. Passing the current thread's looper to the handler constructor, handler itself will save a reference to the Looper, and after the handler is constructed, the message object can be instantiated with handler Obtainmessage method. As long as the data to be transmitted to Handler,handler will construct the message object, and the message object is added to the queue. You can then call handler's SendMessage method to send the Message object, Looper put it in the message queue, and finally, when looper know that the message queue is not empty, it loops from the message queue to take the message, Removing the message invokes the Handlemessage method of the handler object that was just instantiated to handle the message, as is the case with the entire message process.
Android Messaging Mechanism (Handler, message, Looper)