blob: 52db0609854ee115eec19c53350136f061c5c541 [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>
David Christiea8cf4f22013-12-19 18:30:06 -0800333 * Time spent in deep sleep will add an additional delay to execution.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 * The runnable will be run on the thread to which this handler is attached.
335 *
336 * @param r The Runnable that will be executed.
337 * @param uptimeMillis The absolute time at which the callback should run,
338 * using the {@link android.os.SystemClock#uptimeMillis} time-base.
339 *
340 * @return Returns true if the Runnable was successfully placed in to the
341 * message queue. Returns false on failure, usually because the
342 * looper processing the message queue is exiting. Note that a
343 * result of true does not mean the Runnable will be processed -- if
344 * the looper is quit before the delivery time of the message
345 * occurs then the message will be dropped.
346 */
347 public final boolean postAtTime(Runnable r, long uptimeMillis)
348 {
349 return sendMessageAtTime(getPostMessage(r), uptimeMillis);
350 }
351
352 /**
353 * Causes the Runnable r to be added to the message queue, to be run
354 * at a specific time given by <var>uptimeMillis</var>.
355 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
David Christiea8cf4f22013-12-19 18:30:06 -0800356 * Time spent in deep sleep will add an additional delay to execution.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 * The runnable will be run on the thread to which this handler is attached.
358 *
359 * @param r The Runnable that will be executed.
360 * @param uptimeMillis The absolute time at which the callback should run,
361 * using the {@link android.os.SystemClock#uptimeMillis} time-base.
362 *
363 * @return Returns true if the Runnable was successfully placed in to the
364 * message queue. Returns false on failure, usually because the
365 * looper processing the message queue is exiting. Note that a
366 * result of true does not mean the Runnable will be processed -- if
367 * the looper is quit before the delivery time of the message
368 * occurs then the message will be dropped.
369 *
370 * @see android.os.SystemClock#uptimeMillis
371 */
372 public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
373 {
374 return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
375 }
376
377 /**
378 * Causes the Runnable r to be added to the message queue, to be run
379 * after the specified amount of time elapses.
380 * The runnable will be run on the thread to which this handler
381 * is attached.
David Christiea8cf4f22013-12-19 18:30:06 -0800382 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
383 * Time spent in deep sleep will add an additional delay to execution.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 *
385 * @param r The Runnable that will be executed.
386 * @param delayMillis The delay (in milliseconds) until the Runnable
387 * will be executed.
388 *
389 * @return Returns true if the Runnable was successfully placed in to the
390 * message queue. Returns false on failure, usually because the
391 * looper processing the message queue is exiting. Note that a
392 * result of true does not mean the Runnable will be processed --
393 * if the looper is quit before the delivery time of the message
394 * occurs then the message will be dropped.
395 */
396 public final boolean postDelayed(Runnable r, long delayMillis)
397 {
398 return sendMessageDelayed(getPostMessage(r), delayMillis);
399 }
400
401 /**
402 * Posts a message to an object that implements Runnable.
403 * Causes the Runnable r to executed on the next iteration through the
404 * message queue. The runnable will be run on the thread to which this
405 * handler is attached.
406 * <b>This method is only for use in very special circumstances -- it
407 * can easily starve the message queue, cause ordering problems, or have
408 * other unexpected side-effects.</b>
409 *
410 * @param r The Runnable that will be executed.
411 *
412 * @return Returns true if the message was successfully placed in to the
413 * message queue. Returns false on failure, usually because the
414 * looper processing the message queue is exiting.
415 */
416 public final boolean postAtFrontOfQueue(Runnable r)
417 {
418 return sendMessageAtFrontOfQueue(getPostMessage(r));
419 }
420
421 /**
Jeff Brownc53abc42012-08-29 04:43:25 -0700422 * Runs the specified task synchronously.
Jeff Brown8b60e452013-04-18 15:17:48 -0700423 * <p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700424 * If the current thread is the same as the handler thread, then the runnable
425 * runs immediately without being enqueued. Otherwise, posts the runnable
426 * to the handler and waits for it to complete before returning.
Jeff Brown8b60e452013-04-18 15:17:48 -0700427 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700428 * This method is dangerous! Improper use can result in deadlocks.
429 * Never call this method while any locks are held or use it in a
430 * possibly re-entrant manner.
Jeff Brown8b60e452013-04-18 15:17:48 -0700431 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700432 * This method is occasionally useful in situations where a background thread
433 * must synchronously await completion of a task that must run on the
434 * handler's thread. However, this problem is often a symptom of bad design.
435 * Consider improving the design (if possible) before resorting to this method.
Jeff Brown8b60e452013-04-18 15:17:48 -0700436 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700437 * One example of where you might want to use this method is when you just
438 * set up a Handler thread and need to perform some initialization steps on
439 * it before continuing execution.
Jeff Brown8b60e452013-04-18 15:17:48 -0700440 * </p><p>
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700441 * If timeout occurs then this method returns <code>false</code> but the runnable
442 * will remain posted on the handler and may already be in progress or
443 * complete at a later time.
Jeff Brown8b60e452013-04-18 15:17:48 -0700444 * </p><p>
445 * When using this method, be sure to use {@link Looper#quitSafely} when
446 * quitting the looper. Otherwise {@link #runWithScissors} may hang indefinitely.
447 * (TODO: We should fix this by making MessageQueue aware of blocking runnables.)
448 * </p>
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700449 *
Jeff Brownc53abc42012-08-29 04:43:25 -0700450 * @param r The Runnable that will be executed synchronously.
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700451 * @param timeout The timeout in milliseconds, or 0 to wait indefinitely.
Jeff Brownc53abc42012-08-29 04:43:25 -0700452 *
453 * @return Returns true if the Runnable was successfully executed.
454 * Returns false on failure, usually because the
455 * looper processing the message queue is exiting.
456 *
457 * @hide This method is prone to abuse and should probably not be in the API.
458 * If we ever do make it part of the API, we might want to rename it to something
459 * less funny like runUnsafe().
460 */
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700461 public final boolean runWithScissors(final Runnable r, long timeout) {
Jeff Brownc53abc42012-08-29 04:43:25 -0700462 if (r == null) {
463 throw new IllegalArgumentException("runnable must not be null");
464 }
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700465 if (timeout < 0) {
466 throw new IllegalArgumentException("timeout must be non-negative");
467 }
Jeff Brownc53abc42012-08-29 04:43:25 -0700468
469 if (Looper.myLooper() == mLooper) {
470 r.run();
471 return true;
472 }
473
474 BlockingRunnable br = new BlockingRunnable(r);
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700475 return br.postAndWait(this, timeout);
Jeff Brownc53abc42012-08-29 04:43:25 -0700476 }
477
478 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 * Remove any pending posts of Runnable r that are in the message queue.
480 */
481 public final void removeCallbacks(Runnable r)
482 {
483 mQueue.removeMessages(this, r, null);
484 }
485
486 /**
487 * Remove any pending posts of Runnable <var>r</var> with Object
Dianne Hackborn466ed242011-07-21 18:16:31 -0700488 * <var>token</var> that are in the message queue. If <var>token</var> is null,
489 * all callbacks will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 */
491 public final void removeCallbacks(Runnable r, Object token)
492 {
493 mQueue.removeMessages(this, r, token);
494 }
495
496 /**
497 * Pushes a message onto the end of the message queue after all pending messages
498 * before the current time. It will be received in {@link #handleMessage},
499 * in the thread attached to this handler.
500 *
501 * @return Returns true if the message was successfully placed in to the
502 * message queue. Returns false on failure, usually because the
503 * looper processing the message queue is exiting.
504 */
505 public final boolean sendMessage(Message msg)
506 {
507 return sendMessageDelayed(msg, 0);
508 }
509
510 /**
511 * Sends a Message containing only the what value.
512 *
513 * @return Returns true if the message was successfully placed in to the
514 * message queue. Returns false on failure, usually because the
515 * looper processing the message queue is exiting.
516 */
517 public final boolean sendEmptyMessage(int what)
518 {
519 return sendEmptyMessageDelayed(what, 0);
520 }
521
522 /**
523 * Sends a Message containing only the what value, to be delivered
524 * after the specified amount of time elapses.
525 * @see #sendMessageDelayed(android.os.Message, long)
526 *
527 * @return Returns true if the message was successfully placed in to the
528 * message queue. Returns false on failure, usually because the
529 * looper processing the message queue is exiting.
530 */
531 public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
532 Message msg = Message.obtain();
533 msg.what = what;
534 return sendMessageDelayed(msg, delayMillis);
535 }
536
537 /**
538 * Sends a Message containing only the what value, to be delivered
539 * at a specific time.
540 * @see #sendMessageAtTime(android.os.Message, long)
541 *
542 * @return Returns true if the message was successfully placed in to the
543 * message queue. Returns false on failure, usually because the
544 * looper processing the message queue is exiting.
545 */
546
547 public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
548 Message msg = Message.obtain();
549 msg.what = what;
550 return sendMessageAtTime(msg, uptimeMillis);
551 }
552
553 /**
554 * Enqueue a message into the message queue after all pending messages
555 * before (current time + delayMillis). You will receive it in
556 * {@link #handleMessage}, in the thread attached to this handler.
557 *
558 * @return Returns true if the message was successfully placed in to the
559 * message queue. Returns false on failure, usually because the
560 * looper processing the message queue is exiting. Note that a
561 * result of true does not mean the message will be processed -- if
562 * the looper is quit before the delivery time of the message
563 * occurs then the message will be dropped.
564 */
565 public final boolean sendMessageDelayed(Message msg, long delayMillis)
566 {
567 if (delayMillis < 0) {
568 delayMillis = 0;
569 }
570 return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
571 }
572
573 /**
574 * Enqueue a message into the message queue after all pending messages
575 * before the absolute time (in milliseconds) <var>uptimeMillis</var>.
576 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
David Christiea8cf4f22013-12-19 18:30:06 -0800577 * Time spent in deep sleep will add an additional delay to execution.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 * You will receive it in {@link #handleMessage}, in the thread attached
579 * to this handler.
580 *
581 * @param uptimeMillis The absolute time at which the message should be
582 * delivered, using the
583 * {@link android.os.SystemClock#uptimeMillis} time-base.
584 *
585 * @return Returns true if the message was successfully placed in to the
586 * message queue. Returns false on failure, usually because the
587 * looper processing the message queue is exiting. Note that a
588 * result of true does not mean the message will be processed -- if
589 * the looper is quit before the delivery time of the message
590 * occurs then the message will be dropped.
591 */
Jeff Brown109025d2012-08-14 20:41:30 -0700592 public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 MessageQueue queue = mQueue;
Jeff Brown109025d2012-08-14 20:41:30 -0700594 if (queue == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 RuntimeException e = new RuntimeException(
Jeff Brown109025d2012-08-14 20:41:30 -0700596 this + " sendMessageAtTime() called with no mQueue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 Log.w("Looper", e.getMessage(), e);
Jeff Brown109025d2012-08-14 20:41:30 -0700598 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 }
Jeff Brown109025d2012-08-14 20:41:30 -0700600 return enqueueMessage(queue, msg, uptimeMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 }
602
603 /**
604 * Enqueue a message at the front of the message queue, to be processed on
605 * the next iteration of the message loop. You will receive it in
606 * {@link #handleMessage}, in the thread attached to this handler.
607 * <b>This method is only for use in very special circumstances -- it
608 * can easily starve the message queue, cause ordering problems, or have
609 * other unexpected side-effects.</b>
610 *
611 * @return Returns true if the message was successfully placed in to the
612 * message queue. Returns false on failure, usually because the
613 * looper processing the message queue is exiting.
614 */
Jeff Brown109025d2012-08-14 20:41:30 -0700615 public final boolean sendMessageAtFrontOfQueue(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 MessageQueue queue = mQueue;
Jeff Brown109025d2012-08-14 20:41:30 -0700617 if (queue == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 RuntimeException e = new RuntimeException(
619 this + " sendMessageAtTime() called with no mQueue");
620 Log.w("Looper", e.getMessage(), e);
Jeff Brown109025d2012-08-14 20:41:30 -0700621 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 }
Jeff Brown109025d2012-08-14 20:41:30 -0700623 return enqueueMessage(queue, msg, 0);
624 }
625
626 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
627 msg.target = this;
628 if (mAsynchronous) {
629 msg.setAsynchronous(true);
630 }
631 return queue.enqueueMessage(msg, uptimeMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 }
633
634 /**
635 * Remove any pending posts of messages with code 'what' that are in the
636 * message queue.
637 */
638 public final void removeMessages(int what) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800639 mQueue.removeMessages(this, what, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 }
641
642 /**
643 * Remove any pending posts of messages with code 'what' and whose obj is
Jeff Brown32c81132012-04-30 16:28:32 -0700644 * 'object' that are in the message queue. If <var>object</var> is null,
Dianne Hackborn466ed242011-07-21 18:16:31 -0700645 * all messages will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 */
647 public final void removeMessages(int what, Object object) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800648 mQueue.removeMessages(this, what, object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 }
650
651 /**
652 * Remove any pending posts of callbacks and sent messages whose
Dianne Hackborn466ed242011-07-21 18:16:31 -0700653 * <var>obj</var> is <var>token</var>. If <var>token</var> is null,
654 * all callbacks and messages will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 */
656 public final void removeCallbacksAndMessages(Object token) {
657 mQueue.removeCallbacksAndMessages(this, token);
658 }
659
660 /**
661 * Check if there are any pending posts of messages with code 'what' in
662 * the message queue.
663 */
664 public final boolean hasMessages(int what) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800665 return mQueue.hasMessages(this, what, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 }
667
668 /**
669 * Check if there are any pending posts of messages with code 'what' and
670 * whose obj is 'object' in the message queue.
671 */
672 public final boolean hasMessages(int what, Object object) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800673 return mQueue.hasMessages(this, what, object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 }
675
Romain Guyba6be8a2012-04-23 18:22:09 -0700676 /**
677 * Check if there are any pending posts of messages with callback r in
678 * the message queue.
679 *
680 * @hide
681 */
682 public final boolean hasCallbacks(Runnable r) {
683 return mQueue.hasMessages(this, r, null);
684 }
685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 // if we can get rid of this method, the handler need not remember its loop
687 // we could instead export a getMessageQueue() method...
688 public final Looper getLooper() {
689 return mLooper;
690 }
691
692 public final void dump(Printer pw, String prefix) {
693 pw.println(prefix + this + " @ " + SystemClock.uptimeMillis());
694 if (mLooper == null) {
695 pw.println(prefix + "looper uninitialized");
696 } else {
697 mLooper.dump(pw, prefix + " ");
698 }
699 }
700
701 @Override
702 public String toString() {
Kristian Monsen588d8562011-08-04 12:55:33 +0100703 return "Handler (" + getClass().getName() + ") {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 + Integer.toHexString(System.identityHashCode(this))
705 + "}";
706 }
707
708 final IMessenger getIMessenger() {
709 synchronized (mQueue) {
710 if (mMessenger != null) {
711 return mMessenger;
712 }
713 mMessenger = new MessengerImpl();
714 return mMessenger;
715 }
716 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 private final class MessengerImpl extends IMessenger.Stub {
719 public void send(Message msg) {
Dianne Hackborncb3ed1d2014-06-27 18:37:06 -0700720 msg.sendingUid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 Handler.this.sendMessage(msg);
722 }
723 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700724
Romain Guyba6be8a2012-04-23 18:22:09 -0700725 private static Message getPostMessage(Runnable r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 Message m = Message.obtain();
727 m.callback = r;
728 return m;
729 }
730
Romain Guyba6be8a2012-04-23 18:22:09 -0700731 private static Message getPostMessage(Runnable r, Object token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 Message m = Message.obtain();
733 m.obj = token;
734 m.callback = r;
735 return m;
736 }
737
Romain Guyba6be8a2012-04-23 18:22:09 -0700738 private static void handleCallback(Message message) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 message.callback.run();
740 }
741
742 final MessageQueue mQueue;
743 final Looper mLooper;
744 final Callback mCallback;
Jeff Brown109025d2012-08-14 20:41:30 -0700745 final boolean mAsynchronous;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 IMessenger mMessenger;
Jeff Brownc53abc42012-08-29 04:43:25 -0700747
748 private static final class BlockingRunnable implements Runnable {
749 private final Runnable mTask;
750 private boolean mDone;
751
752 public BlockingRunnable(Runnable task) {
753 mTask = task;
754 }
755
756 @Override
757 public void run() {
758 try {
759 mTask.run();
760 } finally {
761 synchronized (this) {
762 mDone = true;
763 notifyAll();
764 }
765 }
766 }
767
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700768 public boolean postAndWait(Handler handler, long timeout) {
Jeff Brownc53abc42012-08-29 04:43:25 -0700769 if (!handler.post(this)) {
770 return false;
771 }
772
773 synchronized (this) {
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700774 if (timeout > 0) {
775 final long expirationTime = SystemClock.uptimeMillis() + timeout;
776 while (!mDone) {
777 long delay = expirationTime - SystemClock.uptimeMillis();
778 if (delay <= 0) {
779 return false; // timeout
780 }
781 try {
782 wait(delay);
783 } catch (InterruptedException ex) {
784 }
785 }
786 } else {
787 while (!mDone) {
788 try {
789 wait();
790 } catch (InterruptedException ex) {
791 }
Jeff Brownc53abc42012-08-29 04:43:25 -0700792 }
793 }
794 }
795 return true;
796 }
797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798}