当前位置:网站首页>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 .
边栏推荐
- 15. System limitations and options
- Contest3145 - the 37th game of 2021 freshman individual training match_ J: Eat radish
- Contest3145 - the 37th game of 2021 freshman individual training match_ G: Score
- Global and Chinese market of digital impression system 2022-2028: Research Report on technology, participants, trends, market size and share
- Love and self-discipline and strive to live a core life
- 2022 examination summary of quality controller - Equipment direction - general basis (quality controller) and examination questions and analysis of quality controller - Equipment direction - general b
- Design and implementation of redis 7.0 multi part AOF
- Fudan released its first review paper on the construction and application of multimodal knowledge atlas, comprehensively describing the existing mmkg technology system and progress
- Format character%* s
- Yyds dry goods inventory hand-in-hand teach you the development of Tiktok series video batch Downloader
猜你喜欢

How to use websocket to realize simple chat function in C #

Have you entered the workplace since the first 00???

ZABBIX API pulls the values of all hosts of a monitoring item and saves them in Excel

false sharing

C # learning notes: structure of CS documents

17. File i/o buffer

Li Chuang EDA learning notes IX: layers
![[Valentine's Day confession code] - Valentine's Day is approaching, and more than 10 romantic love effects are given to the one you love](/img/ab/066923f1aa1e8dd8dcc572cb60a25d.jpg)
[Valentine's Day confession code] - Valentine's Day is approaching, and more than 10 romantic love effects are given to the one you love
![[Yugong series] February 2022 attack and defense world advanced question misc-84 (MySQL)](/img/4d/4a6b76896bf81a27d036a047f68b2b.jpg)
[Yugong series] February 2022 attack and defense world advanced question misc-84 (MySQL)

Gee import SHP data - crop image
随机推荐
2022 examination summary of quality controller - Equipment direction - general basis (quality controller) and examination questions and analysis of quality controller - Equipment direction - general b
[software implementation series] software implementation interview questions with SQL joint query diagram
(column 23) typical C language problem: find the minimum common multiple and maximum common divisor of two numbers. (two solutions)
The "message withdrawal" of a push message push, one click traceless message withdrawal makes the operation no longer difficult
Problems and solutions of several concurrent scenarios of redis
Tsinghua University product: penalty gradient norm improves generalization of deep learning model
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?
15. System limitations and options
What is cloud primordial?
AI 助力藝術設計抄襲檢索新突破!劉芳教授團隊論文被多媒體頂級會議ACM MM錄用
Love and self-discipline and strive to live a core life
Backpropagation formula derivation [Li Hongyi deep learning version]
Unity writes a character controller. The mouse controls the screen to shake and the mouse controls the shooting
150 ppt! The most complete "fair perception machine learning and data mining" tutorial, Dr. AIST Toshihiro kamishima, Japan
Mysql-15 aggregate function
Yyds dry goods inventory hand-in-hand teach you the development of Tiktok series video batch Downloader
The difference between int (1) and int (10)
Safety tips - seat belt suddenly fails to pull? High speed police remind you how to use safety belts in a standardized way
PTA tiantisai l1-079 tiantisai's kindness (20 points) detailed explanation
A brief talk on professional modeler: the prospect and professional development of 3D game modeling industry in China