Android HandlerThread 的使用及其Demo

今天我们一起来学习下一个Android中比较简单的类HandlerThread,虽然它的初始化有点小麻烦。

介绍

首先我们来看看为什么我们要使用HandlerThread?在我们的应用程序当中为了实现同时完成多个任务,所以我们会在应用程序当中创建多个线程。为了让多个线程之间能够方便的通信,我们会使用Handler实现线程间的通信。

下面我们看看如何在线程当中实例化Handler。在线程中实例化Handler我们需要保证线程当中包含Looper(注意UI-Thread默认包含Looper)。

为线程创建Looper的方法如下:在线程run()方法当中先调用Looper.prepare()初始化Looper,然后再run()方法最后调用Looper.loop(),这样我们就在该线程当中创建好Looper。(注意Looper.loop()方法默认是死循环)

我们实现Looper有没有更加简单的方法呢?当然有,这就是我们的HandlerThread。我们来看下AndroidHandlerThread的描述:

Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start() must still be called.


使用步骤

尽管HandlerThread的文档比较简单,但是它的使用并没有想象的那么easy。

  1. 创建一个HandlerThread,即创建了一个包含Looper的线程。

    HandlerThread handlerThread = new HandlerThread("leochin.com");

    handlerThread.start(); //创建HandlerThread后一定要记得start()

  2. 获取HandlerThread的Looper

    Looper looper = handlerThread.getLooper();

  3. 创建Handler,通过Looper初始化

    Handler handler = new Handler(looper);

通过以上三步我们就成功创建HandlerThread。通过handler发送消息,就会在子线程中执行。

如果想让HandlerThread退出,则需要调用handlerThread.quit();


测试代码

HandlerThreadDemo


引用:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值