Handler Looper HandlerThread

Handler提供了一种消息机制用于线程间的通信。
默认情况下,Handler是运行在和创建它的线程同一个线程里的。Looper的机制可以改变这一点,通过在构造函数出传递一个looper,可以指定handler在和looper相同线程中执行。

1.可以在线程中调用 Looper.prepare(); Looper.myLooper() 得到一个当前线程的 looper。

2.Looper.getMainLooper(); 可以得到主线程的looper

3.handler.post(new Runnable(){..}) runnable里的代码和handler是在同一个线程中执行的,当然handler的 handleMessage() 方法也是在handler的同一线程

HandlerThread 可用于方便的创建一个新线程,然后获得一个looper,以便指定后续的handler在新的线程里执行。 而不用自己再去写一个线程类,然后创建looper等操作。
示例:
// Start up the thread running the service.  Note that we create a
        // separate thread because the service normally runs in the process's
        // main thread, which we don't want to block.  We also make it
        // background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments",                Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();       
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);


handler常用于新线程中发送一个消息,然后再handleMessage中更新主线程的UI界面(此时handler必须是运行在主线程中的)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值