Handler用法
一、Handler的定義
主要接受子線程發送的數據,並用此數據配合主線程更新UI。
當應用程序啟動時,Android首先會開啟一個主線程 (即UI線程),主線程管理界面中的UI控件,進行事件分發,比如說:點擊Button,Android系統會分發事件到Button上,來響應你的操作。如果此時需要一個耗時的操作,例如: 聯網讀取數據,或者讀取本地較大的一個文件的時候,你不能把這些操作放在主線程中,如果你放在主線程中的話,界面會出現假死現象,如果5秒鍾還沒有完成的話,會收到Android系統的一個錯誤提示“強制關閉”。這個時候我們需要把這些耗時的操作,放在一個子線程中。
因為子線程涉及到UI更新,Android主線程是線程不安全的,也就是說,更新UI只能在主線程中更新,子線程中操作是危險的。這個時候,Handler就出現了。來解決這個復雜的問題,由於Handler運行在主線程中(UI線程中), 它與子線程可以通過Message對象來傳遞數據,這個時候,Handler就承擔着接受子線程傳過來的(子線程用sedMessage()方法傳遞Message對象,(里面包含數據),把這些消息放入主線程隊列中,配合主線程進行更新UI。
二、Handler一些特點
public class Handler extends Object
java.lang.object à android.os.Handler
已知直接子類:
AsyncQueryHandler
AsyncQueryHandler.WorkerHandler
HttpAuthHandler
SslErrorHandler
類概述:
| A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- 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允許你發送和處理Message(消息)和與一個線程相關的MessageQueue(消息隊列)的Runnable對象,每一個Handler實例都與一個單獨的線程和該線程的消息隊列相關。當你創建一個新的Handler,它被綁定到創建它的線程/消息隊列線程中。從這一點上來說,它將傳遞消息和runnable對象,並且執行他們,因為他們來自於消息隊列中。
| There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own. |
Handler有兩個主要用法:1、安排messages和runnables在將來的某些點上執行;2、排列一個將來執行的動作在一個不同的線程中
| Scheduling messages is accomplished with the post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long) methods. The post versions allow you to enqueue Runnable objects to be called by the message queue when they are received; the sendMessage versions allow you to enqueue a Message object containing a bundle of data that will be processed by the Handler's handleMessage(Message) method (requiring that you implement a subclass of Handler). |
安排messages是通過 post(Runnable), postAtTime(Runnable, long),
postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long)方法來完成的。The post versions允許你排列Runnable對象被接收到的消息隊列所調用;the sendMessage versions允許您排列一個包含了大量將被Handler的handleMessage(Message)方法處理的數據的Message對象(需要你實現Handler的一個子類)。
| When posting or sending to a Handler, you can either allow the item to be processed as soon as the message queue is ready to do so, or specify a delay before it gets processed or absolute time for it to be processed. The latter two allow you to implement timeouts, ticks, and other timing-based behavior. |
當posting或sending一個Handler,您可以允許item當message對列一准備就緒就進行處理,你也可以在它被處理之前指定一個延遲或絕對時間對它進行處理。后兩個允許您實現超時和其他以時序為基礎的行為。
| When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create. You can create your own threads, and communicate back with the main application thread through a Handler. This is done by calling the same post or sendMessage methods as before, but from your new thread. The given Runnable or Message will then be scheduled in the Handler's message queue and processed when appropriate. |
當一個進程在你的應用中被創建,它的主線程致力於運行一個負責管理頂級應用程序對象(如:活動、廣播接收器等)和他們創建的任何windows的消息隊列。您可以創建你自己的線程,通過Handler與主應用線程進行交互。這樣都在之前通過調用的同一個post和sendMessage方法實現的,但是來自你的新線程。給定的Runnable或Message將被安排在Handler的message隊列,並在適當的時候進行處理。
摘要
嵌套類
| 接口 |
Handler.Callback |
Callback interface you can use when instantiating a Handler to avoid having to implement your own subclass of Handler. |
實例化一個避免實現你自己子類的Handler的Handler時的回調接口。
Public Constructors(公共構造函數)
| Handler() |
| Default constructor associates this handler with the queue for the current thread. If there isn't one, this handler won't be able to receive messages. 將handler和當前線程的隊列聯系起來的默認構造函數。如果不是一個,該handler將不能接收消息。 |
| 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和當前線程的隊列和你能處理消息的回調接口聯系起來的構造函數。 |
| 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. 用提供的對列代替默認的,處理消息的回調接口。 |
Public Methods(公共方法)
| void |
dispatchMessage(Message msg) |
||||
| Handle system messages here. 這里處理系統的消息。 |
|||||
| final void |
dump(Printer pw, String prefix) |
||||
| final Looper |
getLooper() |
||||
| String |
getMessageName(Message message) |
||||
| Returns a string representing the name of the specified message. The default implementation will either return the class name of the message callback if any, or the hexadecimal representation of the message "what" field. 返回一個代表指定消息名字的字符串。它的默認實現將返回這個回調消息的類名,或者這個消息“what”字段的十六進制的代表。 |
|||||
| void |
handleMessage(Message msg) |
||||
| Subclasses must implement this to receive messages. 子類必須實現它用來接收消息。 |
|||||
| final boolean |
hasMessages(int what, Object object) |
||||
| Check if there are any pending posts of messages with code 'what' and whose obj is 'object' in the message queue. 檢查是否有任何即將post帶代碼“what”和它的obj 是“object”的消息在消息隊列。 |
|||||
| final boolean |
hasMessages(int what) |
||||
| Check if there are any pending posts of messages with code 'what' in the message queue. 檢查是否有任何即將post帶代碼“what”的消息在消息隊列。 |
|||||
| final Message |
obtainMessage(int what, int arg1, int arg2) |
||||
| Same as obtainMessage(), except that it also sets the what, arg1 and arg2 members of the returned Message. 與obtainMessage()方法一樣,除此之外它也能設置what,arg1和arg2返回消息的成員。 |
|||||
| final Message |
obtainMessage() |
||||
| Returns a new Message from the global message pool. More efficient than creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this). If you don't want that facility, just call Message.obtain() instead. 從全局消息池中返回一個新的消息。比創建和分配新的實例有效率。這個的重新取回的消息有它的handler設置到這個實例。如果你不想要那套設施,可以通過調用的Message.obtain() 方法替代。 |
|||||
| final Message |
obtainMessage(int what, int arg1, int arg2, Object obj) |
||||
| Same as obtainMessage(), except that it also sets the what, obj, arg1,and arg2 values on the returned Message. 與obtainMessage()方法一樣,除此之外它也能設置what,obj,arg1和arg2返回消息值。 |
|||||
| final Message |
obtainMessage(int what) |
||||
| Same as obtainMessage(), except that it also sets the what member of the returned Message. 與obtainMessage()方法一樣,除此之外它也能設置what返回消息成員。 |
|||||
| final Message |
obtainMessage(int what, Object obj) |
||||
| Same as obtainMessage(), except that it also sets the what and obj members of the returned Message. 與obtainMessage()方法一樣,除此之外它也能設置obj返回消息成員。 |
|||||
| final boolean |
post(Runnable r) |
||||
| Causes the Runnable r to be added to the message queue. 使Runnable r添加到消息隊列。 Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. 如果Runnable被成功放置在消息隊列中就返回true,如果失敗就返回false,常常因為the looper處理消息隊列正在退出。 |
|||||
| final boolean |
postAtFrontOfQueue(Runnable r) |
||||
| Posts a message to an object that implements Runnable. 發布一個消息到一個實現了Runnable的對象。 Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. 如果Runnable被成功放置在消息隊列中就返回true,如果失敗就返回false,常常因為the looper處理消息隊列正在退出。 |
|||||
| final boolean |
postAtTime(Runnable r, Object token, long uptimeMillis) |
||||
| Causes the Runnable r to be added to the message queue, to be run at a specific time given by uptimeMillis. 使Runnable r添加到消息隊列中,運行在一個uptimeMillis給出的特定時間。 Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped. 如果Runnable被成功放置在消息隊列中就返回true,如果失敗就返回false,常常因為the looper處理消息隊列正在退出。注意true的結果並不意味着Runnable將被執行,如果的這個looper在發送消息之前放棄了,這個消息將被放棄。 |
|||||
| final boolean |
postAtTime(Runnable r, long uptimeMillis) |
||||
| Causes the Runnable r to be added to the message queue, to be run at a specific time given by uptimeMillis. 使Runnable r添加到消息隊列中,運行在一個uptimeMillis給出的特定時間。 Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped. 如果Runnable被成功放置在消息隊列中就返回true,如果失敗就返回false,常常因為the looper處理消息隊列正在退出。注意true的結果並不意味着Runnable將被執行,如果的這個looper在發送消息之前放棄了,這個消息將被放棄。 |
|||||
| final boolean |
postDelayed(Runnable r, long delayMillis) |
||||
| Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. 使Runnable r添加到消息隊列,運行在指定時間的流逝之后。 Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped. 如果Runnable被成功放置在消息隊列中就返回true,如果失敗就返回false,常常因為the looper處理消息隊列正在退出。注意true的結果並不意味着Runnable將被執行,如果的這個looper在發送消息之前放棄了,這個消息將被放棄。 |
|||||
| final void |
removeCallbacks(Runnable r) |
||||
| Remove any pending posts of Runnable r that are in the message queue. 移除任何即將發布的在消息隊列里的Runnable r。 |
|||||
| final void |
removeCallbacks(Runnable r, Object token) |
||||
| Remove any pending posts of Runnable r with Object token that are in the message queue. 移除任何即將發布的有Object token在消息隊列里的Runnable r。 |
|||||
| final void |
removeCallbacksAndMessages(Object token) |
||||
| Remove any pending posts of callbacks and sent messages whose obj is token. 移除任何即將發布的回調和發送obj是token的消息。 |
|||||
| final void |
removeMessages(int what) |
||||
| Remove any pending posts of messages with code 'what' that are in the message queue. 移除任何即將發布的有代碼“what”的在消息隊列中的消息。 |
|||||
| final void |
removeMessages(int what, Object object) |
||||
| Remove any pending posts of messages with code 'what' and whose obj is 'object' that are in the message queue. 移除任何即將發布的有代碼“what”和它的obj是“object”的在消息隊列中的消息。 |
|||||
| final boolean |
sendEmptyMessage(int what) |
||||
| Sends a Message containing only the what value. 發送一個僅包含what值的消息。 Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. 如果Runnable被成功放置在消息隊列中就返回true,如果失敗就返回false,常常因為the looper處理消息隊列正在退出。 |
|||||
| final boolean |
sendEmptyMessageAtTime(int what, long uptimeMillis) |
||||
| Sends a Message containing only the what value, to be delivered at a specific time. 發送一個僅包含what值的將在一個特定時間送達的消息。 Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. 如果Runnable被成功放置在消息隊列中就返回true,如果失敗就返回false,常常因為the looper處理消息隊列正在退出。 |
|||||
| final boolean |
sendEmptyMessageDelayed(int what, long delayMillis) |
||||
| Sends a Message containing only the what value, to be delivered after the specified amount of time elapses. 發送一個僅包含what值的將在特定的時間流逝后送達的消息。 Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. 如果Runnable被成功放置在消息隊列中就返回true,如果失敗就返回false,常常因為the looper處理消息隊列正在退出。 |
|||||
| final boolean |
sendMessage(Message msg) |
||||
| Pushes a message onto the end of the message queue after all pending messages before the current time. 將一個消息推到當前時間之前的所有掛起的消息之后的消息隊列的最后。 Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. 如果Runnable被成功放置在消息隊列中就返回true,如果失敗就返回false,常常因為the looper處理消息隊列正在退出。 |
|||||
| final boolean |
sendMessageAtFrontOfQueue(Message msg) |
||||
| Enqueue a message at the front of the message queue, to be processed on the next iteration of the message loop. You will receive it in handleMessage(Message), in the thread attached to this handler. This method is only for use in very special circumstances -- it can easily starve the message queue, cause ordering problems, or have other unexpected side-effects. 排列一個在消息隊列前面的消息,處理下一個message loop的迭代。你將在附屬於這個handler的線程里的handleMessage(Message)方法里接收到它。這個方法只能在特殊的情況下使用,它很容易餓死消息隊列,引起排序問題,或者還有其他意想不到的副作用。 Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. 如果Runnable被成功放置在消息隊列中就返回true,如果失敗就返回false,常常因為the looper處理消息隊列正在退出。 |
|||||
| boolean |
sendMessageAtTime(Message msg, long uptimeMillis) |
||||
| Enqueue a message into the message queue after all pending messages before the absolute time (in milliseconds) uptimeMillis. The time-base is uptimeMillis(). You will receive it in handleMessage(Message), in the thread attached to this handler. 排列一個消息進入在絕對時間之前的所有的掛起的消息之后的消息隊列。時間坐標是uptimeMillis()。你將在附屬於這個handler的線程里的handleMessage(Message)方法里接收到它。 Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped. 如果Runnable被成功放置在消息隊列中就返回true,如果失敗就返回false,常常因為the looper處理消息隊列正在退出。注意true的結果並不意味着Runnable將被執行,如果的這個looper在發送消息之前放棄了,這個消息將被放棄。 |
|||||
| final boolean |
sendMessageDelayed(Message msg, long delayMillis) |
||||
| Enqueue a message into the message queue after all pending messages before (current time + delayMillis). You will receive it in handleMessage(Message), in the thread attached to this handler 排列一個消息進入在(當前時間+延遲時間)之前的所有的掛起的消息之后的消息隊列。你將在附屬於這個handler的線程里的handleMessage(Message)方法里接收到它。 Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped. 如果Runnable被成功放置在消息隊列中就返回true,如果失敗就返回false,常常因為the looper處理消息隊列正在退出。注意true的結果並不意味着Runnable將被執行,如果的這個looper在發送消息之前放棄了,這個消息將被放棄。 |
|||||
| String |
toString() |
||||
| Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression: getClass().getName() + '@' + Integer.toHexString(hashCode()) See Writing a useful toString method if you intend implementing your own toString method. 返回一個包含該對象的簡潔的、可讀的描述性的字符串。在子類鼓勵覆寫這個方法,提供一個了解這個對象的類型和數據的實現。默認的實現相當於下面的表達式: getClass().getName() + '@' + Integer.toHexString(hashCode()) 如果你想實現你自己的toString方法,看看寫一個有用的toString方法。 |
|||||
Inherited Methods(繼承方法)
From class java.lang.Object(Object類)
| Object |
clone() |
| Creates and returns a copy of this Object. 創建並返回這個對象的一個副本。 |
|
| boolean |
equals(Object o) |
| Compares this instance with the specified object and indicates if they are equal. 比較該實例與指定的對象,並表示他們是否相等。 |
|
| void |
finalize() |
| Invoked when the garbage collector has detected that this instance is no longer reachable. 當垃圾收集器發現這個實例不再是可獲得的時候調用此方法。 |
|
| final Class<?> |
getClass() |
| Returns the unique instance of Class that represents this object's class. 返回代表這個對象的class的類的獨特實例。 |
|
| int |
hashCode() |
| Returns an integer hash code for this object. 返回該對象的整數哈希值。 |
|
| final void |
notify() |
| Causes a thread which is waiting on this object's monitor (by means of calling one of the wait() methods) to be woken up. 讓一個正在等待該對象的監聽器(通過調用wait()方法)的線程被喚醒。 |
|
| final void |
notifyAll() |
| Causes all threads which are waiting on this object's monitor (by means of calling one of the wait() methods) to be woken up. 讓所有正在等待該對象的監聽器(通過調用wait()方法)的線程被喚醒。 |
|
| String |
toString() |
| Returns a string containing a concise, human-readable description of this object. 返回一個包含該對象的簡潔的、可讀的描述性的字符串。 |
|
| final void |
wait() |
| Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object. 讓該調用線程處於等待狀態直到有另一個線程調用該對象的notify()或者notifyAll()方法。 |
|
| final void |
wait(long millis, int nanos) |
| Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the specified timeout expires. 讓該調用線程處於等待狀態直到有另一個線程調用該對象的notify()或者notifyAll()方法或者是到指定的超時時限。 |
|
| final void |
wait(long millis) |
| Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the specified timeout expires. 讓該調用線程處於等待狀態直到有另一個線程調用該對象的notify()或者notifyAll()方法或者是到指定的超時時限。 |
|
