current position:Home>Android handler source code analysis 2
Android handler source code analysis 2
2022-01-27 03:44:45 【Sniper 000】
This is my participation 8 The fourth of the yuegengwen challenge 17 God , Check out the activity details :8 Yuegengwen challenge
stay ActivityThread Of main Method , This method is the entrance to the application . main The source code of the method is as follows :
public static void main(String[] args) {
// Code ellipsis
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
Copy code
eureka Looper.prepareMainLooper(), This sum Looper.prepare() It's so similar , Follow in and have a look
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
Copy code
Back again , Still called prepare Methodical . So the main thread has created a Looper Object's . Handler The analysis of the creation process of is completed , Now I finally understand .
Let's sum up ,Handler The creation of depends on Looper Of . The main thread creates one by default Looper Object's . every last Looper Will be associated with a thread (ThreadLocal Encapsulated Looper). every last Looper A message queue will be encapsulated in the . thus ,handler,Looper,MessageQueue,Thread The four roles are related , You have me , I have you. . handler Create in main thread , Because it is associated with the message queue of the main thread , like that handler Of handleMessage Method will execute in the main thread , So this is updating UI It's thread safe .
Go on , There are still many unsolved problems I believe you want to know more about Handler How to send messages . Usually we create a Message object , And pull some data from the server , Mark , Assign parameters to Message Some fields of what,arg1,obj etc. ,handler call sendMessage Method to send , This data can be sent to the main thread , And then in handlerMessage Method to handle updates UI that will do .
Then we went from handler Of sendMessage Methods start looking for information
public final boolean sendMessage(Message msg) {
return sendMessageDelayed(msg, 0);
}
Copy code
sendMessage Would call sendMessageDelayed Methods and message Object passing in , The second parameter is the delay time , Use sendMessage Method defaults to 0 Of . Then came sendMessageDelayed Method
public final boolean sendMessageDelayed(Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
Copy code
To work around , Will eventually call sendMessageAtTime Method , And will message Object passed into .
Continue to follow up sendMessageAtTime Method ,
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;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
Copy code
It analyzes , Creating Looper When the object , Will create a MessageQueue, So as long as Looper If it is created normally , The message queue is not empty . So to the last line enqueueMessage Method , Source code is as follows :
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
Copy code
You can see that the last line calls MessageQueue Of enqueueMessage Method . Be careful : It's posted on it enqueueMessage yes Handler Methods , No MessageQueue Of , It's just a layer of packaging , The operation of the real queue message queue is, of course MessageQueue in . And from the first line msg.target = this We can know ,msg Of target Field , In fact, that is handler.
MessageQueue Of enqueueMessage The source code of the method is as follows :
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
Copy code
Messagequeue There is an object in mMessage Used to point to the current incoming msg, The latest news . And just now sendMessageAtTime(Message msg, long uptimeMillis) Method , The second parameter specifies the time , Then follow this here uptimeMillis To sort messages , And the result of my analysis msg.next Is to point to the next message , In this way, each message is related in chronological order , The message at the top points to the message at the bottom .
copyright notice
author[Sniper 000],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270344392748.html
The sidebar is recommended
- Spring IOC container loading process
- [thinking] the difference between singleton mode and static method - object-oriented programming
- Hadoop environment setup (MySQL environment configuration)
- 10 minutes, using node JS creates a real-time early warning system for bad weather!
- Git tool
- Force deduction algorithm - 92 Reverse linked list II
- What is the sub problem of dynamic programming?
- C / C + +: static keyword summary
- Idea does not have the artifacts option when configuring Tomcat
- Anaconda can't open it
guess what you like
-
I don't know how to start this
-
Matlab simulation of transportation optimization algorithm based on PSO
-
MySQL slow log optimization
-
[Vue] as the window is stretched (larger, smaller, wider and higher), the text will not be displayed
-
Popular Linux distributions for embedded computing
-
Suzhou computer research
-
After installing SSL Certificate in Windows + tomcat, the domain name request is not successful. Please answer!!
-
Implementation time output and greetings of jQuery instance
-
The 72 year old uncle became popular. Wu Jing and Guo fan made his story into a film, which made countless dreamers blush
-
How to save computer research
Random recommended
- Springboot implements excel import and export, which is easy to use, and poi can be thrown away
- The final examination subjects of a class are mathematical programming, and the scores are sorted and output from high to low
- Two pronged approach, Tsinghua Professor Pro code JDK and hotspot source code notes, one-time learning to understand
- C + + recursive knapsack problem
- The use of GIT and GitHub and the latest git tutorial are easy to understand -- Video notes of crazy God speaking
- PostgreSQL statement query
- Ignition database test
- Context didn't understand why he got a high salary?, Nginxfair principle
- Bootstrap switch switch control user's guide, springcloud actual combat video
- A list that contains only strings. What other search methods can be used except sequential search
- [matlab path planning] multi ant colony algorithm grid map path planning [including GUI source code 650]
- [matlab path planning] improved genetic algorithm grid map path planning [including source code phase 525]
- Iinternet network path management system
- Appium settings app is not running after 5000ms
- Reactnative foundation - 07 (background image, status bar, statusbar)
- Reactnative foundation - 04 (custom rpx)
- If you want an embedded database (H2, hsql or Derby), please put it on the classpath
- When using stm32g070 Hal library, if you want to write to flash, you must perform an erase. If you don't let it, you can't write continuously.
- Linux checks where the software is installed and what files are installed
- SQL statement fuzzy query and time interval filtering
- 69. Sqrt (x) (c + + problem solving version with vs runnable source program)
- Fresh students are about to graduate. Do you choose Java development or big data?
- Java project: OA management system (java + SSM + bootstrap + MySQL + JSP)
- Titanic passenger survival prediction
- Vectorization of deep learning formula
- Configuration and use of private image warehouse of microservice architect docker
- Relearn JavaScript events
- For someone, delete return 1 and return 0
- How does Java dynamically obtain what type of data is passed? It is used to judge whether the data is the same, dynamic data type
- How does the database cow optimize SQL?
- [data structure] chain structure of binary tree (pre order traversal) (middle order traversal) (post order traversal) (sequence traversal)
- Webpack packaging optimization solution
- 5. Operation element
- Detailed explanation of red and black trees
- redhat7. 9 install database 19C
- Blue Bridge Cup notes: (the given elements are not repeated) complete arrangement (arrangement cannot be repeated, arrangement can be repeated)
- Detailed explanation of springboot default package scanning mechanism and @ componentscan specified scanning path
- How to solve the run-time exception of test times
- Detailed explanation of k8s management tool kubectl
- Android system view memory command