handler和looper的关系

本文详细介绍了Android应用启动时主线程(UI线程)的工作原理,包括消息队列、Looper对象的作用及其实现机制,以及Handler如何与Looper绑定来实现消息传递和处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Android应用启动时,会默认有一个主线程(UI线程),在这个线程中会关联一个消息队列,所有的操作都会被封装成消息然后交给主线程来处理。
为了保证主线程不会主动退出,会将取消息的操作放在一个死循环中,这样程序就相当于一直在执行死循环,因此不会退出。
在应用启动时,会开启一个主线程(UI线程),并且启动消息循环,应用不停地从该消息队列中取出、处理消息达到程序运行的效果。
Looper对象封装了消息队列,Looper对象是ThreadLocal的,不同线程之间的Looper对象不能共享与访问。
而Handler通过与Looper对象绑定来实现与执行线程的绑定,handler会把Runnable(包装成Message)或者Message对象追加到与线程关联的消息队列中,然后在消息循环中挨个取出消息,并且处理消息。当Handler绑定的Looper是主线程的Looper,则该Handler可以在handleMessage中更新UI,否则更新UI则会抛出异常!

public static void main(String[] args) {  
     SamplingProfilerIntegration.start();  
     CloseGuard.setEnabled(false);  
     Environment.initForCurrentUser();  

     // Set the reporter for event logging in libcore  
     EventLogger.setReporter(new EventLoggingReporter());  

     Process.setArgV0("<pre-initialized>");  

     Looper.prepareMainLooper();// 1、创建消息循环Looper  

     ActivityThread thread = new ActivityThread();  
     thread.attach(false);  

     if (sMainThreadHandler == null) {  
         sMainThreadHandler = thread.getHandler(); // UI线程的Handler  
     }  

     AsyncTask.init();  
     if (false) {  
         Looper.myLooper().setMessageLogging(new  
                 LogPrinter(Log.DEBUG, "ActivityThread"));  
     }  

     Looper.loop();   // 2、执行消息循环  
     throw new RuntimeException("Main thread loop unexpectedly exited");  
 } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值