blob: 8678d95db17dc65b481b785110dce29265913c8b [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
Eugene Suslaa38fbf62017-03-14 10:26:10 -070019import android.annotation.NonNull;
20import android.annotation.Nullable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.util.Log;
22import android.util.Printer;
23
24import java.lang.reflect.Modifier;
25
26/**
27 * A Handler allows you to send and process {@link Message} and Runnable
28 * objects associated with a thread's {@link MessageQueue}. Each Handler
29 * instance is associated with a single thread and that thread's message
30 * queue. When you create a new Handler, it is bound to the thread /
31 * message queue of the thread that is creating it -- from that point on,
32 * it will deliver messages and runnables to that message queue and execute
33 * them as they come out of the message queue.
34 *
35 * <p>There are two main uses for a Handler: (1) to schedule messages and
36 * runnables to be executed as some point in the future; and (2) to enqueue
37 * an action to be performed on a different thread than your own.
38 *
39 * <p>Scheduling messages is accomplished with the
40 * {@link #post}, {@link #postAtTime(Runnable, long)},
41 * {@link #postDelayed}, {@link #sendEmptyMessage},
42 * {@link #sendMessage}, {@link #sendMessageAtTime}, and
43 * {@link #sendMessageDelayed} methods. The <em>post</em> versions allow
44 * you to enqueue Runnable objects to be called by the message queue when
45 * they are received; the <em>sendMessage</em> versions allow you to enqueue
46 * a {@link Message} object containing a bundle of data that will be
47 * processed by the Handler's {@link #handleMessage} method (requiring that
48 * you implement a subclass of Handler).
49 *
50 * <p>When posting or sending to a Handler, you can either
51 * allow the item to be processed as soon as the message queue is ready
52 * to do so, or specify a delay before it gets processed or absolute time for
53 * it to be processed. The latter two allow you to implement timeouts,
54 * ticks, and other timing-based behavior.
55 *
56 * <p>When a
57 * process is created for your application, its main thread is dedicated to
58 * running a message queue that takes care of managing the top-level
59 * application objects (activities, broadcast receivers, etc) and any windows
60 * they create. You can create your own threads, and communicate back with
61 * the main application thread through a Handler. This is done by calling
62 * the same <em>post</em> or <em>sendMessage</em> methods as before, but from
Chris Palmer42855142010-09-09 17:04:31 -070063 * your new thread. The given Runnable or Message will then be scheduled
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064 * in the Handler's message queue and processed when appropriate.
65 */
66public class Handler {
67 /*
68 * Set this flag to true to detect anonymous, local or member classes
69 * that extend this Handler class and that are not static. These kind
70 * of classes can potentially create leaks.
71 */
72 private static final boolean FIND_POTENTIAL_LEAKS = false;
73 private static final String TAG = "Handler";
Eugene Suslaa38fbf62017-03-14 10:26:10 -070074 private static Handler MAIN_THREAD_HANDLER = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075
76 /**
77 * Callback interface you can use when instantiating a Handler to avoid
78 * having to implement your own subclass of Handler.
Kristian Monsen1d3b4092013-06-05 17:06:32 -070079 *
80 * @param msg A {@link android.os.Message Message} object
81 * @return True if no further handling is desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 */
83 public interface Callback {
84 public boolean handleMessage(Message msg);
85 }
86
87 /**
88 * Subclasses must implement this to receive messages.
89 */
90 public void handleMessage(Message msg) {
91 }
92
93 /**
94 * Handle system messages here.
95 */
96 public void dispatchMessage(Message msg) {
97 if (msg.callback != null) {
98 handleCallback(msg);
99 } else {
100 if (mCallback != null) {
101 if (mCallback.handleMessage(msg)) {
102 return;
103 }
104 }
105 handleMessage(msg);
106 }
107 }
108
109 /**
Jeff Browna2910d02012-08-25 12:29:46 -0700110 * Default constructor associates this handler with the {@link Looper} for the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 * current thread.
112 *
Jeff Browna2910d02012-08-25 12:29:46 -0700113 * If this thread does not have a looper, this handler won't be able to receive messages
114 * so an exception is thrown.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 */
116 public Handler() {
Jeff Browna2910d02012-08-25 12:29:46 -0700117 this(null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 }
119
120 /**
Jeff Browna2910d02012-08-25 12:29:46 -0700121 * Constructor associates this handler with the {@link Looper} for the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 * current thread and takes a callback interface in which you can handle
123 * messages.
Jeff Browna2910d02012-08-25 12:29:46 -0700124 *
125 * If this thread does not have a looper, this handler won't be able to receive messages
126 * so an exception is thrown.
127 *
128 * @param callback The callback interface in which to handle messages, or null.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 */
130 public Handler(Callback callback) {
Jeff Browna2910d02012-08-25 12:29:46 -0700131 this(callback, false);
132 }
133
134 /**
135 * Use the provided {@link Looper} instead of the default one.
136 *
137 * @param looper The looper, must not be null.
138 */
139 public Handler(Looper looper) {
140 this(looper, null, false);
141 }
142
143 /**
144 * Use the provided {@link Looper} instead of the default one and take a callback
145 * interface in which to handle messages.
146 *
147 * @param looper The looper, must not be null.
148 * @param callback The callback interface in which to handle messages, or null.
149 */
150 public Handler(Looper looper, Callback callback) {
151 this(looper, callback, false);
152 }
153
154 /**
155 * Use the {@link Looper} for the current thread
156 * and set whether the handler should be asynchronous.
157 *
158 * Handlers are synchronous by default unless this constructor is used to make
159 * one that is strictly asynchronous.
160 *
161 * Asynchronous messages represent interrupts or events that do not require global ordering
Jeff Brown9840c072014-11-11 20:21:21 -0800162 * with respect to synchronous messages. Asynchronous messages are not subject to
Jeff Browna2910d02012-08-25 12:29:46 -0700163 * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
164 *
165 * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
166 * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
167 *
168 * @hide
169 */
170 public Handler(boolean async) {
171 this(null, async);
172 }
173
174 /**
175 * Use the {@link Looper} for the current thread with the specified callback interface
176 * and set whether the handler should be asynchronous.
177 *
178 * Handlers are synchronous by default unless this constructor is used to make
179 * one that is strictly asynchronous.
180 *
181 * Asynchronous messages represent interrupts or events that do not require global ordering
Jeff Brown9840c072014-11-11 20:21:21 -0800182 * with respect to synchronous messages. Asynchronous messages are not subject to
Jeff Browna2910d02012-08-25 12:29:46 -0700183 * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
184 *
185 * @param callback The callback interface in which to handle messages, or null.
186 * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
187 * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
188 *
189 * @hide
190 */
191 public Handler(Callback callback, boolean async) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 if (FIND_POTENTIAL_LEAKS) {
193 final Class<? extends Handler> klass = getClass();
194 if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
195 (klass.getModifiers() & Modifier.STATIC) == 0) {
196 Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
197 klass.getCanonicalName());
198 }
199 }
200
201 mLooper = Looper.myLooper();
202 if (mLooper == null) {
203 throw new RuntimeException(
204 "Can't create handler inside thread that has not called Looper.prepare()");
205 }
206 mQueue = mLooper.mQueue;
207 mCallback = callback;
Jeff Browna2910d02012-08-25 12:29:46 -0700208 mAsynchronous = async;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 }
210
211 /**
Jeff Browna2910d02012-08-25 12:29:46 -0700212 * Use the provided {@link Looper} instead of the default one and take a callback
Jeff Brown109025d2012-08-14 20:41:30 -0700213 * interface in which to handle messages. Also set whether the handler
214 * should be asynchronous.
215 *
216 * Handlers are synchronous by default unless this constructor is used to make
217 * one that is strictly asynchronous.
218 *
219 * Asynchronous messages represent interrupts or events that do not require global ordering
Jeff Brown9840c072014-11-11 20:21:21 -0800220 * with respect to synchronous messages. Asynchronous messages are not subject to
Jeff Brown109025d2012-08-14 20:41:30 -0700221 * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
222 *
Jeff Browna2910d02012-08-25 12:29:46 -0700223 * @param looper The looper, must not be null.
224 * @param callback The callback interface in which to handle messages, or null.
Jeff Brown109025d2012-08-14 20:41:30 -0700225 * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
226 * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
227 *
228 * @hide
229 */
230 public Handler(Looper looper, Callback callback, boolean async) {
231 mLooper = looper;
232 mQueue = looper.mQueue;
233 mCallback = callback;
234 mAsynchronous = async;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 }
236
Eugene Suslaa38fbf62017-03-14 10:26:10 -0700237 /** @hide */
238 @NonNull
239 public static Handler getMain() {
240 if (MAIN_THREAD_HANDLER == null) {
241 MAIN_THREAD_HANDLER = new Handler(Looper.getMainLooper());
242 }
243 return MAIN_THREAD_HANDLER;
244 }
245
246 /** @hide */
247 @NonNull
248 public static Handler mainIfNull(@Nullable Handler handler) {
249 return handler == null ? getMain() : handler;
250 }
251
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600252 /** {@hide} */
253 public String getTraceName(Message message) {
254 final StringBuilder sb = new StringBuilder();
255 sb.append(getClass().getName()).append(": ");
256 if (message.callback != null) {
257 sb.append(message.callback.getClass().getName());
258 } else {
259 sb.append("#").append(message.what);
260 }
261 return sb.toString();
262 }
263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 /**
Romain Guyf9284692011-07-13 18:46:21 -0700265 * Returns a string representing the name of the specified message.
266 * The default implementation will either return the class name of the
267 * message callback if any, or the hexadecimal representation of the
268 * message "what" field.
269 *
270 * @param message The message whose name is being queried
271 */
272 public String getMessageName(Message message) {
273 if (message.callback != null) {
274 return message.callback.getClass().getName();
275 }
276 return "0x" + Integer.toHexString(message.what);
277 }
278
279 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 * Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
281 * creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
282 * If you don't want that facility, just call Message.obtain() instead.
283 */
284 public final Message obtainMessage()
285 {
286 return Message.obtain(this);
287 }
288
289 /**
290 * Same as {@link #obtainMessage()}, except that it also sets the what member of the returned Message.
291 *
292 * @param what Value to assign to the returned Message.what field.
293 * @return A Message from the global message pool.
294 */
295 public final Message obtainMessage(int what)
296 {
297 return Message.obtain(this, what);
298 }
299
300 /**
301 *
302 * Same as {@link #obtainMessage()}, except that it also sets the what and obj members
303 * of the returned Message.
304 *
305 * @param what Value to assign to the returned Message.what field.
306 * @param obj Value to assign to the returned Message.obj field.
307 * @return A Message from the global message pool.
308 */
309 public final Message obtainMessage(int what, Object obj)
310 {
311 return Message.obtain(this, what, obj);
312 }
313
314 /**
315 *
316 * Same as {@link #obtainMessage()}, except that it also sets the what, arg1 and arg2 members of the returned
317 * Message.
318 * @param what Value to assign to the returned Message.what field.
319 * @param arg1 Value to assign to the returned Message.arg1 field.
320 * @param arg2 Value to assign to the returned Message.arg2 field.
321 * @return A Message from the global message pool.
322 */
323 public final Message obtainMessage(int what, int arg1, int arg2)
324 {
325 return Message.obtain(this, what, arg1, arg2);
326 }
327
328 /**
329 *
330 * Same as {@link #obtainMessage()}, except that it also sets the what, obj, arg1,and arg2 values on the
331 * returned Message.
332 * @param what Value to assign to the returned Message.what field.
333 * @param arg1 Value to assign to the returned Message.arg1 field.
334 * @param arg2 Value to assign to the returned Message.arg2 field.
335 * @param obj Value to assign to the returned Message.obj field.
336 * @return A Message from the global message pool.
337 */
338 public final Message obtainMessage(int what, int arg1, int arg2, Object obj)
339 {
340 return Message.obtain(this, what, arg1, arg2, obj);
341 }
342
343 /**
344 * Causes the Runnable r to be added to the message queue.
345 * The runnable will be run on the thread to which this handler is
346 * attached.
347 *
348 * @param r The Runnable that will be executed.
349 *
350 * @return Returns true if the Runnable was successfully placed in to the
351 * message queue. Returns false on failure, usually because the
352 * looper processing the message queue is exiting.
353 */
354 public final boolean post(Runnable r)
355 {
356 return sendMessageDelayed(getPostMessage(r), 0);
357 }
358
359 /**
360 * Causes the Runnable r to be added to the message queue, to be run
361 * at a specific time given by <var>uptimeMillis</var>.
362 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
David Christiea8cf4f22013-12-19 18:30:06 -0800363 * Time spent in deep sleep will add an additional delay to execution.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 * The runnable will be run on the thread to which this handler is attached.
365 *
366 * @param r The Runnable that will be executed.
367 * @param uptimeMillis The absolute time at which the callback should run,
368 * using the {@link android.os.SystemClock#uptimeMillis} time-base.
369 *
370 * @return Returns true if the Runnable was successfully placed in to the
371 * message queue. Returns false on failure, usually because the
372 * looper processing the message queue is exiting. Note that a
373 * result of true does not mean the Runnable will be processed -- if
374 * the looper is quit before the delivery time of the message
375 * occurs then the message will be dropped.
376 */
377 public final boolean postAtTime(Runnable r, long uptimeMillis)
378 {
379 return sendMessageAtTime(getPostMessage(r), uptimeMillis);
380 }
381
382 /**
383 * Causes the Runnable r to be added to the message queue, to be run
384 * at a specific time given by <var>uptimeMillis</var>.
385 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
David Christiea8cf4f22013-12-19 18:30:06 -0800386 * Time spent in deep sleep will add an additional delay to execution.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 * The runnable will be run on the thread to which this handler is attached.
388 *
389 * @param r The Runnable that will be executed.
390 * @param uptimeMillis The absolute time at which the callback should run,
391 * using the {@link android.os.SystemClock#uptimeMillis} time-base.
392 *
393 * @return Returns true if the Runnable was successfully placed in to the
394 * message queue. Returns false on failure, usually because the
395 * looper processing the message queue is exiting. Note that a
396 * result of true does not mean the Runnable will be processed -- if
397 * the looper is quit before the delivery time of the message
398 * occurs then the message will be dropped.
399 *
400 * @see android.os.SystemClock#uptimeMillis
401 */
402 public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
403 {
404 return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
405 }
406
407 /**
408 * Causes the Runnable r to be added to the message queue, to be run
409 * after the specified amount of time elapses.
410 * The runnable will be run on the thread to which this handler
411 * is attached.
David Christiea8cf4f22013-12-19 18:30:06 -0800412 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
413 * Time spent in deep sleep will add an additional delay to execution.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 *
415 * @param r The Runnable that will be executed.
416 * @param delayMillis The delay (in milliseconds) until the Runnable
417 * will be executed.
418 *
419 * @return Returns true if the Runnable was successfully placed in to the
420 * message queue. Returns false on failure, usually because the
421 * looper processing the message queue is exiting. Note that a
422 * result of true does not mean the Runnable will be processed --
423 * if the looper is quit before the delivery time of the message
424 * occurs then the message will be dropped.
425 */
426 public final boolean postDelayed(Runnable r, long delayMillis)
427 {
428 return sendMessageDelayed(getPostMessage(r), delayMillis);
429 }
430
431 /**
432 * Posts a message to an object that implements Runnable.
433 * Causes the Runnable r to executed on the next iteration through the
434 * message queue. The runnable will be run on the thread to which this
435 * handler is attached.
436 * <b>This method is only for use in very special circumstances -- it
437 * can easily starve the message queue, cause ordering problems, or have
438 * other unexpected side-effects.</b>
439 *
440 * @param r The Runnable that will be executed.
441 *
442 * @return Returns true if the message was successfully placed in to the
443 * message queue. Returns false on failure, usually because the
444 * looper processing the message queue is exiting.
445 */
446 public final boolean postAtFrontOfQueue(Runnable r)
447 {
448 return sendMessageAtFrontOfQueue(getPostMessage(r));
449 }
450
451 /**
Jeff Brownc53abc42012-08-29 04:43:25 -0700452 * Runs the specified task synchronously.
Jeff Brown8b60e452013-04-18 15:17:48 -0700453 * <p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700454 * If the current thread is the same as the handler thread, then the runnable
455 * runs immediately without being enqueued. Otherwise, posts the runnable
456 * to the handler and waits for it to complete before returning.
Jeff Brown8b60e452013-04-18 15:17:48 -0700457 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700458 * This method is dangerous! Improper use can result in deadlocks.
459 * Never call this method while any locks are held or use it in a
460 * possibly re-entrant manner.
Jeff Brown8b60e452013-04-18 15:17:48 -0700461 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700462 * This method is occasionally useful in situations where a background thread
463 * must synchronously await completion of a task that must run on the
464 * handler's thread. However, this problem is often a symptom of bad design.
465 * Consider improving the design (if possible) before resorting to this method.
Jeff Brown8b60e452013-04-18 15:17:48 -0700466 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700467 * One example of where you might want to use this method is when you just
468 * set up a Handler thread and need to perform some initialization steps on
469 * it before continuing execution.
Jeff Brown8b60e452013-04-18 15:17:48 -0700470 * </p><p>
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700471 * If timeout occurs then this method returns <code>false</code> but the runnable
472 * will remain posted on the handler and may already be in progress or
473 * complete at a later time.
Jeff Brown8b60e452013-04-18 15:17:48 -0700474 * </p><p>
475 * When using this method, be sure to use {@link Looper#quitSafely} when
476 * quitting the looper. Otherwise {@link #runWithScissors} may hang indefinitely.
477 * (TODO: We should fix this by making MessageQueue aware of blocking runnables.)
478 * </p>
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700479 *
Jeff Brownc53abc42012-08-29 04:43:25 -0700480 * @param r The Runnable that will be executed synchronously.
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700481 * @param timeout The timeout in milliseconds, or 0 to wait indefinitely.
Jeff Brownc53abc42012-08-29 04:43:25 -0700482 *
483 * @return Returns true if the Runnable was successfully executed.
484 * Returns false on failure, usually because the
485 * looper processing the message queue is exiting.
486 *
487 * @hide This method is prone to abuse and should probably not be in the API.
488 * If we ever do make it part of the API, we might want to rename it to something
489 * less funny like runUnsafe().
490 */
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700491 public final boolean runWithScissors(final Runnable r, long timeout) {
Jeff Brownc53abc42012-08-29 04:43:25 -0700492 if (r == null) {
493 throw new IllegalArgumentException("runnable must not be null");
494 }
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700495 if (timeout < 0) {
496 throw new IllegalArgumentException("timeout must be non-negative");
497 }
Jeff Brownc53abc42012-08-29 04:43:25 -0700498
499 if (Looper.myLooper() == mLooper) {
500 r.run();
501 return true;
502 }
503
504 BlockingRunnable br = new BlockingRunnable(r);
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700505 return br.postAndWait(this, timeout);
Jeff Brownc53abc42012-08-29 04:43:25 -0700506 }
507
508 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 * Remove any pending posts of Runnable r that are in the message queue.
510 */
511 public final void removeCallbacks(Runnable r)
512 {
513 mQueue.removeMessages(this, r, null);
514 }
515
516 /**
517 * Remove any pending posts of Runnable <var>r</var> with Object
Dianne Hackborn466ed242011-07-21 18:16:31 -0700518 * <var>token</var> that are in the message queue. If <var>token</var> is null,
519 * all callbacks will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 */
521 public final void removeCallbacks(Runnable r, Object token)
522 {
523 mQueue.removeMessages(this, r, token);
524 }
525
526 /**
527 * Pushes a message onto the end of the message queue after all pending messages
528 * before the current time. It will be received in {@link #handleMessage},
529 * in the thread attached to this handler.
530 *
531 * @return Returns true if the message was successfully placed in to the
532 * message queue. Returns false on failure, usually because the
533 * looper processing the message queue is exiting.
534 */
535 public final boolean sendMessage(Message msg)
536 {
537 return sendMessageDelayed(msg, 0);
538 }
539
540 /**
541 * Sends a Message containing only the what value.
542 *
543 * @return Returns true if the message was successfully placed in to the
544 * message queue. Returns false on failure, usually because the
545 * looper processing the message queue is exiting.
546 */
547 public final boolean sendEmptyMessage(int what)
548 {
549 return sendEmptyMessageDelayed(what, 0);
550 }
551
552 /**
553 * Sends a Message containing only the what value, to be delivered
554 * after the specified amount of time elapses.
555 * @see #sendMessageDelayed(android.os.Message, long)
556 *
557 * @return Returns true if the message was successfully placed in to the
558 * message queue. Returns false on failure, usually because the
559 * looper processing the message queue is exiting.
560 */
561 public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
562 Message msg = Message.obtain();
563 msg.what = what;
564 return sendMessageDelayed(msg, delayMillis);
565 }
566
567 /**
568 * Sends a Message containing only the what value, to be delivered
569 * at a specific time.
570 * @see #sendMessageAtTime(android.os.Message, long)
571 *
572 * @return Returns true if the message was successfully placed in to the
573 * message queue. Returns false on failure, usually because the
574 * looper processing the message queue is exiting.
575 */
576
577 public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
578 Message msg = Message.obtain();
579 msg.what = what;
580 return sendMessageAtTime(msg, uptimeMillis);
581 }
582
583 /**
584 * Enqueue a message into the message queue after all pending messages
585 * before (current time + delayMillis). You will receive it in
586 * {@link #handleMessage}, in the thread attached to this handler.
587 *
588 * @return Returns true if the message was successfully placed in to the
589 * message queue. Returns false on failure, usually because the
590 * looper processing the message queue is exiting. Note that a
591 * result of true does not mean the message will be processed -- if
592 * the looper is quit before the delivery time of the message
593 * occurs then the message will be dropped.
594 */
595 public final boolean sendMessageDelayed(Message msg, long delayMillis)
596 {
597 if (delayMillis < 0) {
598 delayMillis = 0;
599 }
600 return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
601 }
602
603 /**
604 * Enqueue a message into the message queue after all pending messages
605 * before the absolute time (in milliseconds) <var>uptimeMillis</var>.
606 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
David Christiea8cf4f22013-12-19 18:30:06 -0800607 * Time spent in deep sleep will add an additional delay to execution.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 * You will receive it in {@link #handleMessage}, in the thread attached
609 * to this handler.
610 *
611 * @param uptimeMillis The absolute time at which the message should be
612 * delivered, using the
613 * {@link android.os.SystemClock#uptimeMillis} time-base.
614 *
615 * @return Returns true if the message was successfully placed in to the
616 * message queue. Returns false on failure, usually because the
617 * looper processing the message queue is exiting. Note that a
618 * result of true does not mean the message will be processed -- if
619 * the looper is quit before the delivery time of the message
620 * occurs then the message will be dropped.
621 */
Jeff Brown109025d2012-08-14 20:41:30 -0700622 public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 MessageQueue queue = mQueue;
Jeff Brown109025d2012-08-14 20:41:30 -0700624 if (queue == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 RuntimeException e = new RuntimeException(
Jeff Brown109025d2012-08-14 20:41:30 -0700626 this + " sendMessageAtTime() called with no mQueue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 Log.w("Looper", e.getMessage(), e);
Jeff Brown109025d2012-08-14 20:41:30 -0700628 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 }
Jeff Brown109025d2012-08-14 20:41:30 -0700630 return enqueueMessage(queue, msg, uptimeMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 }
632
633 /**
634 * Enqueue a message at the front of the message queue, to be processed on
635 * the next iteration of the message loop. You will receive it in
636 * {@link #handleMessage}, in the thread attached to this handler.
637 * <b>This method is only for use in very special circumstances -- it
638 * can easily starve the message queue, cause ordering problems, or have
639 * other unexpected side-effects.</b>
640 *
641 * @return Returns true if the message was successfully placed in to the
642 * message queue. Returns false on failure, usually because the
643 * looper processing the message queue is exiting.
644 */
Jeff Brown109025d2012-08-14 20:41:30 -0700645 public final boolean sendMessageAtFrontOfQueue(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 MessageQueue queue = mQueue;
Jeff Brown109025d2012-08-14 20:41:30 -0700647 if (queue == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 RuntimeException e = new RuntimeException(
649 this + " sendMessageAtTime() called with no mQueue");
650 Log.w("Looper", e.getMessage(), e);
Jeff Brown109025d2012-08-14 20:41:30 -0700651 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 }
Jeff Brown109025d2012-08-14 20:41:30 -0700653 return enqueueMessage(queue, msg, 0);
654 }
655
656 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
657 msg.target = this;
658 if (mAsynchronous) {
659 msg.setAsynchronous(true);
660 }
661 return queue.enqueueMessage(msg, uptimeMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 }
663
664 /**
665 * Remove any pending posts of messages with code 'what' that are in the
666 * message queue.
667 */
668 public final void removeMessages(int what) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800669 mQueue.removeMessages(this, what, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 }
671
672 /**
673 * Remove any pending posts of messages with code 'what' and whose obj is
Jeff Brown32c81132012-04-30 16:28:32 -0700674 * 'object' that are in the message queue. If <var>object</var> is null,
Dianne Hackborn466ed242011-07-21 18:16:31 -0700675 * all messages will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 */
677 public final void removeMessages(int what, Object object) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800678 mQueue.removeMessages(this, what, object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 }
680
681 /**
682 * Remove any pending posts of callbacks and sent messages whose
Dianne Hackborn466ed242011-07-21 18:16:31 -0700683 * <var>obj</var> is <var>token</var>. If <var>token</var> is null,
684 * all callbacks and messages will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 */
686 public final void removeCallbacksAndMessages(Object token) {
687 mQueue.removeCallbacksAndMessages(this, token);
688 }
689
690 /**
691 * Check if there are any pending posts of messages with code 'what' in
692 * the message queue.
693 */
694 public final boolean hasMessages(int what) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800695 return mQueue.hasMessages(this, what, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 }
697
698 /**
699 * Check if there are any pending posts of messages with code 'what' and
700 * whose obj is 'object' in the message queue.
701 */
702 public final boolean hasMessages(int what, Object object) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800703 return mQueue.hasMessages(this, what, object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 }
705
Romain Guyba6be8a2012-04-23 18:22:09 -0700706 /**
707 * Check if there are any pending posts of messages with callback r in
708 * the message queue.
709 *
710 * @hide
711 */
712 public final boolean hasCallbacks(Runnable r) {
713 return mQueue.hasMessages(this, r, null);
714 }
715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 // if we can get rid of this method, the handler need not remember its loop
717 // we could instead export a getMessageQueue() method...
718 public final Looper getLooper() {
719 return mLooper;
720 }
721
722 public final void dump(Printer pw, String prefix) {
723 pw.println(prefix + this + " @ " + SystemClock.uptimeMillis());
724 if (mLooper == null) {
725 pw.println(prefix + "looper uninitialized");
726 } else {
727 mLooper.dump(pw, prefix + " ");
728 }
729 }
730
731 @Override
732 public String toString() {
Kristian Monsen588d8562011-08-04 12:55:33 +0100733 return "Handler (" + getClass().getName() + ") {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 + Integer.toHexString(System.identityHashCode(this))
735 + "}";
736 }
737
738 final IMessenger getIMessenger() {
739 synchronized (mQueue) {
740 if (mMessenger != null) {
741 return mMessenger;
742 }
743 mMessenger = new MessengerImpl();
744 return mMessenger;
745 }
746 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 private final class MessengerImpl extends IMessenger.Stub {
749 public void send(Message msg) {
Dianne Hackborncb3ed1d2014-06-27 18:37:06 -0700750 msg.sendingUid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 Handler.this.sendMessage(msg);
752 }
753 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700754
Romain Guyba6be8a2012-04-23 18:22:09 -0700755 private static Message getPostMessage(Runnable r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 Message m = Message.obtain();
757 m.callback = r;
758 return m;
759 }
760
Romain Guyba6be8a2012-04-23 18:22:09 -0700761 private static Message getPostMessage(Runnable r, Object token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 Message m = Message.obtain();
763 m.obj = token;
764 m.callback = r;
765 return m;
766 }
767
Romain Guyba6be8a2012-04-23 18:22:09 -0700768 private static void handleCallback(Message message) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 message.callback.run();
770 }
771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 final Looper mLooper;
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600773 final MessageQueue mQueue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 final Callback mCallback;
Jeff Brown109025d2012-08-14 20:41:30 -0700775 final boolean mAsynchronous;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 IMessenger mMessenger;
Jeff Brownc53abc42012-08-29 04:43:25 -0700777
778 private static final class BlockingRunnable implements Runnable {
779 private final Runnable mTask;
780 private boolean mDone;
781
782 public BlockingRunnable(Runnable task) {
783 mTask = task;
784 }
785
786 @Override
787 public void run() {
788 try {
789 mTask.run();
790 } finally {
791 synchronized (this) {
792 mDone = true;
793 notifyAll();
794 }
795 }
796 }
797
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700798 public boolean postAndWait(Handler handler, long timeout) {
Jeff Brownc53abc42012-08-29 04:43:25 -0700799 if (!handler.post(this)) {
800 return false;
801 }
802
803 synchronized (this) {
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700804 if (timeout > 0) {
805 final long expirationTime = SystemClock.uptimeMillis() + timeout;
806 while (!mDone) {
807 long delay = expirationTime - SystemClock.uptimeMillis();
808 if (delay <= 0) {
809 return false; // timeout
810 }
811 try {
812 wait(delay);
813 } catch (InterruptedException ex) {
814 }
815 }
816 } else {
817 while (!mDone) {
818 try {
819 wait();
820 } catch (InterruptedException ex) {
821 }
Jeff Brownc53abc42012-08-29 04:43:25 -0700822 }
823 }
824 }
825 return true;
826 }
827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828}