zoukankan      html  css  js  c++  java
  • Android消息机制

      用消息队列可以完成主线程和子线程之间的消息传递,涉及到三个类:Looper,Message,Handler,这三者之间的关系如下:

      

      从上图可以看出,Looper可视为一个MessageQueue,是一个消息的集合,而每个消息都可以通过Handler增加和取出,Handler对象可能存在于主线程(UI Thread)和子线程中。

      Message类

       android.os.Message的主要功能是进行消息的封装,Message类定义的变量和方法如下:

      

      

      Handler类

       android.os.Handler类用于处理消息。

        A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a    single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it --          from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue. 

      

      每一个Handler实例都与创建该Handler所在的线程绑定,并绑定了该线程中的消息队列(即:Looper),之后该Handler实例便会向该消息队列(Looper)中发送和处理消息。

      Handler类有两个作用:

      一、在新启动的线程中发送消息

      二、在主线程中获取、处理消息

      

      消息队列 Looper

       每个线程只能拥有一个Looper。它的loop方法负责读取MessageQueue中的消息,读到信息之后就把消息交给发送该消息的Handler进行处理。  

      在UI线程(主线程)中,系统已经初始化了一个Looper对象,因此程序直接创建Handler即可,然后就可以通过Handler来发送消息、处理消息。

      如果需要在子线程中,创建Handler用于发送、处理消息,需要在子线程中创建自己的Looper对象,并启动它。创建Looper对象,方法为: Looper.prepare()

      如果在子线程中创建自己的Handler对象,在run()方法里面,步骤如下:

      1.Looper.prepare();

      2.创建Handler实例,并重写其handleMessage()方法;

      3.Looper.loop();

      总结:不同线程间通信,比如线程A要向线程B发送信息,是调用线程B中的Handler对象实例发送信息,然后在线程B中的handleMessage()方法里进行消息处理。

  • 相关阅读:
    Authentication with SignalR and OAuth Bearer Token
    [Web API] 如何让 Web API 统一回传格式以及例外处理[转]
    EF6 Database First (DbContext)
    DbContext运行时动态附加上一个dbset
    命令模式
    责任链模式
    策略模式
    Sql Server isnull() 用法
    状态者模式
    dom元素改变监听
  • 原文地址:https://www.cnblogs.com/xingkai/p/5106063.html
Copyright © 2011-2022 走看看