Handler的定义:
主要接受子线程发送的数据,并用此数据配合主线程更新UI.
解释: 当应用程序启动时,Android首先会开启一个主线程 (也就是UI线程) , 主线程为管理界面中的UI控件,进行事件分发, 比如说, 你要是点击一个 Button ,Android会分发事件到Button上,来响应你的操作。 如果此时需要一个耗时的操作,例如: 联网读取数据,或者读取本地较大的一个文件的时候,你不能把这些操作放在主线程中,如果你放在主线程中的话,界面会出现假死现象, 如果5秒钟还没有完成的话,会收到Android系统的一个错误提示 "强制关闭".
这个时候我们需要把这些耗时的操作,放在一个子线程中,因为子线程涉及到UI更新,Android主线程是线程不安全的,也就是说,更新UI只能在主线程中更新,子线程中操作是危险的. 这个时候,Handler就出现了,来解决这个复杂的问题。
由于Handler运行在主线程中(UI线程中), 它与子线程可以通过Message对象来传递数据, 这个时候,Handler就承担着接受子线程传过来的(子线程用sendMessage()方法传弟)Message对象,(里面包含数据) , 把这些消息放入主线程队列中,配合主线程进行更新UI。
参考:http://www.pin5i.com/showtopic-android-handler.html
Handler一些特点
handler可以分发Message对象和Runnable对象到主线程中, 每个Handler实例,都会绑定到创建他的线程中(一般是位于主线程),
它有两个作用:(1): 安排消息或Runnable 在某个主线程中某个地方执行, (2)安排一个动作在不同的线程中执行
Handler实例
- Handler处理Message 的方法:
1)子类需要继承Hendler类,通过Handler对象调用sendMessage 等方法发送Message数据
2)重写handleMessage(Messagemsg) 方法, 用于接受线程数据
- Handler处理线程的方法
处理的方式跟Thread对象有相似的地方
参考:http://blog.youkuaiyun.com/csf928437197/article/details/6632930
Handler类在Android API 里面的解释
AHandler allows you to send and process Message and Runnable objects associated with athread's MessageQueue. Each Handler instance is associatedwith a single thread and that thread's message queue. When you create a newHandler, it is bound to the thread / message queue of the thread that iscreating it -- from that point on, it will deliver messages and runnables tothat message queue and execute them as they come out of the message queue.
Thereare two main uses for a Handler:
(1) to schedule messages and runnables to beexecuted as some point in the future; and
(2) to enqueue an action to beperformed on a different thread than your own.