Android thread lorule. prepare (), lorule. loop () Use
During the optimization project, a very Low problem was found. Sort it out and forget: Let's take a look at the definition of HandlerThread, which encapsulates the logoff thread:
Logoff is used to encapsulate the message loop in the android thread. By default, the next thread does not have a message loop. You need to call logoff. prepare () to create a message loop for the thread and call logoff. loop () to make the message loop take effect, get the message from the message queue, and process the message. Note: written in logoff. the code after loop () will not be executed immediately. After the call, mHandler. getLooper (). after quit (), the loop will be aborted, and the subsequent code can be run. The logoff object stores messages and events through MessageQueue. A thread can have only one logoff corresponding to one MessageQueue.
The following is a typical loginthread implementation in Android APIs:
// Handler's default constructor without parameters: new Handler (), which actually obtains the message loop in the current thread through logoff. mylogoff,
// By default, the thread does not have a message loop, so you need to call logoff. prepare () to create a message loop for the thread, and then pass, logoff. loop () to make the message loop take effect.
[Java]
- Class LooperThread extends Thread
- {
- Public Handler mHandler;
- Public void run ()
- {
- Logoff. prepare ();
- MHandler = new Handler ()
- {
- Public void handleMessage (Message msg)
- {
- // Process incoming messages here
- }
- };
- Logoff. loop ();
- }
In addition, the MainUI thread of the Activity has a message queue by default. Therefore, when creating a Handler in an Activity, you do not need to call logoff. prepare () first ().
So there are many Low problems:
In the project, a HandlerThread is rewritten, THE post method is defined, and the following implementation is performed in the main thread:
AsyncHandler. post (new Runnable (){
@ Override
Public void run (){
Try {
Logoff. prepare ();
// Code to be executed asynchronously ******
Logoff. loop ();
} Catch (Exception e ){
// TODO: handle exception
E. printStackTrace ();
}
As soon as you can see the problem, this Code cannot be run asynchronously. Why? Let's take a look at the implementation of prepare:
/** Initialize the current thread as a logoff.
* This gives you a chance to create handlers that then reference
* This logoff, before actually starting the loop. Be sure to call
* {@ Link # loop ()} after calling this method, and end it by calling
* {@ Link # quit ()}.
*/
Public static void prepare (){
Prepare (true );
}
Private static void prepare (boolean quitAllowed ){
If (sThreadLocal. get ()! = Null ){
Throw new RuntimeException (Only one logoff may be created per thread );
}
SThreadLocal. set (new LOD (quitAllowed ));
}
So, simple, but a problem ~