Android calls Looper.prepareMainLooper in the entry function ActivityThread.main() of the process to create a Looper for the main thread of the application, and then calls Looper.loop() to start the message loop of the process, and then the message can be processed.
ActivityThread source code:
151 public final class ActivityThread {
2202 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
2253 if (activity != null) {
2259 activity.attach(appContext, this, ..., );
5219 public static void main(String[] args) {
// 在这儿调用 Looper.prepareMainLooper, 为应用的主线程创建Looper
5240 Looper.prepareMainLooper();
5242 ActivityThread thread = new ActivityThread();
5245 if (sMainThreadHandler == null) {
5246 sMainThreadHandler = thread.getHandler();
5247 }
5254 Looper.loop();
5257 }
5258}
Looper source code:
52 public final class Looper {
// Initialize the current thread as a looper, marking it as an application's main looper.
// The main looper for your application is created by the Android environment,
// so you should never need to call this function yourself. See also: prepare()
87 public static void prepareMainLooper() {
88 prepare(false);
89 synchronized (Looper.class) {
90 if (sMainLooper != null) {
91 throw new IllegalStateException("The main Looper has already been prepared.");
92 }
93 sMainLooper = myLooper();
94 }
95 }
Activity source code:
660 public class Activity extends ContextThemeWrapper {
699 /*package*/ ActivityThread mMainThread;
5922 final void attach(Context context, ActivityThread aThread, ..., ) {
5944 mMainThread = aThread;
Reference:
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/app/ActivityThread.java http://grepcode .com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/app/Activity.java Source code analysis of Android application process startup process - by Luo Shengyang Android_Message_Handler_Message processing mechanism summary notes
Android calls
Looper.prepareMainLooper
in the entry function ActivityThread.main() of the process to create a Looper for the main thread of the application, and then callsLooper.loop()
to start the message loop of the process, and then the message can be processed.ActivityThread source code:
Looper source code:
Activity source code:
Reference:
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/app/ActivityThread.java
http://grepcode .com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/app/Activity.java
Source code analysis of Android application process startup process - by Luo Shengyang
Android_Message_Handler_Message processing mechanism summary notes
@li21 said it very well,
by the way, let me tell you how to automatically increase
Looper
you can use
HandlerThread