Android之Handler、MessageQueue、Message、Messager与Looper关系

Handler是android系统中一种重要的异步消息通信机制。  

线程与MessageQueue的关系?应用程序主线程自带有一个MessageQueue,而自己创建的线程没有MessageQueue。

Looper与MessageQueue的关系?Looper管理MessageQueue。

如何在新创建的线程中添加MessageQueue?在新创建的线程中,在run方法中调用Looper.prepare()方法初始化MessageQueue,最后调用Looper.loop()方法启用MessageQueue。

如何在两个线程中进行异步通信?这就需要在两个线程中分别准备消息队列,Hanlder实例,通过对方的Handler实例来发送Runnable或Message给对方进行处理。     

  android应用程序主线程即UI线程中组件的属性值的更新不能由子线程来更改,所以此时出现了Handler这个中介来解决这个问题,Handler在子线程中发送Message或Runnable到与UI线程相关联的MessageQueue队列中(有Looper维护消息队列),然后Handler在UI线程中从MessageQueue中取出Message或Runnable进行处理,来完成对UI属性值的更改或ui组件的添加。

    首先学习下Message ,Defines a message containing a description and arbitrary data object that can be sent to a Handler. This object contains two extra int fields and an extra object field that allow you to not do allocations in many cases.

   MessageQueue   Low-level class holding the list of messages to be dispatched by a Looper. Messages are not added directly to a MessageQueue, but rather through Handler objects associated with the Looper.

   Looper Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.

   class LooperThread extends Thread {
      public Handler mHandler;


      public void run() {
          Looper.prepare();


          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };


          Looper.loop();
      }
  }

    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.


There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.


Scheduling messages is accomplished with the post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long) methods. 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值