Android中UI线程Looper,Handler的关系

An droid中的Activit y、service和 Broadcast都是由 UI线程负责处理的。
UI线程默认已经含有消息循环和消息队列。
而其他由开发者自主生成的工作线程默认是没有消息队列和消息循环的。如果想生成,则可以用Looper.prepare();
Handler的作用是把消息加入特定的消息队列中(Looper的messageQuene),并分发和处理该消息队列中的消息。 构造Handler的时候可以指定一个Looper对象,如果不指定则利用当前线程的Looper创建。

如果要通过handler来处理界面更新,则可以通过以下两种分方式。
方式一: 一个Activity中可以创建多个工作线程或者其他的组件,如果这些线程或者组件把他们的消息放入Activity的主线程消息队列,那么该消息就会在主线程中处理了。因为主线程一般负责界面的更新操作,所以这种方式可以很好的实现Android界面更新。
方式二:只要Handler对象以主线程的Looper创建,那么调用 HandlersendMessage,将会把消息放入主线程的消息队列。并且将会在主线程中调用该handler handleMessage方法来处理消息。

以上两种方法本质上都还是在UI线程中处理界面更新。
附:
handler构造方法
Public Constructors
  Handler()
Default constructor associates this handler with the queue for the current thread.
  Handler( Handler.Callback  callback)
Constructor associates this handler with the queue for the current thread and takes a callback interface in which you can handle messages.
  Handler( Looper  looper)
Use the provided queue instead of the default one.
  Handler( Looper  looper,  Handler.Callback  callback)
Use the provided queue instead of the default one and take a callback interface in which to handle messages.
Looper的公共方法
Public Methods
void dump( Printer  pw,  String  prefix)
synchronized final static  Looper getMainLooper()
Returns the application's main looper, which lives in the main thread of the application.(UI thread)
Thread getThread()
Return the Thread associated with this Looper.(work
thread)
final static void loop()
Run the message queue in this thread.
final static  Looper myLooper()
Return the Looper object associated with the current thread.
final static  MessageQueue myQueue()
Return the  MessageQueue  object associated with the current thread.
final static void prepare()
Initialize the current thread as a looper.
final static void prepareMainLooper()
Initialize the current thread as a looper, marking it as an application's main looper.
void quit()
void setMessageLogging( Printer  printer)
Control logging of messages as they are processed by this Looper.
String toString()
Returns a string containing a concise, human-readable description of this object.

http://my.unix-center.net/~Simon_fu/?p=652
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值