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