为什么Handler在主线程中不需要使用Looper.prepare()和loop()方法?看源码!

看了网上很多文章,发现没人真正解释为什么在主线程中不需要使用Looper.prepare()和Looper.loop()方法。下面我贴一下安卓源码,相信大家就一目了然了,源码的位置是在ActivityThread类中的main函数。大家可以用Source Insight查看。

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();//这实际就是一个实例化一个looper对象,大家也可以看看prepareMainlooper方法(下方)。
        ActivityThread thread = new ActivityThread();
        thread.attach(false);
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        } 
	Looper.loop();//启动循环器 
}
  public static void prepareMainLooper() {
        prepare(false); //实例化Looper,上篇博文分析过这个方法了,不再赘述
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();//获得Looper对象
        }
    }



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在非 UI 线程使用 Looper.prepare() 和 Looper.loop() 方法可以创建一个消息循环,使得该线程能够接收并处理消息。接着,可以在该线程创建 Handler,并重写 handleMessage() 方法来处理消息。 下面是一个示例代码: ``` class MyThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) { // 处理消息 } }; Looper.loop(); } } ``` 在该示例代码,创建了一个名为 MyThread 的线程。在 run() 方法,首先调用 Looper.prepare() 方法来创建一个消息循环。然后创建一个 Handler,并重写其 handleMessage() 方法来处理消息。最后调用 Looper.loop() 方法来启动消息循环。 接着,在其他线程可以通过 MyThread 实例的 mHandler 属性来向该线程发送消息。例如: ``` MyThread thread = new MyThread(); thread.start(); Message msg = thread.mHandler.obtainMessage(); msg.what = 1; msg.obj = "Hello"; thread.mHandler.sendMessage(msg); ``` 在该示例代码,首先创建了一个 MyThread 的实例,并启动该线程。然后创建一个消息,并设置其 what 和 obj 属性。最后通过 thread.mHandler.sendMessage() 方法来将该消息发送给 MyThread 线程Handler 进行处理。 需要注意的是,如果在非 UI 线程使用 Handler,必须在该线程的 run() 方法调用 Looper.prepare() 和 Looper.loop() 方法来创建消息循环,否则将会抛出异常。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值