handler

来源:互联网 发布:js图片触摸缩放 编辑:程序博客网 时间:2024/06/05 08:33


sendEmptyMessage方法的源码
/**
* Sends a Message containing only the what value.

* @return Returns true if the message was successfully placed in to the 
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean sendEmptyMessage(int what)
{
   return sendEmptyMessageDelayed(what, 0);
}




sendMessage方法的源码


/**
* Sends a Message containing only the what value, to be delivered
* after the specified amount of time elapses.
* @see #sendMessageDelayed(android.os.Message, long) 

* @return Returns true if the message was successfully placed in to the 
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}


构建message!


Handler是用于操作线程内部的消息队列的类。


Looper可以让消息队列(MessageQueue)附属在线程之内,并让消息队列循环起来,接收并处理消息。


但,我们并不直接的操作消息队列,而是用Handler来操作消息队列,给消息队列发送消息,


和从消息队列中取出消息并处理。这就是Handler的职责。


Handler,Looper和MessageQueue是属于一个线程内部的数据,但是它提供给外部线程访问的接口,Handler就是公开给外部线程,与线程通讯的接口。


换句话说,这三个东西都是用来线程间通讯用的(ITC--Inter Thread Communication),与进行间通讯(IPC--Inter Process Communication)的消息队列msgque的核心


思想是一致的。


MessageQueue是相对较底层的,较少直接使用,Looper和Handler就是专门用来操作底层MessageQueue的。


还有一个重要的数据结构是通讯的基本元素,就是消息对象(Message),Message从来不单独使用,它都是跟随Handler来使用的。具体方法可以参考文档,但需要注意的是


同一个消息对象不能发送二次,否则会有AndroidRuntimeException: { what=1000 when=-15ms obj=.. } This message is already in use."。


每次发送消息前都要通过Message.obtain()来获取新的对象,或者,对于不需要传送额外数据的直接发送空消息就好Handler.sendEmptyMessage(int)。


另外也需要注意消息对象是不能手动回收的,也就是说你不能调用Message.recycle()来释放一个消息对象,因为当该对象被从队列中取出处理完毕后,MessageQueue内部


会自动的去做recycle()。


这个理解起来也很容易,因为发送一个消息到消息队列后,消息什么时候会被处理,对于应用程序来讲是不知道的,只有MessageQueue才会知道,所以只能由MessageQue


ue来做回收释放的动作。


因为Handler是用于操作一个线程内部的消息队列的,所以Handler必须依附于一个线程,而且只能是一个线程。


换句话说,你必须在一个线程内创建Handler,同时指定Handler的回调handlerMessage(Message msg)。


Handler主要有二个用途,一个是用于线程内部消息循环; 另外一个就是用于线程间通讯。


Handler的基本用法可以参考文档,说的还是比较清楚的。


用于线程内部消息循环


主要是用作在将来定时做某个动作,或者循环性,周期性的做某个动作。主要的接口就是


    Handler.sendEmptyMessageDelayed(int msgid, long after);
    Handler.sendMessageDelayed(Message msg, long after);
    Handler.postDelayed(Runnable task, long after);
    Handler.sendMessageAtTime(Message msg, long timeMillis);
    Handler.sendEmptyMessageAtTime(int id, long timeMiilis);
    Handler.postAtTime(Runnable task, long timeMillis);


这些方法的目的都是设置一个定时器,在指定的时间后,或者在指定的时间向Handler所在的MessageQueue发送消息。


这样就非常方便应用程序实现定时操作,或者循环时序操作(处理消息时再延时发送消息,以达成循环时序)。


这个使用起来并不难,但需要注意一点的是,线程内部消息循环并不是并发处理,也就是所有的消息都是在Handler所属的线程内处理的,所以虽然你用post(Runnable r),


发给MessageQueue一个Runnable,但这并不会创建新的线程来执行,处理此消息时仅是调用r.run()。


(想要另起线程执行,必须把Runnable放到一个Thread中)。
0 0
原创粉丝点击