blob: e6886c4d337d719728a036e5ceb28910f02924b7 [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.
Kristian Monsen1d3b4092013-06-05 17:06:32 -070076 *
77 * @param msg A {@link android.os.Message Message} object
78 * @return True if no further handling is desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079 */
80 public interface Callback {
81 public boolean handleMessage(Message msg);
82 }
83
84 /**
85 * Subclasses must implement this to receive messages.
86 */
87 public void handleMessage(Message msg) {
88 }
89
90 /**
91 * Handle system messages here.
92 */
93 public void dispatchMessage(Message msg) {
94 if (msg.callback != null) {
95 handleCallback(msg);
96 } else {
97 if (mCallback != null) {
98 if (mCallback.handleMessage(msg)) {
99 return;
100 }
101 }
102 handleMessage(msg);
103 }
104 }
105
106 /**
Jeff Browna2910d02012-08-25 12:29:46 -0700107 * Default constructor associates this handler with the {@link Looper} for the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 * current thread.
109 *
Jeff Browna2910d02012-08-25 12:29:46 -0700110 * If this thread does not have a looper, this handler won't be able to receive messages
111 * so an exception is thrown.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 */
113 public Handler() {
Jeff Browna2910d02012-08-25 12:29:46 -0700114 this(null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 }
116
117 /**
Jeff Browna2910d02012-08-25 12:29:46 -0700118 * Constructor associates this handler with the {@link Looper} for the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 * current thread and takes a callback interface in which you can handle
120 * messages.
Jeff Browna2910d02012-08-25 12:29:46 -0700121 *
122 * If this thread does not have a looper, this handler won't be able to receive messages
123 * so an exception is thrown.
124 *
125 * @param callback The callback interface in which to handle messages, or null.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 */
127 public Handler(Callback callback) {
Jeff Browna2910d02012-08-25 12:29:46 -0700128 this(callback, false);
129 }
130
131 /**
132 * Use the provided {@link Looper} instead of the default one.
133 *
134 * @param looper The looper, must not be null.
135 */
136 public Handler(Looper looper) {
137 this(looper, null, false);
138 }
139
140 /**
141 * Use the provided {@link Looper} instead of the default one and take a callback
142 * interface in which to handle messages.
143 *
144 * @param looper The looper, must not be null.
145 * @param callback The callback interface in which to handle messages, or null.
146 */
147 public Handler(Looper looper, Callback callback) {
148 this(looper, callback, false);
149 }
150
151 /**
152 * Use the {@link Looper} for the current thread
153 * and set whether the handler should be asynchronous.
154 *
155 * Handlers are synchronous by default unless this constructor is used to make
156 * one that is strictly asynchronous.
157 *
158 * Asynchronous messages represent interrupts or events that do not require global ordering
159 * with represent to synchronous messages. Asynchronous messages are not subject to
160 * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
161 *
162 * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
163 * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
164 *
165 * @hide
166 */
167 public Handler(boolean async) {
168 this(null, async);
169 }
170
171 /**
172 * Use the {@link Looper} for the current thread with the specified callback interface
173 * and set whether the handler should be asynchronous.
174 *
175 * Handlers are synchronous by default unless this constructor is used to make
176 * one that is strictly asynchronous.
177 *
178 * Asynchronous messages represent interrupts or events that do not require global ordering
179 * with represent to synchronous messages. Asynchronous messages are not subject to
180 * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
181 *
182 * @param callback The callback interface in which to handle messages, or null.
183 * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
184 * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
185 *
186 * @hide
187 */
188 public Handler(Callback callback, boolean async) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 if (FIND_POTENTIAL_LEAKS) {
190 final Class<? extends Handler> klass = getClass();
191 if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
192 (klass.getModifiers() & Modifier.STATIC) == 0) {
193 Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
194 klass.getCanonicalName());
195 }
196 }
197
198 mLooper = Looper.myLooper();
199 if (mLooper == null) {
200 throw new RuntimeException(
201 "Can't create handler inside thread that has not called Looper.prepare()");
202 }
203 mQueue = mLooper.mQueue;
204 mCallback = callback;
Jeff Browna2910d02012-08-25 12:29:46 -0700205 mAsynchronous = async;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 }
207
208 /**
Jeff Browna2910d02012-08-25 12:29:46 -0700209 * Use the provided {@link Looper} instead of the default one and take a callback
Jeff Brown109025d2012-08-14 20:41:30 -0700210 * interface in which to handle messages. Also set whether the handler
211 * should be asynchronous.
212 *
213 * Handlers are synchronous by default unless this constructor is used to make
214 * one that is strictly asynchronous.
215 *
216 * Asynchronous messages represent interrupts or events that do not require global ordering
217 * with represent to synchronous messages. Asynchronous messages are not subject to
218 * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
219 *
Jeff Browna2910d02012-08-25 12:29:46 -0700220 * @param looper The looper, must not be null.
221 * @param callback The callback interface in which to handle messages, or null.
Jeff Brown109025d2012-08-14 20:41:30 -0700222 * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
223 * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
224 *
225 * @hide
226 */
227 public Handler(Looper looper, Callback callback, boolean async) {
228 mLooper = looper;
229 mQueue = looper.mQueue;
230 mCallback = callback;
231 mAsynchronous = async;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 }
233
234 /**
Romain Guyf9284692011-07-13 18:46:21 -0700235 * Returns a string representing the name of the specified message.
236 * The default implementation will either return the class name of the
237 * message callback if any, or the hexadecimal representation of the
238 * message "what" field.
239 *
240 * @param message The message whose name is being queried
241 */
242 public String getMessageName(Message message) {
243 if (message.callback != null) {
244 return message.callback.getClass().getName();
245 }
246 return "0x" + Integer.toHexString(message.what);
247 }
248
249 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 * Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
251 * creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
252 * If you don't want that facility, just call Message.obtain() instead.
253 */
254 public final Message obtainMessage()
255 {
256 return Message.obtain(this);
257 }
258
259 /**
260 * Same as {@link #obtainMessage()}, except that it also sets the what member of the returned Message.
261 *
262 * @param what Value to assign to the returned Message.what field.
263 * @return A Message from the global message pool.
264 */
265 public final Message obtainMessage(int what)
266 {
267 return Message.obtain(this, what);
268 }
269
270 /**
271 *
272 * Same as {@link #obtainMessage()}, except that it also sets the what and obj members
273 * of the returned Message.
274 *
275 * @param what Value to assign to the returned Message.what field.
276 * @param obj Value to assign to the returned Message.obj field.
277 * @return A Message from the global message pool.
278 */
279 public final Message obtainMessage(int what, Object obj)
280 {
281 return Message.obtain(this, what, obj);
282 }
283
284 /**
285 *
286 * Same as {@link #obtainMessage()}, except that it also sets the what, arg1 and arg2 members of the returned
287 * Message.
288 * @param what Value to assign to the returned Message.what field.
289 * @param arg1 Value to assign to the returned Message.arg1 field.
290 * @param arg2 Value to assign to the returned Message.arg2 field.
291 * @return A Message from the global message pool.
292 */
293 public final Message obtainMessage(int what, int arg1, int arg2)
294 {
295 return Message.obtain(this, what, arg1, arg2);
296 }
297
298 /**
299 *
300 * Same as {@link #obtainMessage()}, except that it also sets the what, obj, arg1,and arg2 values on the
301 * returned Message.
302 * @param what Value to assign to the returned Message.what field.
303 * @param arg1 Value to assign to the returned Message.arg1 field.
304 * @param arg2 Value to assign to the returned Message.arg2 field.
305 * @param obj Value to assign to the returned Message.obj field.
306 * @return A Message from the global message pool.
307 */
308 public final Message obtainMessage(int what, int arg1, int arg2, Object obj)
309 {
310 return Message.obtain(this, what, arg1, arg2, obj);
311 }
312
313 /**
314 * Causes the Runnable r to be added to the message queue.
315 * The runnable will be run on the thread to which this handler is
316 * attached.
317 *
318 * @param r The Runnable that will be executed.
319 *
320 * @return Returns true if the Runnable was successfully placed in to the
321 * message queue. Returns false on failure, usually because the
322 * looper processing the message queue is exiting.
323 */
324 public final boolean post(Runnable r)
325 {
326 return sendMessageDelayed(getPostMessage(r), 0);
327 }
328
329 /**
330 * Causes the Runnable r to be added to the message queue, to be run
331 * at a specific time given by <var>uptimeMillis</var>.
332 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
333 * The runnable will be run on the thread to which this handler is attached.
334 *
335 * @param r The Runnable that will be executed.
336 * @param uptimeMillis The absolute time at which the callback should run,
337 * using the {@link android.os.SystemClock#uptimeMillis} time-base.
338 *
339 * @return Returns true if the Runnable was successfully placed in to the
340 * message queue. Returns false on failure, usually because the
341 * looper processing the message queue is exiting. Note that a
342 * result of true does not mean the Runnable will be processed -- if
343 * the looper is quit before the delivery time of the message
344 * occurs then the message will be dropped.
345 */
346 public final boolean postAtTime(Runnable r, long uptimeMillis)
347 {
348 return sendMessageAtTime(getPostMessage(r), uptimeMillis);
349 }
350
351 /**
352 * Causes the Runnable r to be added to the message queue, to be run
353 * at a specific time given by <var>uptimeMillis</var>.
354 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
355 * The runnable will be run on the thread to which this handler is attached.
356 *
357 * @param r The Runnable that will be executed.
358 * @param uptimeMillis The absolute time at which the callback should run,
359 * using the {@link android.os.SystemClock#uptimeMillis} time-base.
360 *
361 * @return Returns true if the Runnable was successfully placed in to the
362 * message queue. Returns false on failure, usually because the
363 * looper processing the message queue is exiting. Note that a
364 * result of true does not mean the Runnable will be processed -- if
365 * the looper is quit before the delivery time of the message
366 * occurs then the message will be dropped.
367 *
368 * @see android.os.SystemClock#uptimeMillis
369 */
370 public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
371 {
372 return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
373 }
374
375 /**
376 * Causes the Runnable r to be added to the message queue, to be run
377 * after the specified amount of time elapses.
378 * The runnable will be run on the thread to which this handler
379 * is attached.
380 *
381 * @param r The Runnable that will be executed.
382 * @param delayMillis The delay (in milliseconds) until the Runnable
383 * will be executed.
384 *
385 * @return Returns true if the Runnable was successfully placed in to the
386 * message queue. Returns false on failure, usually because the
387 * looper processing the message queue is exiting. Note that a
388 * result of true does not mean the Runnable will be processed --
389 * if the looper is quit before the delivery time of the message
390 * occurs then the message will be dropped.
391 */
392 public final boolean postDelayed(Runnable r, long delayMillis)
393 {
394 return sendMessageDelayed(getPostMessage(r), delayMillis);
395 }
396
397 /**
398 * Posts a message to an object that implements Runnable.
399 * Causes the Runnable r to executed on the next iteration through the
400 * message queue. The runnable will be run on the thread to which this
401 * handler is attached.
402 * <b>This method is only for use in very special circumstances -- it
403 * can easily starve the message queue, cause ordering problems, or have
404 * other unexpected side-effects.</b>
405 *
406 * @param r The Runnable that will be executed.
407 *
408 * @return Returns true if the message was successfully placed in to the
409 * message queue. Returns false on failure, usually because the
410 * looper processing the message queue is exiting.
411 */
412 public final boolean postAtFrontOfQueue(Runnable r)
413 {
414 return sendMessageAtFrontOfQueue(getPostMessage(r));
415 }
416
417 /**
Jeff Brownc53abc42012-08-29 04:43:25 -0700418 * Runs the specified task synchronously.
Jeff Brown8b60e452013-04-18 15:17:48 -0700419 * <p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700420 * If the current thread is the same as the handler thread, then the runnable
421 * runs immediately without being enqueued. Otherwise, posts the runnable
422 * to the handler and waits for it to complete before returning.
Jeff Brown8b60e452013-04-18 15:17:48 -0700423 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700424 * This method is dangerous! Improper use can result in deadlocks.
425 * Never call this method while any locks are held or use it in a
426 * possibly re-entrant manner.
Jeff Brown8b60e452013-04-18 15:17:48 -0700427 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700428 * This method is occasionally useful in situations where a background thread
429 * must synchronously await completion of a task that must run on the
430 * handler's thread. However, this problem is often a symptom of bad design.
431 * Consider improving the design (if possible) before resorting to this method.
Jeff Brown8b60e452013-04-18 15:17:48 -0700432 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700433 * One example of where you might want to use this method is when you just
434 * set up a Handler thread and need to perform some initialization steps on
435 * it before continuing execution.
Jeff Brown8b60e452013-04-18 15:17:48 -0700436 * </p><p>
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700437 * If timeout occurs then this method returns <code>false</code> but the runnable
438 * will remain posted on the handler and may already be in progress or
439 * complete at a later time.
Jeff Brown8b60e452013-04-18 15:17:48 -0700440 * </p><p>
441 * When using this method, be sure to use {@link Looper#quitSafely} when
442 * quitting the looper. Otherwise {@link #runWithScissors} may hang indefinitely.
443 * (TODO: We should fix this by making MessageQueue aware of blocking runnables.)
444 * </p>
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700445 *
Jeff Brownc53abc42012-08-29 04:43:25 -0700446 * @param r The Runnable that will be executed synchronously.
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700447 * @param timeout The timeout in milliseconds, or 0 to wait indefinitely.
Jeff Brownc53abc42012-08-29 04:43:25 -0700448 *
449 * @return Returns true if the Runnable was successfully executed.
450 * Returns false on failure, usually because the
451 * looper processing the message queue is exiting.
452 *
453 * @hide This method is prone to abuse and should probably not be in the API.
454 * If we ever do make it part of the API, we might want to rename it to something
455 * less funny like runUnsafe().
456 */
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700457 public final boolean runWithScissors(final Runnable r, long timeout) {
Jeff Brownc53abc42012-08-29 04:43:25 -0700458 if (r == null) {
459 throw new IllegalArgumentException("runnable must not be null");
460 }
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700461 if (timeout < 0) {
462 throw new IllegalArgumentException("timeout must be non-negative");
463 }
Jeff Brownc53abc42012-08-29 04:43:25 -0700464
465 if (Looper.myLooper() == mLooper) {
466 r.run();
467 return true;
468 }
469
470 BlockingRunnable br = new BlockingRunnable(r);
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700471 return br.postAndWait(this, timeout);
Jeff Brownc53abc42012-08-29 04:43:25 -0700472 }
473
474 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 * Remove any pending posts of Runnable r that are in the message queue.
476 */
477 public final void removeCallbacks(Runnable r)
478 {
479 mQueue.removeMessages(this, r, null);
480 }
481
482 /**
483 * Remove any pending posts of Runnable <var>r</var> with Object
Dianne Hackborn466ed242011-07-21 18:16:31 -0700484 * <var>token</var> that are in the message queue. If <var>token</var> is null,
485 * all callbacks will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 */
487 public final void removeCallbacks(Runnable r, Object token)
488 {
489 mQueue.removeMessages(this, r, token);
490 }
491
492 /**
493 * Pushes a message onto the end of the message queue after all pending messages
494 * before the current time. It will be received in {@link #handleMessage},
495 * in the thread attached to this handler.
496 *
497 * @return Returns true if the message was successfully placed in to the
498 * message queue. Returns false on failure, usually because the
499 * looper processing the message queue is exiting.
500 */
501 public final boolean sendMessage(Message msg)
502 {
503 return sendMessageDelayed(msg, 0);
504 }
505
506 /**
507 * Sends a Message containing only the what value.
508 *
509 * @return Returns true if the message was successfully placed in to the
510 * message queue. Returns false on failure, usually because the
511 * looper processing the message queue is exiting.
512 */
513 public final boolean sendEmptyMessage(int what)
514 {
515 return sendEmptyMessageDelayed(what, 0);
516 }
517
518 /**
519 * Sends a Message containing only the what value, to be delivered
520 * after the specified amount of time elapses.
521 * @see #sendMessageDelayed(android.os.Message, long)
522 *
523 * @return Returns true if the message was successfully placed in to the
524 * message queue. Returns false on failure, usually because the
525 * looper processing the message queue is exiting.
526 */
527 public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
528 Message msg = Message.obtain();
529 msg.what = what;
530 return sendMessageDelayed(msg, delayMillis);
531 }
532
533 /**
534 * Sends a Message containing only the what value, to be delivered
535 * at a specific time.
536 * @see #sendMessageAtTime(android.os.Message, long)
537 *
538 * @return Returns true if the message was successfully placed in to the
539 * message queue. Returns false on failure, usually because the
540 * looper processing the message queue is exiting.
541 */
542
543 public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
544 Message msg = Message.obtain();
545 msg.what = what;
546 return sendMessageAtTime(msg, uptimeMillis);
547 }
548
549 /**
550 * Enqueue a message into the message queue after all pending messages
551 * before (current time + delayMillis). You will receive it in
552 * {@link #handleMessage}, in the thread attached to this handler.
553 *
554 * @return Returns true if the message was successfully placed in to the
555 * message queue. Returns false on failure, usually because the
556 * looper processing the message queue is exiting. Note that a
557 * result of true does not mean the message will be processed -- if
558 * the looper is quit before the delivery time of the message
559 * occurs then the message will be dropped.
560 */
561 public final boolean sendMessageDelayed(Message msg, long delayMillis)
562 {
563 if (delayMillis < 0) {
564 delayMillis = 0;
565 }
566 return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
567 }
568
569 /**
570 * Enqueue a message into the message queue after all pending messages
571 * before the absolute time (in milliseconds) <var>uptimeMillis</var>.
572 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
573 * You will receive it in {@link #handleMessage}, in the thread attached
574 * to this handler.
575 *
576 * @param uptimeMillis The absolute time at which the message should be
577 * delivered, using the
578 * {@link android.os.SystemClock#uptimeMillis} time-base.
579 *
580 * @return Returns true if the message was successfully placed in to the
581 * message queue. Returns false on failure, usually because the
582 * looper processing the message queue is exiting. Note that a
583 * result of true does not mean the message will be processed -- if
584 * the looper is quit before the delivery time of the message
585 * occurs then the message will be dropped.
586 */
Jeff Brown109025d2012-08-14 20:41:30 -0700587 public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 MessageQueue queue = mQueue;
Jeff Brown109025d2012-08-14 20:41:30 -0700589 if (queue == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 RuntimeException e = new RuntimeException(
Jeff Brown109025d2012-08-14 20:41:30 -0700591 this + " sendMessageAtTime() called with no mQueue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 Log.w("Looper", e.getMessage(), e);
Jeff Brown109025d2012-08-14 20:41:30 -0700593 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 }
Jeff Brown109025d2012-08-14 20:41:30 -0700595 return enqueueMessage(queue, msg, uptimeMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 }
597
598 /**
599 * Enqueue a message at the front of the message queue, to be processed on
600 * the next iteration of the message loop. You will receive it in
601 * {@link #handleMessage}, in the thread attached to this handler.
602 * <b>This method is only for use in very special circumstances -- it
603 * can easily starve the message queue, cause ordering problems, or have
604 * other unexpected side-effects.</b>
605 *
606 * @return Returns true if the message was successfully placed in to the
607 * message queue. Returns false on failure, usually because the
608 * looper processing the message queue is exiting.
609 */
Jeff Brown109025d2012-08-14 20:41:30 -0700610 public final boolean sendMessageAtFrontOfQueue(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 MessageQueue queue = mQueue;
Jeff Brown109025d2012-08-14 20:41:30 -0700612 if (queue == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 RuntimeException e = new RuntimeException(
614 this + " sendMessageAtTime() called with no mQueue");
615 Log.w("Looper", e.getMessage(), e);
Jeff Brown109025d2012-08-14 20:41:30 -0700616 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 }
Jeff Brown109025d2012-08-14 20:41:30 -0700618 return enqueueMessage(queue, msg, 0);
619 }
620
621 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
622 msg.target = this;
623 if (mAsynchronous) {
624 msg.setAsynchronous(true);
625 }
626 return queue.enqueueMessage(msg, uptimeMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 }
628
629 /**
630 * Remove any pending posts of messages with code 'what' that are in the
631 * message queue.
632 */
633 public final void removeMessages(int what) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800634 mQueue.removeMessages(this, what, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 }
636
637 /**
638 * Remove any pending posts of messages with code 'what' and whose obj is
Jeff Brown32c81132012-04-30 16:28:32 -0700639 * 'object' that are in the message queue. If <var>object</var> is null,
Dianne Hackborn466ed242011-07-21 18:16:31 -0700640 * all messages will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 */
642 public final void removeMessages(int what, Object object) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800643 mQueue.removeMessages(this, what, object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 }
645
646 /**
647 * Remove any pending posts of callbacks and sent messages whose
Dianne Hackborn466ed242011-07-21 18:16:31 -0700648 * <var>obj</var> is <var>token</var>. If <var>token</var> is null,
649 * all callbacks and messages will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 */
651 public final void removeCallbacksAndMessages(Object token) {
652 mQueue.removeCallbacksAndMessages(this, token);
653 }
654
655 /**
656 * Check if there are any pending posts of messages with code 'what' in
657 * the message queue.
658 */
659 public final boolean hasMessages(int what) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800660 return mQueue.hasMessages(this, what, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 }
662
663 /**
664 * Check if there are any pending posts of messages with code 'what' and
665 * whose obj is 'object' in the message queue.
666 */
667 public final boolean hasMessages(int what, Object object) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800668 return mQueue.hasMessages(this, what, object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 }
670
Romain Guyba6be8a2012-04-23 18:22:09 -0700671 /**
672 * Check if there are any pending posts of messages with callback r in
673 * the message queue.
674 *
675 * @hide
676 */
677 public final boolean hasCallbacks(Runnable r) {
678 return mQueue.hasMessages(this, r, null);
679 }
680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 // if we can get rid of this method, the handler need not remember its loop
682 // we could instead export a getMessageQueue() method...
683 public final Looper getLooper() {
684 return mLooper;
685 }
686
687 public final void dump(Printer pw, String prefix) {
688 pw.println(prefix + this + " @ " + SystemClock.uptimeMillis());
689 if (mLooper == null) {
690 pw.println(prefix + "looper uninitialized");
691 } else {
692 mLooper.dump(pw, prefix + " ");
693 }
694 }
695
696 @Override
697 public String toString() {
Kristian Monsen588d8562011-08-04 12:55:33 +0100698 return "Handler (" + getClass().getName() + ") {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 + Integer.toHexString(System.identityHashCode(this))
700 + "}";
701 }
702
703 final IMessenger getIMessenger() {
704 synchronized (mQueue) {
705 if (mMessenger != null) {
706 return mMessenger;
707 }
708 mMessenger = new MessengerImpl();
709 return mMessenger;
710 }
711 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 private final class MessengerImpl extends IMessenger.Stub {
714 public void send(Message msg) {
715 Handler.this.sendMessage(msg);
716 }
717 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700718
Romain Guyba6be8a2012-04-23 18:22:09 -0700719 private static Message getPostMessage(Runnable r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 Message m = Message.obtain();
721 m.callback = r;
722 return m;
723 }
724
Romain Guyba6be8a2012-04-23 18:22:09 -0700725 private static Message getPostMessage(Runnable r, Object token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 Message m = Message.obtain();
727 m.obj = token;
728 m.callback = r;
729 return m;
730 }
731
Romain Guyba6be8a2012-04-23 18:22:09 -0700732 private static void handleCallback(Message message) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 message.callback.run();
734 }
735
736 final MessageQueue mQueue;
737 final Looper mLooper;
738 final Callback mCallback;
Jeff Brown109025d2012-08-14 20:41:30 -0700739 final boolean mAsynchronous;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 IMessenger mMessenger;
Jeff Brownc53abc42012-08-29 04:43:25 -0700741
742 private static final class BlockingRunnable implements Runnable {
743 private final Runnable mTask;
744 private boolean mDone;
745
746 public BlockingRunnable(Runnable task) {
747 mTask = task;
748 }
749
750 @Override
751 public void run() {
752 try {
753 mTask.run();
754 } finally {
755 synchronized (this) {
756 mDone = true;
757 notifyAll();
758 }
759 }
760 }
761
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700762 public boolean postAndWait(Handler handler, long timeout) {
Jeff Brownc53abc42012-08-29 04:43:25 -0700763 if (!handler.post(this)) {
764 return false;
765 }
766
767 synchronized (this) {
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700768 if (timeout > 0) {
769 final long expirationTime = SystemClock.uptimeMillis() + timeout;
770 while (!mDone) {
771 long delay = expirationTime - SystemClock.uptimeMillis();
772 if (delay <= 0) {
773 return false; // timeout
774 }
775 try {
776 wait(delay);
777 } catch (InterruptedException ex) {
778 }
779 }
780 } else {
781 while (!mDone) {
782 try {
783 wait();
784 } catch (InterruptedException ex) {
785 }
Jeff Brownc53abc42012-08-29 04:43:25 -0700786 }
787 }
788 }
789 return true;
790 }
791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792}