当前位置:网站首页>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 .
边栏推荐
- What are the main investment products of bond funds and what are they
- VRRP+BFD
- 1day vulnerability pushback skills practice (3)
- There is no need to authorize the automatic dream weaving collection plug-in for dream weaving collection
- Record a problem that soft deletion fails due to warehouse level error
- [development team follows] API specification
- Contest3145 - the 37th game of 2021 freshman individual training match_ D: Ranking
- How to use STR function of C language
- The requests module uses
- Osnabrueck University | overview of specific architectures in the field of reinforcement learning
猜你喜欢
I stepped on a foundation pit today
Ai aide à la recherche de plagiat dans le design artistique! L'équipe du professeur Liu Fang a été embauchée par ACM mm, une conférence multimédia de haut niveau.
長文綜述:大腦中的熵、自由能、對稱性和動力學
[software implementation series] software implementation interview questions with SQL joint query diagram
AI 助力藝術設計抄襲檢索新突破!劉芳教授團隊論文被多媒體頂級會議ACM MM錄用
Johnson–Lindenstrauss Lemma
Lichuang EDA learning notes 14: PCB board canvas settings
Résumé: entropie, énergie libre, symétrie et dynamique dans le cerveau
Network communication basic kit -- IPv4 socket structure
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?
随机推荐
FRP intranet penetration
12. Gettimeofday() and time()
I stepped on a foundation pit today
Www 2022 | taxoenrich: self supervised taxonomy complemented by Structural Semantics
Mysql-15 aggregate function
ZABBIX API pulls the values of all hosts of a monitoring item and saves them in Excel
Question d: Haffman coding
MySQL workbench use
Fudan released its first review paper on the construction and application of multimodal knowledge atlas, comprehensively describing the existing mmkg technology system and progress
查詢效率提昇10倍!3種優化方案,幫你解决MySQL深分頁問題
[untitled] the relationship between the metauniverse and digital collections
Love and self-discipline and strive to live a core life
What are the conditions for the opening of Tiktok live broadcast preview?
false sharing
Save Private Ryan - map building + voltage dp+deque+ shortest circuit
Advanced learning of MySQL -- Application -- storage engine
STM32 key content
在尋求人類智能AI的過程中,Meta將賭注押向了自監督學習
Dare to climb here, you're not far from prison, reptile reverse actual combat case
Mysql to PostgreSQL real-time data synchronization practice sharing