An
droid中的Activit
y、service和
Broadcast都是由
UI线程负责处理的。
http://my.unix-center.net/~Simon_fu/?p=652
UI线程默认已经含有消息循环和消息队列。
而其他由开发者自主生成的工作线程默认是没有消息队列和消息循环的。如果想生成,则可以用Looper.prepare();
Handler的作用是把消息加入特定的消息队列中(Looper的messageQuene),并分发和处理该消息队列中的消息。
构造Handler的时候可以指定一个Looper对象,如果不指定则利用当前线程的Looper创建。
如果要通过handler来处理界面更新,则可以通过以下两种分方式。
方式一:
一个Activity中可以创建多个工作线程或者其他的组件,如果这些线程或者组件把他们的消息放入Activity的主线程消息队列,那么该消息就会在主线程中处理了。因为主线程一般负责界面的更新操作,所以这种方式可以很好的实现Android界面更新。
方式二:只要Handler对象以主线程的Looper创建,那么调用 Handler的sendMessage,将会把消息放入主线程的消息队列。并且将会在主线程中调用该handler 的handleMessage方法来处理消息。
以上两种方法本质上都还是在UI线程中处理界面更新。
附:
handler构造方法
Public Constructors | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Handler()
Default constructor associates this handler with the queue for the current thread.
| |||||||||||
Handler(
Handler.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
Use the provided queue instead of the default one.
| |||||||||||
Handler(
Looper
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
| ||||||||||
synchronized final static
|
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
|
myLooper()
Return the Looper object associated with the current thread.
| ||||||||||
final static
| myQueue() | ||||||||||
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
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.
|