1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.os;
18 
19 import android.util.Log;
20 import android.util.Printer;
21 
22 import java.lang.reflect.Modifier;
23 
24 /**
25  * A Handler allows you to send and process {@link Message} and Runnable
26  * objects associated with a thread's {@link MessageQueue}.  Each Handler
27  * instance is associated with a single thread and that thread's message
28  * queue.  When you create a new Handler, it is bound to the thread /
29  * message queue of the thread that is creating it -- from that point on,
30  * it will deliver messages and runnables to that message queue and execute
31  * them as they come out of the message queue.
32  *
33  * <p>There are two main uses for a Handler: (1) to schedule messages and
34  * runnables to be executed as some point in the future; and (2) to enqueue
35  * an action to be performed on a different thread than your own.
36  *
37  * <p>Scheduling messages is accomplished with the
38  * {@link #post}, {@link #postAtTime(Runnable, long)},
39  * {@link #postDelayed}, {@link #sendEmptyMessage},
40  * {@link #sendMessage}, {@link #sendMessageAtTime}, and
41  * {@link #sendMessageDelayed} methods.  The <em>post</em> versions allow
42  * you to enqueue Runnable objects to be called by the message queue when
43  * they are received; the <em>sendMessage</em> versions allow you to enqueue
44  * a {@link Message} object containing a bundle of data that will be
45  * processed by the Handler's {@link #handleMessage} method (requiring that
46  * you implement a subclass of Handler).
47  *
48  * <p>When posting or sending to a Handler, you can either
49  * allow the item to be processed as soon as the message queue is ready
50  * to do so, or specify a delay before it gets processed or absolute time for
51  * it to be processed.  The latter two allow you to implement timeouts,
52  * ticks, and other timing-based behavior.
53  *
54  * <p>When a
55  * process is created for your application, its main thread is dedicated to
56  * running a message queue that takes care of managing the top-level
57  * application objects (activities, broadcast receivers, etc) and any windows
58  * they create.  You can create your own threads, and communicate back with
59  * the main application thread through a Handler.  This is done by calling
60  * the same <em>post</em> or <em>sendMessage</em> methods as before, but from
61  * your new thread.  The given Runnable or Message will then be scheduled
62  * in the Handler's message queue and processed when appropriate.
63  */
64 public class Handler {
65     /*
66      * Set this flag to true to detect anonymous, local or member classes
67      * that extend this Handler class and that are not static. These kind
68      * of classes can potentially create leaks.
69      */
70     private static final boolean FIND_POTENTIAL_LEAKS = false;
71     private static final String TAG = "Handler";
72 
73     /**
74      * Callback interface you can use when instantiating a Handler to avoid
75      * having to implement your own subclass of Handler.
76      *
77      * @param msg A {@link android.os.Message Message} object
78      * @return True if no further handling is desired
79      */
80     public interface Callback {
handleMessage(Message msg)81         public boolean handleMessage(Message msg);
82     }
83 
84     /**
85      * Subclasses must implement this to receive messages.
86      */
handleMessage(Message msg)87     public void handleMessage(Message msg) {
88     }
89 
90     /**
91      * Handle system messages here.
92      */
dispatchMessage(Message msg)93     public void dispatchMessage(Message msg) {
94         if (msg.callback != null) {
95             handleCallback(msg);
96         } else {
97             if (mCallback != null) {
98                 if (mCallback.handleMessage(msg)) {
99                     return;
100                 }
101             }
102             handleMessage(msg);
103         }
104     }
105 
106     /**
107      * Default constructor associates this handler with the {@link Looper} for the
108      * current thread.
109      *
110      * If this thread does not have a looper, this handler won't be able to receive messages
111      * so an exception is thrown.
112      */
Handler()113     public Handler() {
114         this(null, false);
115     }
116 
117     /**
118      * Constructor associates this handler with the {@link Looper} for the
119      * current thread and takes a callback interface in which you can handle
120      * messages.
121      *
122      * If this thread does not have a looper, this handler won't be able to receive messages
123      * so an exception is thrown.
124      *
125      * @param callback The callback interface in which to handle messages, or null.
126      */
Handler(Callback callback)127     public Handler(Callback callback) {
128         this(callback, false);
129     }
130 
131     /**
132      * Use the provided {@link Looper} instead of the default one.
133      *
134      * @param looper The looper, must not be null.
135      */
Handler(Looper looper)136     public Handler(Looper looper) {
137         this(looper, null, false);
138     }
139 
140     /**
141      * Use the provided {@link Looper} instead of the default one and take a callback
142      * interface in which to handle messages.
143      *
144      * @param looper The looper, must not be null.
145      * @param callback The callback interface in which to handle messages, or null.
146      */
Handler(Looper looper, Callback callback)147     public Handler(Looper looper, Callback callback) {
148         this(looper, callback, false);
149     }
150 
151     /**
152      * Use the {@link Looper} for the current thread
153      * and set whether the handler should be asynchronous.
154      *
155      * Handlers are synchronous by default unless this constructor is used to make
156      * one that is strictly asynchronous.
157      *
158      * Asynchronous messages represent interrupts or events that do not require global ordering
159      * with respect to synchronous messages.  Asynchronous messages are not subject to
160      * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
161      *
162      * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
163      * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
164      *
165      * @hide
166      */
Handler(boolean async)167     public Handler(boolean async) {
168         this(null, async);
169     }
170 
171     /**
172      * Use the {@link Looper} for the current thread with the specified callback interface
173      * and set whether the handler should be asynchronous.
174      *
175      * Handlers are synchronous by default unless this constructor is used to make
176      * one that is strictly asynchronous.
177      *
178      * Asynchronous messages represent interrupts or events that do not require global ordering
179      * with respect to synchronous messages.  Asynchronous messages are not subject to
180      * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
181      *
182      * @param callback The callback interface in which to handle messages, or null.
183      * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
184      * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
185      *
186      * @hide
187      */
Handler(Callback callback, boolean async)188     public Handler(Callback callback, boolean async) {
189         if (FIND_POTENTIAL_LEAKS) {
190             final Class<? extends Handler> klass = getClass();
191             if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
192                     (klass.getModifiers() & Modifier.STATIC) == 0) {
193                 Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
194                     klass.getCanonicalName());
195             }
196         }
197 
198         mLooper = Looper.myLooper();
199         if (mLooper == null) {
200             throw new RuntimeException(
201                 "Can't create handler inside thread that has not called Looper.prepare()");
202         }
203         mQueue = mLooper.mQueue;
204         mCallback = callback;
205         mAsynchronous = async;
206     }
207 
208     /**
209      * Use the provided {@link Looper} instead of the default one and take a callback
210      * interface in which to handle messages.  Also set whether the handler
211      * should be asynchronous.
212      *
213      * Handlers are synchronous by default unless this constructor is used to make
214      * one that is strictly asynchronous.
215      *
216      * Asynchronous messages represent interrupts or events that do not require global ordering
217      * with respect to synchronous messages.  Asynchronous messages are not subject to
218      * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
219      *
220      * @param looper The looper, must not be null.
221      * @param callback The callback interface in which to handle messages, or null.
222      * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
223      * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
224      *
225      * @hide
226      */
Handler(Looper looper, Callback callback, boolean async)227     public Handler(Looper looper, Callback callback, boolean async) {
228         mLooper = looper;
229         mQueue = looper.mQueue;
230         mCallback = callback;
231         mAsynchronous = async;
232     }
233 
234     /**
235      * Returns a string representing the name of the specified message.
236      * The default implementation will either return the class name of the
237      * message callback if any, or the hexadecimal representation of the
238      * message "what" field.
239      *
240      * @param message The message whose name is being queried
241      */
getMessageName(Message message)242     public String getMessageName(Message message) {
243         if (message.callback != null) {
244             return message.callback.getClass().getName();
245         }
246         return "0x" + Integer.toHexString(message.what);
247     }
248 
249     /**
250      * Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
251      * creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
252      *  If you don't want that facility, just call Message.obtain() instead.
253      */
obtainMessage()254     public final Message obtainMessage()
255     {
256         return Message.obtain(this);
257     }
258 
259     /**
260      * Same as {@link #obtainMessage()}, except that it also sets the what member of the returned Message.
261      *
262      * @param what Value to assign to the returned Message.what field.
263      * @return A Message from the global message pool.
264      */
obtainMessage(int what)265     public final Message obtainMessage(int what)
266     {
267         return Message.obtain(this, what);
268     }
269 
270     /**
271      *
272      * Same as {@link #obtainMessage()}, except that it also sets the what and obj members
273      * of the returned Message.
274      *
275      * @param what Value to assign to the returned Message.what field.
276      * @param obj Value to assign to the returned Message.obj field.
277      * @return A Message from the global message pool.
278      */
obtainMessage(int what, Object obj)279     public final Message obtainMessage(int what, Object obj)
280     {
281         return Message.obtain(this, what, obj);
282     }
283 
284     /**
285      *
286      * Same as {@link #obtainMessage()}, except that it also sets the what, arg1 and arg2 members of the returned
287      * Message.
288      * @param what Value to assign to the returned Message.what field.
289      * @param arg1 Value to assign to the returned Message.arg1 field.
290      * @param arg2 Value to assign to the returned Message.arg2 field.
291      * @return A Message from the global message pool.
292      */
obtainMessage(int what, int arg1, int arg2)293     public final Message obtainMessage(int what, int arg1, int arg2)
294     {
295         return Message.obtain(this, what, arg1, arg2);
296     }
297 
298     /**
299      *
300      * Same as {@link #obtainMessage()}, except that it also sets the what, obj, arg1,and arg2 values on the
301      * returned Message.
302      * @param what Value to assign to the returned Message.what field.
303      * @param arg1 Value to assign to the returned Message.arg1 field.
304      * @param arg2 Value to assign to the returned Message.arg2 field.
305      * @param obj Value to assign to the returned Message.obj field.
306      * @return A Message from the global message pool.
307      */
obtainMessage(int what, int arg1, int arg2, Object obj)308     public final Message obtainMessage(int what, int arg1, int arg2, Object obj)
309     {
310         return Message.obtain(this, what, arg1, arg2, obj);
311     }
312 
313     /**
314      * Causes the Runnable r to be added to the message queue.
315      * The runnable will be run on the thread to which this handler is
316      * attached.
317      *
318      * @param r The Runnable that will be executed.
319      *
320      * @return Returns true if the Runnable was successfully placed in to the
321      *         message queue.  Returns false on failure, usually because the
322      *         looper processing the message queue is exiting.
323      */
post(Runnable r)324     public final boolean post(Runnable r)
325     {
326        return  sendMessageDelayed(getPostMessage(r), 0);
327     }
328 
329     /**
330      * Causes the Runnable r to be added to the message queue, to be run
331      * at a specific time given by <var>uptimeMillis</var>.
332      * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
333      * Time spent in deep sleep will add an additional delay to execution.
334      * The runnable will be run on the thread to which this handler is attached.
335      *
336      * @param r The Runnable that will be executed.
337      * @param uptimeMillis The absolute time at which the callback should run,
338      *         using the {@link android.os.SystemClock#uptimeMillis} time-base.
339      *
340      * @return Returns true if the Runnable was successfully placed in to the
341      *         message queue.  Returns false on failure, usually because the
342      *         looper processing the message queue is exiting.  Note that a
343      *         result of true does not mean the Runnable will be processed -- if
344      *         the looper is quit before the delivery time of the message
345      *         occurs then the message will be dropped.
346      */
postAtTime(Runnable r, long uptimeMillis)347     public final boolean postAtTime(Runnable r, long uptimeMillis)
348     {
349         return sendMessageAtTime(getPostMessage(r), uptimeMillis);
350     }
351 
352     /**
353      * Causes the Runnable r to be added to the message queue, to be run
354      * at a specific time given by <var>uptimeMillis</var>.
355      * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
356      * Time spent in deep sleep will add an additional delay to execution.
357      * The runnable will be run on the thread to which this handler is attached.
358      *
359      * @param r The Runnable that will be executed.
360      * @param uptimeMillis The absolute time at which the callback should run,
361      *         using the {@link android.os.SystemClock#uptimeMillis} time-base.
362      *
363      * @return Returns true if the Runnable was successfully placed in to the
364      *         message queue.  Returns false on failure, usually because the
365      *         looper processing the message queue is exiting.  Note that a
366      *         result of true does not mean the Runnable will be processed -- if
367      *         the looper is quit before the delivery time of the message
368      *         occurs then the message will be dropped.
369      *
370      * @see android.os.SystemClock#uptimeMillis
371      */
postAtTime(Runnable r, Object token, long uptimeMillis)372     public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
373     {
374         return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
375     }
376 
377     /**
378      * Causes the Runnable r to be added to the message queue, to be run
379      * after the specified amount of time elapses.
380      * The runnable will be run on the thread to which this handler
381      * is attached.
382      * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
383      * Time spent in deep sleep will add an additional delay to execution.
384      *
385      * @param r The Runnable that will be executed.
386      * @param delayMillis The delay (in milliseconds) until the Runnable
387      *        will be executed.
388      *
389      * @return Returns true if the Runnable was successfully placed in to the
390      *         message queue.  Returns false on failure, usually because the
391      *         looper processing the message queue is exiting.  Note that a
392      *         result of true does not mean the Runnable will be processed --
393      *         if the looper is quit before the delivery time of the message
394      *         occurs then the message will be dropped.
395      */
postDelayed(Runnable r, long delayMillis)396     public final boolean postDelayed(Runnable r, long delayMillis)
397     {
398         return sendMessageDelayed(getPostMessage(r), delayMillis);
399     }
400 
401     /**
402      * Posts a message to an object that implements Runnable.
403      * Causes the Runnable r to executed on the next iteration through the
404      * message queue. The runnable will be run on the thread to which this
405      * handler is attached.
406      * <b>This method is only for use in very special circumstances -- it
407      * can easily starve the message queue, cause ordering problems, or have
408      * other unexpected side-effects.</b>
409      *
410      * @param r The Runnable that will be executed.
411      *
412      * @return Returns true if the message was successfully placed in to the
413      *         message queue.  Returns false on failure, usually because the
414      *         looper processing the message queue is exiting.
415      */
postAtFrontOfQueue(Runnable r)416     public final boolean postAtFrontOfQueue(Runnable r)
417     {
418         return sendMessageAtFrontOfQueue(getPostMessage(r));
419     }
420 
421     /**
422      * Runs the specified task synchronously.
423      * <p>
424      * If the current thread is the same as the handler thread, then the runnable
425      * runs immediately without being enqueued.  Otherwise, posts the runnable
426      * to the handler and waits for it to complete before returning.
427      * </p><p>
428      * This method is dangerous!  Improper use can result in deadlocks.
429      * Never call this method while any locks are held or use it in a
430      * possibly re-entrant manner.
431      * </p><p>
432      * This method is occasionally useful in situations where a background thread
433      * must synchronously await completion of a task that must run on the
434      * handler's thread.  However, this problem is often a symptom of bad design.
435      * Consider improving the design (if possible) before resorting to this method.
436      * </p><p>
437      * One example of where you might want to use this method is when you just
438      * set up a Handler thread and need to perform some initialization steps on
439      * it before continuing execution.
440      * </p><p>
441      * If timeout occurs then this method returns <code>false</code> but the runnable
442      * will remain posted on the handler and may already be in progress or
443      * complete at a later time.
444      * </p><p>
445      * When using this method, be sure to use {@link Looper#quitSafely} when
446      * quitting the looper.  Otherwise {@link #runWithScissors} may hang indefinitely.
447      * (TODO: We should fix this by making MessageQueue aware of blocking runnables.)
448      * </p>
449      *
450      * @param r The Runnable that will be executed synchronously.
451      * @param timeout The timeout in milliseconds, or 0 to wait indefinitely.
452      *
453      * @return Returns true if the Runnable was successfully executed.
454      *         Returns false on failure, usually because the
455      *         looper processing the message queue is exiting.
456      *
457      * @hide This method is prone to abuse and should probably not be in the API.
458      * If we ever do make it part of the API, we might want to rename it to something
459      * less funny like runUnsafe().
460      */
runWithScissors(final Runnable r, long timeout)461     public final boolean runWithScissors(final Runnable r, long timeout) {
462         if (r == null) {
463             throw new IllegalArgumentException("runnable must not be null");
464         }
465         if (timeout < 0) {
466             throw new IllegalArgumentException("timeout must be non-negative");
467         }
468 
469         if (Looper.myLooper() == mLooper) {
470             r.run();
471             return true;
472         }
473 
474         BlockingRunnable br = new BlockingRunnable(r);
475         return br.postAndWait(this, timeout);
476     }
477 
478     /**
479      * Remove any pending posts of Runnable r that are in the message queue.
480      */
removeCallbacks(Runnable r)481     public final void removeCallbacks(Runnable r)
482     {
483         mQueue.removeMessages(this, r, null);
484     }
485 
486     /**
487      * Remove any pending posts of Runnable <var>r</var> with Object
488      * <var>token</var> that are in the message queue.  If <var>token</var> is null,
489      * all callbacks will be removed.
490      */
removeCallbacks(Runnable r, Object token)491     public final void removeCallbacks(Runnable r, Object token)
492     {
493         mQueue.removeMessages(this, r, token);
494     }
495 
496     /**
497      * Pushes a message onto the end of the message queue after all pending messages
498      * before the current time. It will be received in {@link #handleMessage},
499      * in the thread attached to this handler.
500      *
501      * @return Returns true if the message was successfully placed in to the
502      *         message queue.  Returns false on failure, usually because the
503      *         looper processing the message queue is exiting.
504      */
sendMessage(Message msg)505     public final boolean sendMessage(Message msg)
506     {
507         return sendMessageDelayed(msg, 0);
508     }
509 
510     /**
511      * Sends a Message containing only the what value.
512      *
513      * @return Returns true if the message was successfully placed in to the
514      *         message queue.  Returns false on failure, usually because the
515      *         looper processing the message queue is exiting.
516      */
sendEmptyMessage(int what)517     public final boolean sendEmptyMessage(int what)
518     {
519         return sendEmptyMessageDelayed(what, 0);
520     }
521 
522     /**
523      * Sends a Message containing only the what value, to be delivered
524      * after the specified amount of time elapses.
525      * @see #sendMessageDelayed(android.os.Message, long)
526      *
527      * @return Returns true if the message was successfully placed in to the
528      *         message queue.  Returns false on failure, usually because the
529      *         looper processing the message queue is exiting.
530      */
sendEmptyMessageDelayed(int what, long delayMillis)531     public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
532         Message msg = Message.obtain();
533         msg.what = what;
534         return sendMessageDelayed(msg, delayMillis);
535     }
536 
537     /**
538      * Sends a Message containing only the what value, to be delivered
539      * at a specific time.
540      * @see #sendMessageAtTime(android.os.Message, long)
541      *
542      * @return Returns true if the message was successfully placed in to the
543      *         message queue.  Returns false on failure, usually because the
544      *         looper processing the message queue is exiting.
545      */
546 
sendEmptyMessageAtTime(int what, long uptimeMillis)547     public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
548         Message msg = Message.obtain();
549         msg.what = what;
550         return sendMessageAtTime(msg, uptimeMillis);
551     }
552 
553     /**
554      * Enqueue a message into the message queue after all pending messages
555      * before (current time + delayMillis). You will receive it in
556      * {@link #handleMessage}, in the thread attached to this handler.
557      *
558      * @return Returns true if the message was successfully placed in to the
559      *         message queue.  Returns false on failure, usually because the
560      *         looper processing the message queue is exiting.  Note that a
561      *         result of true does not mean the message will be processed -- if
562      *         the looper is quit before the delivery time of the message
563      *         occurs then the message will be dropped.
564      */
sendMessageDelayed(Message msg, long delayMillis)565     public final boolean sendMessageDelayed(Message msg, long delayMillis)
566     {
567         if (delayMillis < 0) {
568             delayMillis = 0;
569         }
570         return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
571     }
572 
573     /**
574      * Enqueue a message into the message queue after all pending messages
575      * before the absolute time (in milliseconds) <var>uptimeMillis</var>.
576      * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
577      * Time spent in deep sleep will add an additional delay to execution.
578      * You will receive it in {@link #handleMessage}, in the thread attached
579      * to this handler.
580      *
581      * @param uptimeMillis The absolute time at which the message should be
582      *         delivered, using the
583      *         {@link android.os.SystemClock#uptimeMillis} time-base.
584      *
585      * @return Returns true if the message was successfully placed in to the
586      *         message queue.  Returns false on failure, usually because the
587      *         looper processing the message queue is exiting.  Note that a
588      *         result of true does not mean the message will be processed -- if
589      *         the looper is quit before the delivery time of the message
590      *         occurs then the message will be dropped.
591      */
sendMessageAtTime(Message msg, long uptimeMillis)592     public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
593         MessageQueue queue = mQueue;
594         if (queue == null) {
595             RuntimeException e = new RuntimeException(
596                     this + " sendMessageAtTime() called with no mQueue");
597             Log.w("Looper", e.getMessage(), e);
598             return false;
599         }
600         return enqueueMessage(queue, msg, uptimeMillis);
601     }
602 
603     /**
604      * Enqueue a message at the front of the message queue, to be processed on
605      * the next iteration of the message loop.  You will receive it in
606      * {@link #handleMessage}, in the thread attached to this handler.
607      * <b>This method is only for use in very special circumstances -- it
608      * can easily starve the message queue, cause ordering problems, or have
609      * other unexpected side-effects.</b>
610      *
611      * @return Returns true if the message was successfully placed in to the
612      *         message queue.  Returns false on failure, usually because the
613      *         looper processing the message queue is exiting.
614      */
sendMessageAtFrontOfQueue(Message msg)615     public final boolean sendMessageAtFrontOfQueue(Message msg) {
616         MessageQueue queue = mQueue;
617         if (queue == null) {
618             RuntimeException e = new RuntimeException(
619                 this + " sendMessageAtTime() called with no mQueue");
620             Log.w("Looper", e.getMessage(), e);
621             return false;
622         }
623         return enqueueMessage(queue, msg, 0);
624     }
625 
enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)626     private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
627         msg.target = this;
628         if (mAsynchronous) {
629             msg.setAsynchronous(true);
630         }
631         return queue.enqueueMessage(msg, uptimeMillis);
632     }
633 
634     /**
635      * Remove any pending posts of messages with code 'what' that are in the
636      * message queue.
637      */
removeMessages(int what)638     public final void removeMessages(int what) {
639         mQueue.removeMessages(this, what, null);
640     }
641 
642     /**
643      * Remove any pending posts of messages with code 'what' and whose obj is
644      * 'object' that are in the message queue.  If <var>object</var> is null,
645      * all messages will be removed.
646      */
removeMessages(int what, Object object)647     public final void removeMessages(int what, Object object) {
648         mQueue.removeMessages(this, what, object);
649     }
650 
651     /**
652      * Remove any pending posts of callbacks and sent messages whose
653      * <var>obj</var> is <var>token</var>.  If <var>token</var> is null,
654      * all callbacks and messages will be removed.
655      */
removeCallbacksAndMessages(Object token)656     public final void removeCallbacksAndMessages(Object token) {
657         mQueue.removeCallbacksAndMessages(this, token);
658     }
659 
660     /**
661      * Check if there are any pending posts of messages with code 'what' in
662      * the message queue.
663      */
hasMessages(int what)664     public final boolean hasMessages(int what) {
665         return mQueue.hasMessages(this, what, null);
666     }
667 
668     /**
669      * Check if there are any pending posts of messages with code 'what' and
670      * whose obj is 'object' in the message queue.
671      */
hasMessages(int what, Object object)672     public final boolean hasMessages(int what, Object object) {
673         return mQueue.hasMessages(this, what, object);
674     }
675 
676     /**
677      * Check if there are any pending posts of messages with callback r in
678      * the message queue.
679      *
680      * @hide
681      */
hasCallbacks(Runnable r)682     public final boolean hasCallbacks(Runnable r) {
683         return mQueue.hasMessages(this, r, null);
684     }
685 
686     // if we can get rid of this method, the handler need not remember its loop
687     // we could instead export a getMessageQueue() method...
getLooper()688     public final Looper getLooper() {
689         return mLooper;
690     }
691 
dump(Printer pw, String prefix)692     public final void dump(Printer pw, String prefix) {
693         pw.println(prefix + this + " @ " + SystemClock.uptimeMillis());
694         if (mLooper == null) {
695             pw.println(prefix + "looper uninitialized");
696         } else {
697             mLooper.dump(pw, prefix + "  ");
698         }
699     }
700 
701     @Override
toString()702     public String toString() {
703         return "Handler (" + getClass().getName() + ") {"
704         + Integer.toHexString(System.identityHashCode(this))
705         + "}";
706     }
707 
getIMessenger()708     final IMessenger getIMessenger() {
709         synchronized (mQueue) {
710             if (mMessenger != null) {
711                 return mMessenger;
712             }
713             mMessenger = new MessengerImpl();
714             return mMessenger;
715         }
716     }
717 
718     private final class MessengerImpl extends IMessenger.Stub {
send(Message msg)719         public void send(Message msg) {
720             msg.sendingUid = Binder.getCallingUid();
721             Handler.this.sendMessage(msg);
722         }
723     }
724 
getPostMessage(Runnable r)725     private static Message getPostMessage(Runnable r) {
726         Message m = Message.obtain();
727         m.callback = r;
728         return m;
729     }
730 
getPostMessage(Runnable r, Object token)731     private static Message getPostMessage(Runnable r, Object token) {
732         Message m = Message.obtain();
733         m.obj = token;
734         m.callback = r;
735         return m;
736     }
737 
handleCallback(Message message)738     private static void handleCallback(Message message) {
739         message.callback.run();
740     }
741 
742     final MessageQueue mQueue;
743     final Looper mLooper;
744     final Callback mCallback;
745     final boolean mAsynchronous;
746     IMessenger mMessenger;
747 
748     private static final class BlockingRunnable implements Runnable {
749         private final Runnable mTask;
750         private boolean mDone;
751 
BlockingRunnable(Runnable task)752         public BlockingRunnable(Runnable task) {
753             mTask = task;
754         }
755 
756         @Override
run()757         public void run() {
758             try {
759                 mTask.run();
760             } finally {
761                 synchronized (this) {
762                     mDone = true;
763                     notifyAll();
764                 }
765             }
766         }
767 
postAndWait(Handler handler, long timeout)768         public boolean postAndWait(Handler handler, long timeout) {
769             if (!handler.post(this)) {
770                 return false;
771             }
772 
773             synchronized (this) {
774                 if (timeout > 0) {
775                     final long expirationTime = SystemClock.uptimeMillis() + timeout;
776                     while (!mDone) {
777                         long delay = expirationTime - SystemClock.uptimeMillis();
778                         if (delay <= 0) {
779                             return false; // timeout
780                         }
781                         try {
782                             wait(delay);
783                         } catch (InterruptedException ex) {
784                         }
785                     }
786                 } else {
787                     while (!mDone) {
788                         try {
789                             wait();
790                         } catch (InterruptedException ex) {
791                         }
792                     }
793                 }
794             }
795             return true;
796         }
797     }
798 }
799