:(Handler, Looper, Message, MessageQueue)Message: Messages that contain the message ID, the message Processing object, and the processed data are queued by MessageQueue and processed by handler.Handler: Handler, responsible for sending and processing the message. When using handler, you need to implement the Handlemessage (Message msg) method to process a specific message, such as updating the UI. The main functions of the handler class are: (There ar
In accordance with the principles of Android handler detailed analysis we can know that when creating handle objects in the main thread, the main thread creates a loop object by default using the Threalocal function to bind the loop object and the main thread.Can we create a loop object and child thread bindings in a child thread that's actually possible?In this way we create a Looper object in the child thread, bind the
provide a separate copy of the variable, So each thread can change its own copy independently, without affecting the counterpart of other threads. In fact, this is in the space of time (contrary to synchronized), at the expense of memory, the single greatly reduce the thread synchronization (such as synchronized) the performance of the cost and reduce the complexity of the thread concurrency control. The typical example is the use of threadlocal in the Android code for
) the performance of the cost and reduce the complexity of the thread concurrency control. The typical example is the use of threadlocal in the Android code for Looper and the basic usage of threadlocal, as follows:
public class Looper {
private static final String TAG = "Looper";
Sthreadlocal.get () would return null unless for you ' ve called prepare ().
[Java]View Plaincopyprint?
Public void showtoast (String msg) {
Looper.prepare ();
Toast.maketext (Getapplicationcontext (), MSG, Toast.length_short). Show ();
Looper.loop ();
}
public void Showtoast (String msg) {looper.prepare (); Toast.maketext (Getapplicationcontext (), MSG, Toast.length_short). Show (); Looper.loop ();}Just add those two sentences to show toast in a non-UI thread[Java]View Plaincopyprint?
The show () inside the toast
publ
One of the reasons I love Android APIs are because it contains so many useful little things. Many of them is not even specific to the platform and I really miss them in Java SE. Today I ' d like to give a short introduction to II nice classes– Looper and Handler. They is used in the Android UI internally, and available to US developers so we can do some cool things with their help.So what can I do with Loopers and Handlers? Basically, they implement a
also be done.2.Handler cross-thread communication 2.1 principle descriptionIn order for other threads to send messages to notify the current thread to perform some tasks, the current thread thread can do this:
The current thread provides a unique MessageQueue that is used to receive a message that other threads have dropped in. MessageQueue maintains all messages using FIFO time sequence.
The current thread provides a unique looper to ma
); }//handler The default constructor will eventually be transferred to this method Public Handler(Callback Callback, BooleanAsync) {if(Find_potential_leaks) {final classif((Klass.isanonymousclass () | | klass.ismemberclass () | | klass.islocalclass ()) (klass.getmodif Iers () modifier.static) = =0) {//It turns out there has been a test printLOG.W (TAG,"The following Handler class should be static or leaks might occur:"+ Klass.getcanonicalname ()); } }there is a mlooper in//handlerM
processing is performed after the service die, please move to the next step to check and analyze private Boolean mredelivery; // In fact, this stuff runs in handlerthread. Why? This is nonsense. We use the logoff private final class servicehandler extends handler of handlerthread {// This part must be passed into the Logoff of handlerthread, right? Right? It must be public servicehandler (Looper loler) {super (Lo
Instantiation of the handlerIn Android development, handler is often used to commit a task to a specified thread (such as the main thread) to execute or to delay execution. The handler constructor has several overloaded forms, but eventually it is called to one of the following two types: PublicHandler (Callback Callback,Booleanasync) {Mlooper=Looper.mylooper (); if(Mlooper = =NULL) { Throw NewRuntimeException ("Can ' t create handler inside thread that have not called looper.prepare ()")
IntroducedFirst, let's see why we're using it HandlerThread . In our application, we create multiple threads in our application in order to accomplish multiple tasks simultaneously. In order to facilitate communication between multiple threads, we use Handler the implementation of inter-thread communication. Below we look at how to instantiate handler . Instantiated in thread handler We need to make sure that the thread contains Looper ( Note : ui-t
the main thread and then use this handler to communicate with the main thread in the new threads. Because the message queue for the main thread is already built, you can create the handler directly, and the new thread will be used directly.
In some cases, it is necessary to communicate between multithreading, which is to create MessageQueue and handler for each thread, as long as the thread can access the handler of other threads to communicate with it.
To create the handler correctly, because
Objective
It is believed that every Android developer knows that the update UI can only be done in the main thread, and that if you need to update the UI after the child thread executes the task, you need to use handler to jump to the main thread. Here are several ways to manipulate the UI.
First, the use of Handler handlemessage ()
Construction of Handler
Public Handler () {This
(null, FALSE);
}
Public Handler (Callback Callback, Boolean async) {
if (find_potential_leaks) {
fin
Looper is used to encapsulate a message loop in an Android thread, by default a thread is not present in the message loop, and it needs to call Looper.prepare () to create a message loop for the thread, calling Looper.loop () Make the message loop work, take the message from the message queue, and process the message.Note: code written after Looper.loop () will not be executed immediately, and after the call to Mhandler.getlooper (). Quit (), loop wil
Logoff is a very important concept in Android. It is the main communication mode between Android Application threads, and it is also the main method for internal thread serialization, the core of logoff is actually a message queue. It completes inter-thread communication and intra-thread serialization operations by constantly processing messages in the logoff message queue. If any thread wants to use a message mechanism-specific operation, it must create a l
.
Now I can explain the questions in the previous instance program: because the program creates a handler instance through this constructor, The logoff obtained by handler is actually the main thread, the message queue is also the main thread, so handler only delivers the message to the Message Queue of the main thread. The main thread is actually processing the time-consuming message, so an ANR error is reported.
2. Handler (low.lofter) constructor
public Handler(
Handler for processing.
1 // create and associate MessageQueue2 private Looper (boolean quitAllowed) {3 mQueue = new MessageQueue (quitAllowed); 4 mThread = Thread. currentThread (); 5}
1 // one thread can have at most one logoff. Call the prepare () method to create the logoff object 2 public static void prepare () {3 prepare (true ); 4} 5 6 private static void prepare (boolean quitAllowed) {7 if (sThreadLocal. get ()! = Null) {8 throw new RuntimeEx
initializes a Looper object when creating the UI thread, and also creates a MessageQueue associated with it;
Handler: The function is to send and process information, if you want Handler to work properly, there is a Looper object in the current thread
Message: Handler received and processed messages object
MessageQueue: Message Queuing, FIFO management message, which creates a MessageQueue a
Android source code analysis-detailed explanation of Handler and logoff mechanisms
In the Android system, similar to Java applications, the applications are message-driven. Simply put, there is a message queue, we can continuously add messages to this message queue, retrieve messages from them, and process messages. In Android, Handler, logoff, and Message are mainly involved in this work.Logoff class: a message loop is run for a thread. There is a message queue in it. Each thread can only have
Process Summary
Looper.prepare (): Saves an Looper instance in this thread, and then holds a MessageQueue object in the instance, because Looper.prepare () can only be called once in a thread, So MessageQueue will only exist in one thread.
Looper.loop (): Poll MessageQueue, Callback Msg.target.dispatchMessage (msg) method.
Handler constructor method: Gets the Looper instance that is saved i
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.