• Android HandlerThread 的使用及其Demo (转)


    转自http://www.cnblogs.com/hnrainll/p/3597246.html

    介绍

    首先我们来看看为什么我们要使用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


    引用:

  • 相关阅读:
    python学习笔记之--read、readline和readlines
    目录操作习题
    递归习题
    文件操作练习题
    HandleBase句柄的5种写法
    ContextBase
    BasegoSort
    PrototypePra原型_设计订单保存
    DesignPattenTemplate模板模式
    DesignPattenStrategy策略模式
  • 原文地址:https://www.cnblogs.com/seacode/p/3937419.html
Copyright © 2020-2023  润新知