Android Message Processing-logoff and Handler class

Source: Internet
Author: User

Windows programmers may know that Windows programs are message-driven and have a global message loop system. Android applications are message-driven, and the message loop mechanism should also be provided. Android uses logoff and Handler to implement the message loop mechanism. Android message loops are targeted at threads (each thread can have its own message queue and message loop ).

In the Android system, this work is done by logoff and Handler.

Analyze the logoff class first:
It mainly provides message loops and message queues in charge of threads.

Class LooperThread extends Thread {
Public Handler mHandler;

Public void run (){
Logoff. prepare (); // prepare...

MHandler = new Handler (){
Public void handleMessage (Message msg) {// Message Processing
// Process incoming messages here
}
};

Logoff. loop (); // enters the message loop
}
}

The following logoff preparation functions:
Private static final ThreadLocal sThreadLocal = new ThreadLocal ();

Public static final void prepare (){
If (sThreadLocal. get ()! = Null ){
Throw new RuntimeException ("Only one logoff may be created per thread ");
}
SThreadLocal. set (new logoff ());
}


Here, the local storage variable of the ThreadLocal thread is used to associate the logoff with the call thread.
What is the message processing process?
/**
* Run the message queue in this thread. Be sure to call
* {@ Link # quit ()} to end the loop.
*/
Public static final void loop (){
Looper me = mylome (); // The Looper object stored in the thread
MessageQueue queue = me. mQueue; // message queue in the logoff class
While (true ){
Message msg = queue. next (); // might block to get the Message
// If (! Me. mRun ){
// Break;
//}
If (msg! = Null ){
If (msg.tar get = null ){
// No target is a magic identifier for the quit message.
Return;
}
If (me. mLogging! = Null) me. mLogging. println (
">>>>> Dispatching to" + msg.tar get + ""
+ Msg. callback + ":" + msg. what
);
Msg.tar get. dispatchMessage (msg); // use the Target registration method to process the message
If (me. mLogging! = Null) me. mLogging. println (
"<Finished to" + msg.tar get + ""
+ Msg. callback );
Msg. recycle ();
}
}
}

You can use Loop. myLooper () to obtain the Looper object of the current thread, and use Loop. getMainLooper () to obtain the Looper object of the main thread of the current process.


In android, the UI thread is the main thread of the message, which is created in ActivityThread. java:
Public static final void main (String [] args ){
Lorule. preparemainlorule ();

Logoff. loop (); // message loop Processing
}


-->
Public static final void preparemainlogoff (){
Prepare ();
SetMainLooper (myLooper ());
If (Process. supportsProcesses ()){
MyLooper (). mQueue. mQuitAllowed = false;
}
}


Private synchronized static void setMainLooper (Looper looper ){
Mmainlogoff = logoff;
}

Then analyze the Handler class:
It is mainly used to add messages to a specific logoff message queue and distribute and process the messages in the access message queue. When constructing a Handler, you can specify a logoff object, if this parameter is not specified, it is created using the Logoff of the current thread. Www.2cto.com


See the following code to understand:
Public Handler (Looper looper, Callback callback ){
Mlogoff = logoff;
MQueue = logoff. mQueue;
MCallback = callback;
}

Here, we also tell you to put messages into the message queue of the main thread. You only need to create a Hanlde object with the Logoff of the main thread. Both sendMessage and handleMessage are processed in the main thread.

Let's look at the following variables:
Final MessageQueue mQueue;
Final low.mlow;
Final Callback mCallback;

Here there are also queues, logoff objects and callback function classes, which use different Handler constructors to complete corresponding operations.
Simplify the complexity of using queues and message transmission, and provide convenient calling methods. The most important functions are:

/**
* Handle system messages here.
*/
Public void dispatchMessage (Message msg ){
If (msg. callback! = Null ){
HandleCallback (msg); // 1. Use the Calback function to process messages.
} Else {
If (mCallback! = Null ){
If (mCallback. handleMessage (msg) {// 2. Use mCallback to process messages
Return;
}
}
HandleMessage (msg); // 3. Use sub-classes to process messages. The most common method here is to directly overload the handleMessage function.
}
}

So what is the relationship between these persons?



 

Multiple worker threads or other components can be created in an Activity. If these threads or components put their messages into the active thread message queue of the Activity, the message will be processed in the main thread.


Another problem is how to deal with the synchronization relationship between logoff and Handler, Which is solved by the HandlerThread class on android.

Public Looper getLooper (){
If (! IsAlive ()){
Return null;
}

// If the thread has been started, wait until the looper has been created.
Synchronized (this ){
While (isAlive () & mlogoff = null ){
Try {
Wait (); // If the logoff object has not been created by the new thread, wait
} Catch (InterruptedException e ){
}
}
}
Return mLooper;
}

The new thread creates a logoff object by running the run function:
Public void run (){
MTid = Process. myTid ();
Logoff. prepare (); // The logoff object of the process will be created here.
Synchronized (this ){
Mlogoff = logoff. mylogoff ();
NotifyAll (); // OK. After creation, the notification is triggered. Finally, lorule. loop () is called to enter the message loop.
}
Process. setThreadPriority (mPriority );
OnLooperPrepared ();
Logoff. loop ();
MTid =-1;
}


Here, we use the policyall/wait lightweight check to solve this problem. Therefore, we need to use the HanlderThread class to complete multi-thread synchronization.

From andyhuabing's column

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.