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