消息队列在线程里基本都有一个叫做“消息队列”的东西,它负责线程间通信。这是一种设计模式,所有控制指令或者内容在线程间传递。 消息队列如同它的名字那样,对于线程来说,它就是一个指令队列。这里我们还可以做一些更酷的事:
注意:这里说的“消息”和Runnable对象、指令队列的概念是一样的。 回到Android上的Handler……如果你仔细阅读的话,可以看到文档是这样说的: > A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. 所以Handler可以让你给线程队列发消息: > Each Handler instance is associated with a single thread and that thread’s message queue. 一个Handler对象只能和一个线程关联: > When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it 所以一个Handler到底和哪个线程关联呢?就是创造它的线程。 > — 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类实例绑定,而且可以和别的线程一起运行,相互通信。 还有一个小建议(如果用过AsyncTask的话),AsyncTask内部也是使用Handler进行处理的,只是不是运行在UI线程而已,它会提供一个channel来和UI线程通信,使用postExecute方法即可实现。 这还挺酷的,那怎么创建Handler呢?有两种方式:
Handler里面有什么实用的API吗?请记住:
如果你现在看看Handler的API,可以清楚看到这几个方法:
代码示例这里的代码都是很基础的,不过你可以好好看看注释。 示例1:使用Handler的“post”方法
如果根本就没有Handler对象,回调post方法会比较难办。 |