每个Handler 的线程都有一个 Looper ,主线程当然也不例外,但是我们不曾准备过主线程的 Looper 而可以直接使用,这是为何?
注意:通常我们认为 ActivityThread 就是主线程。事实上它并不是一个线程,而是主线程操作的管理者,所以吧,我觉得把 ActivityThread 认为就是主线程无可厚非,另外主线程也可以说成 UI 线程。
在 ActivityThread.main() 方法中有如下代码:
1//android.app.ActivityThread 2public static void main(String[] args) { 3 //... 4 Looper.prepareMainLooper(); 5 6 ActivityThread thread = new ActivityThread(); 7 thread.attach(false); 8 9 if (sMainThreadHandler == null) {10 sMainThreadHandler = thread.getHandler();11 }12 //...13 Looper.loop();1415 throw new RuntimeException("Main thread loop unexpectedly exited");16}//android.app.ActivityThread
2public static void main(String[] args) {
3 //...
4 Looper.prepareMainLooper();
5
6 ActivityThread thread = new ActivityThread();
7 thread.attach(false);
8
9 if (sMainThreadHandler == null) {
10 sMainThreadHandler = thread.getHandler();
11 }
12 //...
13 Looper.loop();
14
15 throw new RuntimeException("Main thread loop unexpectedly exited");
16}
Looper.prepareMainLooper(); 代码如下:
1/** 2 * Initialize the current thread as a looper, marking it as an 3 * application's main looper. The main looper for your application 4 * is created by the Android environment, so you should never need 5 * to call this function yourself. See also: {@link #prepare()} 6 */ 7public static void prepareMainLooper() { 8 prepare(false); 9 synchronized (Looper.class) {10 if (sMainLooper != null) {11 throw new IllegalStateException("The main Looper has already been prepared.");12 }13 sMainLooper = myLooper();14 }15}/**
2 * Initialize the current thread as a looper, marking it as an
3 * application's main looper. The main looper for your application
4 * is created by the Android environment, so you should never need
5 * to call this function yourself. See also: {@link #prepare()}
6 */
7public static void prepareMainLooper() {
8 prepare(false);
9 synchronized (Looper.class) {
10 if (sMainLooper != null) {
11 throw new IllegalStateException("The main Looper has already been prepared.");
12 }
13 sMainLooper = myLooper();
14 }
15}
可以看到在 ActivityThread 里 调用了 Looper.prepareMainLooper() 方法创建了 主线程的 Looper ,并且调用了 loop() 方法,所以我们就可以直接使用 Handler 了。
注意:Looper.loop()
是个死循环,后面的代码正常情况不会执行。
-文完-
后续可能还会更新类似的小型知识点,相对于长篇的文章来讲我不需要花费大量的时间写作,对于读者来讲也没有阅读压力,希望对你有所帮助。
另外以后也不轻易开赞赏了,给部分同学省点钱,不要每次都赏,浪费钱,如果喜欢我的公众号,多帮忙分享,点点好看就行啦,感谢支持。
觉得有用,就给我一个“好看”