当前位置:网站首页>Handler source code analysis
Handler source code analysis
2022-07-04 02:56:00 【yinianzhijian99】
Handler Yes 7 A construction method , Commonly used :
public Handler() {
this(null, false);
}
public Handler(Looper looper) {
this(looper, null, false);
}
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
// obtain Looper example
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
When created in a child thread , You need to call Looper.prepare() initialization Looper object , Then you must call Looper.loop() Method ;
When created in the main thread , From ThreadLocal In order to get mainLooper example .
Common methods of sending messages , There are other overloaded methods , I won't list it here :
public final boolean post(Runnable r){
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean sendMessage(Message msg){
return sendMessageDelayed(msg, 0);
}
These methods will call sendMessageDelayed(msg,delayMillis)
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
// Store the message in the message queue
return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
summary :handler.sendMessage(msg) In fact, it's just our Message Added message queue , Queue adopted
It's a linked list , according to when That is, time sequencing . No more logic .
How to process messages , stay looper Example of loop() Method :
public void dispatchMessage(Message msg) {
// if msg.callback Not empty , It means that post(Runnable r) Send a message
// Execute at this time handleCallback(msg), Call back Runnable Copied from the object run()
if (msg.callback != null) {
handleCallback(msg);
} else {
//handler The callback of the instance is not empty
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
// So let's go over here , explain handler The callback of the instance is empty ,
// Execute at this time handleMessage(msg) Method ,
// establish Handler Instance replication method
handleMessage(msg);
}
}
Handler Analysis of finished , Then look at Looper class , Its construction method :
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Looper The message queue is initialized in the construction method of , Also get the current thread , You can see it here ,Looper Is bound to a thread , And there is only one future looper example .
Get the child thread's looper example :
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
Get the main thread's looper example :
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
Looper The most important thing in the class is the message loop method :
public static void loop() {
// obtain looper example
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
// obtain Looper The message queue object in the instance (MessageQueue)
final MessageQueue queue = me.mQueue;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); // might block
// If the retrieved message is empty , The thread is blocked
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
// Send a message to the corresponding Handler, then handler Will process messages
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
// Release the resources occupied by messages
msg.recycleUnchecked();
}
}
loop() Method keeps getting messages in a loop , Send the message to handler Handle .
MessageQueue Class has two main methods , No detailed analysis here :
enqueueMessage(queue, msg, uptimeMillis): Insert a message into the message queue
next(): Get messages from the message queue
thus ,Handler Relevant source code analysis is completed .
边栏推荐
- Data collection and summary
- Problems and solutions of several concurrent scenarios of redis
- Short math guide for latex by Michael downs
- Command Execution Vulnerability - command execution - vulnerability sites - code injection - vulnerability exploitation - joint execution - bypass (spaces, keyword filtering, variable bypass) - two ex
- Unity controls the selection of the previous and next characters
- Zhihu million hot discussion: why can we only rely on job hopping for salary increase? Bosses would rather hire outsiders with a high salary than get a raise?
- 14. Process time
- The 37 year old programmer was laid off, and he didn't find a job for 120 days. He had no choice but to go to a small company. As a result, he was confused
- Experience summary of the 12th Blue Bridge Cup (written for the first time)
- Summarize the past to motivate yourself to move on
猜你喜欢
C # learning notes: structure of CS documents
VRRP+BFD
Practical multifunctional toolbox wechat applet source code / support traffic master
Advanced learning of MySQL -- Application -- storage engine
17. File i/o buffer
The "message withdrawal" of a push message push, one click traceless message withdrawal makes the operation no longer difficult
Backpropagation formula derivation [Li Hongyi deep learning version]
WP collection plug-in free WordPress collection hang up plug-in
Measurement fitting based on Halcon learning [4] measure_ arc. Hdev routine
What is cloud primordial?
随机推荐
SQL injection (1) -- determine whether there are SQL injection vulnerabilities
What are the conditions for the opening of Tiktok live broadcast preview?
Basé sur... Netcore Development blog Project Starblog - (14) Implementation of theme switching function
PTA tiantisai l1-079 tiantisai's kindness (20 points) detailed explanation
Command Execution Vulnerability - command execution - vulnerability sites - code injection - vulnerability exploitation - joint execution - bypass (spaces, keyword filtering, variable bypass) - two ex
[software implementation series] software implementation interview questions with SQL joint query diagram
Zhihu million hot discussion: why can we only rely on job hopping for salary increase? Bosses would rather hire outsiders with a high salary than get a raise?
12. Gettimeofday() and time()
MySQL workbench use
Design and implementation of redis 7.0 multi part AOF
150 ppt! The most complete "fair perception machine learning and data mining" tutorial, Dr. AIST Toshihiro kamishima, Japan
Global and Chinese market of contour projectors 2022-2028: Research Report on technology, participants, trends, market size and share
What are the main investment products of bond funds and what are they
60 year old people buy medical insurance and recommend a better product
Network communication basic kit -- IPv4 socket structure
CSCI 2134
(column 23) typical C language problem: find the minimum common multiple and maximum common divisor of two numbers. (two solutions)
Create real-time video chat in unity3d
Setting methods, usage methods and common usage scenarios of environment variables in postman
There is no need to authorize the automatic dream weaving collection plug-in for dream weaving collection