关闭

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

标签: androidHandler MessageQueue
373人阅读 评论(0) 收藏 举报
分类:

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
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7639次
    • 积分:264
    • 等级:
    • 排名:千里之外
    • 原创:20篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条