Handler.java revision 8b60e4514702edd1eb4b6f2bfc027e04a94369c0
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.util.Log;
20import android.util.Printer;
21
22import 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 */
64public 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 {
78        public boolean handleMessage(Message msg);
79    }
80
81    /**
82     * Subclasses must implement this to receive messages.
83     */
84    public void handleMessage(Message msg) {
85    }
86
87    /**
88     * Handle system messages here.
89     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
409    public final boolean postAtFrontOfQueue(Runnable r)
410    {
411        return sendMessageAtFrontOfQueue(getPostMessage(r));
412    }
413
414    /**
415     * Runs the specified task synchronously.
416     * <p>
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     * </p><p>
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     * </p><p>
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     * </p><p>
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     * </p><p>
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     * </p><p>
438     * When using this method, be sure to use {@link Looper#quitSafely} when
439     * quitting the looper.  Otherwise {@link #runWithScissors} may hang indefinitely.
440     * (TODO: We should fix this by making MessageQueue aware of blocking runnables.)
441     * </p>
442     *
443     * @param r The Runnable that will be executed synchronously.
444     * @param timeout The timeout in milliseconds, or 0 to wait indefinitely.
445     *
446     * @return Returns true if the Runnable was successfully executed.
447     *         Returns false on failure, usually because the
448     *         looper processing the message queue is exiting.
449     *
450     * @hide This method is prone to abuse and should probably not be in the API.
451     * If we ever do make it part of the API, we might want to rename it to something
452     * less funny like runUnsafe().
453     */
454    public final boolean runWithScissors(final Runnable r, long timeout) {
455        if (r == null) {
456            throw new IllegalArgumentException("runnable must not be null");
457        }
458        if (timeout < 0) {
459            throw new IllegalArgumentException("timeout must be non-negative");
460        }
461
462        if (Looper.myLooper() == mLooper) {
463            r.run();
464            return true;
465        }
466
467        BlockingRunnable br = new BlockingRunnable(r);
468        return br.postAndWait(this, timeout);
469    }
470
471    /**
472     * Remove any pending posts of Runnable r that are in the message queue.
473     */
474    public final void removeCallbacks(Runnable r)
475    {
476        mQueue.removeMessages(this, r, null);
477    }
478
479    /**
480     * Remove any pending posts of Runnable <var>r</var> with Object
481     * <var>token</var> that are in the message queue.  If <var>token</var> is null,
482     * all callbacks will be removed.
483     */
484    public final void removeCallbacks(Runnable r, Object token)
485    {
486        mQueue.removeMessages(this, r, token);
487    }
488
489    /**
490     * Pushes a message onto the end of the message queue after all pending messages
491     * before the current time. It will be received in {@link #handleMessage},
492     * in the thread attached to this handler.
493     *
494     * @return Returns true if the message was successfully placed in to the
495     *         message queue.  Returns false on failure, usually because the
496     *         looper processing the message queue is exiting.
497     */
498    public final boolean sendMessage(Message msg)
499    {
500        return sendMessageDelayed(msg, 0);
501    }
502
503    /**
504     * Sends a Message containing only the what value.
505     *
506     * @return Returns true if the message was successfully placed in to the
507     *         message queue.  Returns false on failure, usually because the
508     *         looper processing the message queue is exiting.
509     */
510    public final boolean sendEmptyMessage(int what)
511    {
512        return sendEmptyMessageDelayed(what, 0);
513    }
514
515    /**
516     * Sends a Message containing only the what value, to be delivered
517     * after the specified amount of time elapses.
518     * @see #sendMessageDelayed(android.os.Message, long)
519     *
520     * @return Returns true if the message was successfully placed in to the
521     *         message queue.  Returns false on failure, usually because the
522     *         looper processing the message queue is exiting.
523     */
524    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
525        Message msg = Message.obtain();
526        msg.what = what;
527        return sendMessageDelayed(msg, delayMillis);
528    }
529
530    /**
531     * Sends a Message containing only the what value, to be delivered
532     * at a specific time.
533     * @see #sendMessageAtTime(android.os.Message, long)
534     *
535     * @return Returns true if the message was successfully placed in to the
536     *         message queue.  Returns false on failure, usually because the
537     *         looper processing the message queue is exiting.
538     */
539
540    public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
541        Message msg = Message.obtain();
542        msg.what = what;
543        return sendMessageAtTime(msg, uptimeMillis);
544    }
545
546    /**
547     * Enqueue a message into the message queue after all pending messages
548     * before (current time + delayMillis). You will receive it in
549     * {@link #handleMessage}, in the thread attached to this handler.
550     *
551     * @return Returns true if the message was successfully placed in to the
552     *         message queue.  Returns false on failure, usually because the
553     *         looper processing the message queue is exiting.  Note that a
554     *         result of true does not mean the message will be processed -- if
555     *         the looper is quit before the delivery time of the message
556     *         occurs then the message will be dropped.
557     */
558    public final boolean sendMessageDelayed(Message msg, long delayMillis)
559    {
560        if (delayMillis < 0) {
561            delayMillis = 0;
562        }
563        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
564    }
565
566    /**
567     * Enqueue a message into the message queue after all pending messages
568     * before the absolute time (in milliseconds) <var>uptimeMillis</var>.
569     * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
570     * You will receive it in {@link #handleMessage}, in the thread attached
571     * to this handler.
572     *
573     * @param uptimeMillis The absolute time at which the message should be
574     *         delivered, using the
575     *         {@link android.os.SystemClock#uptimeMillis} time-base.
576     *
577     * @return Returns true if the message was successfully placed in to the
578     *         message queue.  Returns false on failure, usually because the
579     *         looper processing the message queue is exiting.  Note that a
580     *         result of true does not mean the message will be processed -- if
581     *         the looper is quit before the delivery time of the message
582     *         occurs then the message will be dropped.
583     */
584    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
585        MessageQueue queue = mQueue;
586        if (queue == null) {
587            RuntimeException e = new RuntimeException(
588                    this + " sendMessageAtTime() called with no mQueue");
589            Log.w("Looper", e.getMessage(), e);
590            return false;
591        }
592        return enqueueMessage(queue, msg, uptimeMillis);
593    }
594
595    /**
596     * Enqueue a message at the front of the message queue, to be processed on
597     * the next iteration of the message loop.  You will receive it in
598     * {@link #handleMessage}, in the thread attached to this handler.
599     * <b>This method is only for use in very special circumstances -- it
600     * can easily starve the message queue, cause ordering problems, or have
601     * other unexpected side-effects.</b>
602     *
603     * @return Returns true if the message was successfully placed in to the
604     *         message queue.  Returns false on failure, usually because the
605     *         looper processing the message queue is exiting.
606     */
607    public final boolean sendMessageAtFrontOfQueue(Message msg) {
608        MessageQueue queue = mQueue;
609        if (queue == null) {
610            RuntimeException e = new RuntimeException(
611                this + " sendMessageAtTime() called with no mQueue");
612            Log.w("Looper", e.getMessage(), e);
613            return false;
614        }
615        return enqueueMessage(queue, msg, 0);
616    }
617
618    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
619        msg.target = this;
620        if (mAsynchronous) {
621            msg.setAsynchronous(true);
622        }
623        return queue.enqueueMessage(msg, uptimeMillis);
624    }
625
626    /**
627     * Remove any pending posts of messages with code 'what' that are in the
628     * message queue.
629     */
630    public final void removeMessages(int what) {
631        mQueue.removeMessages(this, what, null);
632    }
633
634    /**
635     * Remove any pending posts of messages with code 'what' and whose obj is
636     * 'object' that are in the message queue.  If <var>object</var> is null,
637     * all messages will be removed.
638     */
639    public final void removeMessages(int what, Object object) {
640        mQueue.removeMessages(this, what, object);
641    }
642
643    /**
644     * Remove any pending posts of callbacks and sent messages whose
645     * <var>obj</var> is <var>token</var>.  If <var>token</var> is null,
646     * all callbacks and messages will be removed.
647     */
648    public final void removeCallbacksAndMessages(Object token) {
649        mQueue.removeCallbacksAndMessages(this, token);
650    }
651
652    /**
653     * Check if there are any pending posts of messages with code 'what' in
654     * the message queue.
655     */
656    public final boolean hasMessages(int what) {
657        return mQueue.hasMessages(this, what, null);
658    }
659
660    /**
661     * Check if there are any pending posts of messages with code 'what' and
662     * whose obj is 'object' in the message queue.
663     */
664    public final boolean hasMessages(int what, Object object) {
665        return mQueue.hasMessages(this, what, object);
666    }
667
668    /**
669     * Check if there are any pending posts of messages with callback r in
670     * the message queue.
671     *
672     * @hide
673     */
674    public final boolean hasCallbacks(Runnable r) {
675        return mQueue.hasMessages(this, r, null);
676    }
677
678    // if we can get rid of this method, the handler need not remember its loop
679    // we could instead export a getMessageQueue() method...
680    public final Looper getLooper() {
681        return mLooper;
682    }
683
684    public final void dump(Printer pw, String prefix) {
685        pw.println(prefix + this + " @ " + SystemClock.uptimeMillis());
686        if (mLooper == null) {
687            pw.println(prefix + "looper uninitialized");
688        } else {
689            mLooper.dump(pw, prefix + "  ");
690        }
691    }
692
693    @Override
694    public String toString() {
695        return "Handler (" + getClass().getName() + ") {"
696        + Integer.toHexString(System.identityHashCode(this))
697        + "}";
698    }
699
700    final IMessenger getIMessenger() {
701        synchronized (mQueue) {
702            if (mMessenger != null) {
703                return mMessenger;
704            }
705            mMessenger = new MessengerImpl();
706            return mMessenger;
707        }
708    }
709
710    private final class MessengerImpl extends IMessenger.Stub {
711        public void send(Message msg) {
712            Handler.this.sendMessage(msg);
713        }
714    }
715
716    private static Message getPostMessage(Runnable r) {
717        Message m = Message.obtain();
718        m.callback = r;
719        return m;
720    }
721
722    private static Message getPostMessage(Runnable r, Object token) {
723        Message m = Message.obtain();
724        m.obj = token;
725        m.callback = r;
726        return m;
727    }
728
729    private static void handleCallback(Message message) {
730        message.callback.run();
731    }
732
733    final MessageQueue mQueue;
734    final Looper mLooper;
735    final Callback mCallback;
736    final boolean mAsynchronous;
737    IMessenger mMessenger;
738
739    private static final class BlockingRunnable implements Runnable {
740        private final Runnable mTask;
741        private boolean mDone;
742
743        public BlockingRunnable(Runnable task) {
744            mTask = task;
745        }
746
747        @Override
748        public void run() {
749            try {
750                mTask.run();
751            } finally {
752                synchronized (this) {
753                    mDone = true;
754                    notifyAll();
755                }
756            }
757        }
758
759        public boolean postAndWait(Handler handler, long timeout) {
760            if (!handler.post(this)) {
761                return false;
762            }
763
764            synchronized (this) {
765                if (timeout > 0) {
766                    final long expirationTime = SystemClock.uptimeMillis() + timeout;
767                    while (!mDone) {
768                        long delay = expirationTime - SystemClock.uptimeMillis();
769                        if (delay <= 0) {
770                            return false; // timeout
771                        }
772                        try {
773                            wait(delay);
774                        } catch (InterruptedException ex) {
775                        }
776                    }
777                } else {
778                    while (!mDone) {
779                        try {
780                            wait();
781                        } catch (InterruptedException ex) {
782                        }
783                    }
784                }
785            }
786            return true;
787        }
788    }
789}
790