blob: 14d8f0765f9d80fbc85385f7bda7d93003e29d58 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Chris Palmer42855142010-09-09 17:04:31 -070061 * your new thread. The given Runnable or Message will then be scheduled
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 * 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 /**
Jeff Browna2910d02012-08-25 12:29:46 -0700104 * Default constructor associates this handler with the {@link Looper} for the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 * current thread.
106 *
Jeff Browna2910d02012-08-25 12:29:46 -0700107 * If this thread does not have a looper, this handler won't be able to receive messages
108 * so an exception is thrown.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 */
110 public Handler() {
Jeff Browna2910d02012-08-25 12:29:46 -0700111 this(null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 }
113
114 /**
Jeff Browna2910d02012-08-25 12:29:46 -0700115 * Constructor associates this handler with the {@link Looper} for the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 * current thread and takes a callback interface in which you can handle
117 * messages.
Jeff Browna2910d02012-08-25 12:29:46 -0700118 *
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.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 */
124 public Handler(Callback callback) {
Jeff Browna2910d02012-08-25 12:29:46 -0700125 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) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 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;
Jeff Browna2910d02012-08-25 12:29:46 -0700202 mAsynchronous = async;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 }
204
205 /**
Jeff Browna2910d02012-08-25 12:29:46 -0700206 * Use the provided {@link Looper} instead of the default one and take a callback
Jeff Brown109025d2012-08-14 20:41:30 -0700207 * 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 *
Jeff Browna2910d02012-08-25 12:29:46 -0700217 * @param looper The looper, must not be null.
218 * @param callback The callback interface in which to handle messages, or null.
Jeff Brown109025d2012-08-14 20:41:30 -0700219 * @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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 }
230
231 /**
Romain Guyf9284692011-07-13 18:46:21 -0700232 * 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 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 * 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 /**
Jeff Brownc53abc42012-08-29 04:43:25 -0700415 * Runs the specified task synchronously.
Jeff Brown8b60e452013-04-18 15:17:48 -0700416 * <p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700417 * 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.
Jeff Brown8b60e452013-04-18 15:17:48 -0700420 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700421 * 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.
Jeff Brown8b60e452013-04-18 15:17:48 -0700424 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700425 * 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.
Jeff Brown8b60e452013-04-18 15:17:48 -0700429 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700430 * 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.
Jeff Brown8b60e452013-04-18 15:17:48 -0700433 * </p><p>
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700434 * 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.
Jeff Brown8b60e452013-04-18 15:17:48 -0700437 * </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>
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700442 *
Jeff Brownc53abc42012-08-29 04:43:25 -0700443 * @param r The Runnable that will be executed synchronously.
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700444 * @param timeout The timeout in milliseconds, or 0 to wait indefinitely.
Jeff Brownc53abc42012-08-29 04:43:25 -0700445 *
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 */
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700454 public final boolean runWithScissors(final Runnable r, long timeout) {
Jeff Brownc53abc42012-08-29 04:43:25 -0700455 if (r == null) {
456 throw new IllegalArgumentException("runnable must not be null");
457 }
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700458 if (timeout < 0) {
459 throw new IllegalArgumentException("timeout must be non-negative");
460 }
Jeff Brownc53abc42012-08-29 04:43:25 -0700461
462 if (Looper.myLooper() == mLooper) {
463 r.run();
464 return true;
465 }
466
467 BlockingRunnable br = new BlockingRunnable(r);
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700468 return br.postAndWait(this, timeout);
Jeff Brownc53abc42012-08-29 04:43:25 -0700469 }
470
471 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 * 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
Dianne Hackborn466ed242011-07-21 18:16:31 -0700481 * <var>token</var> that are in the message queue. If <var>token</var> is null,
482 * all callbacks will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 */
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 */
Jeff Brown109025d2012-08-14 20:41:30 -0700584 public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 MessageQueue queue = mQueue;
Jeff Brown109025d2012-08-14 20:41:30 -0700586 if (queue == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 RuntimeException e = new RuntimeException(
Jeff Brown109025d2012-08-14 20:41:30 -0700588 this + " sendMessageAtTime() called with no mQueue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 Log.w("Looper", e.getMessage(), e);
Jeff Brown109025d2012-08-14 20:41:30 -0700590 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 }
Jeff Brown109025d2012-08-14 20:41:30 -0700592 return enqueueMessage(queue, msg, uptimeMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 }
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 */
Jeff Brown109025d2012-08-14 20:41:30 -0700607 public final boolean sendMessageAtFrontOfQueue(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 MessageQueue queue = mQueue;
Jeff Brown109025d2012-08-14 20:41:30 -0700609 if (queue == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 RuntimeException e = new RuntimeException(
611 this + " sendMessageAtTime() called with no mQueue");
612 Log.w("Looper", e.getMessage(), e);
Jeff Brown109025d2012-08-14 20:41:30 -0700613 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 }
Jeff Brown109025d2012-08-14 20:41:30 -0700615 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);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 }
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) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800631 mQueue.removeMessages(this, what, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 }
633
634 /**
635 * Remove any pending posts of messages with code 'what' and whose obj is
Jeff Brown32c81132012-04-30 16:28:32 -0700636 * 'object' that are in the message queue. If <var>object</var> is null,
Dianne Hackborn466ed242011-07-21 18:16:31 -0700637 * all messages will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 */
639 public final void removeMessages(int what, Object object) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800640 mQueue.removeMessages(this, what, object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 }
642
643 /**
644 * Remove any pending posts of callbacks and sent messages whose
Dianne Hackborn466ed242011-07-21 18:16:31 -0700645 * <var>obj</var> is <var>token</var>. If <var>token</var> is null,
646 * all callbacks and messages will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 */
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) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800657 return mQueue.hasMessages(this, what, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 }
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) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800665 return mQueue.hasMessages(this, what, object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 }
667
Romain Guyba6be8a2012-04-23 18:22:09 -0700668 /**
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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 // 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() {
Kristian Monsen588d8562011-08-04 12:55:33 +0100695 return "Handler (" + getClass().getName() + ") {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 + 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 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 private final class MessengerImpl extends IMessenger.Stub {
711 public void send(Message msg) {
712 Handler.this.sendMessage(msg);
713 }
714 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700715
Romain Guyba6be8a2012-04-23 18:22:09 -0700716 private static Message getPostMessage(Runnable r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 Message m = Message.obtain();
718 m.callback = r;
719 return m;
720 }
721
Romain Guyba6be8a2012-04-23 18:22:09 -0700722 private static Message getPostMessage(Runnable r, Object token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 Message m = Message.obtain();
724 m.obj = token;
725 m.callback = r;
726 return m;
727 }
728
Romain Guyba6be8a2012-04-23 18:22:09 -0700729 private static void handleCallback(Message message) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 message.callback.run();
731 }
732
733 final MessageQueue mQueue;
734 final Looper mLooper;
735 final Callback mCallback;
Jeff Brown109025d2012-08-14 20:41:30 -0700736 final boolean mAsynchronous;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 IMessenger mMessenger;
Jeff Brownc53abc42012-08-29 04:43:25 -0700738
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
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700759 public boolean postAndWait(Handler handler, long timeout) {
Jeff Brownc53abc42012-08-29 04:43:25 -0700760 if (!handler.post(this)) {
761 return false;
762 }
763
764 synchronized (this) {
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700765 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 }
Jeff Brownc53abc42012-08-29 04:43:25 -0700783 }
784 }
785 }
786 return true;
787 }
788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789}