blob: fc88e900663919d13b58680b420ba7045fbaecea [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.
79 */
80 public interface Callback {
Pavel Grafovdcc53572017-03-10 19:39:14 +000081 /**
82 * @param msg A {@link android.os.Message Message} object
83 * @return True if no further handling is desired
84 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 public boolean handleMessage(Message msg);
86 }
87
88 /**
89 * Subclasses must implement this to receive messages.
90 */
91 public void handleMessage(Message msg) {
92 }
93
94 /**
95 * Handle system messages here.
96 */
97 public void dispatchMessage(Message msg) {
98 if (msg.callback != null) {
99 handleCallback(msg);
100 } else {
101 if (mCallback != null) {
102 if (mCallback.handleMessage(msg)) {
103 return;
104 }
105 }
106 handleMessage(msg);
107 }
108 }
109
110 /**
Jeff Browna2910d02012-08-25 12:29:46 -0700111 * Default constructor associates this handler with the {@link Looper} for the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 * current thread.
113 *
Jeff Browna2910d02012-08-25 12:29:46 -0700114 * If this thread does not have a looper, this handler won't be able to receive messages
115 * so an exception is thrown.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 */
117 public Handler() {
Jeff Browna2910d02012-08-25 12:29:46 -0700118 this(null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 }
120
121 /**
Jeff Browna2910d02012-08-25 12:29:46 -0700122 * Constructor associates this handler with the {@link Looper} for the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 * current thread and takes a callback interface in which you can handle
124 * messages.
Jeff Browna2910d02012-08-25 12:29:46 -0700125 *
126 * If this thread does not have a looper, this handler won't be able to receive messages
127 * so an exception is thrown.
128 *
129 * @param callback The callback interface in which to handle messages, or null.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 */
131 public Handler(Callback callback) {
Jeff Browna2910d02012-08-25 12:29:46 -0700132 this(callback, false);
133 }
134
135 /**
136 * Use the provided {@link Looper} instead of the default one.
137 *
138 * @param looper The looper, must not be null.
139 */
140 public Handler(Looper looper) {
141 this(looper, null, false);
142 }
143
144 /**
145 * Use the provided {@link Looper} instead of the default one and take a callback
146 * interface in which to handle messages.
147 *
148 * @param looper The looper, must not be null.
149 * @param callback The callback interface in which to handle messages, or null.
150 */
151 public Handler(Looper looper, Callback callback) {
152 this(looper, callback, false);
153 }
154
155 /**
156 * Use the {@link Looper} for the current thread
157 * and set whether the handler should be asynchronous.
158 *
159 * Handlers are synchronous by default unless this constructor is used to make
160 * one that is strictly asynchronous.
161 *
162 * Asynchronous messages represent interrupts or events that do not require global ordering
Jeff Brown9840c072014-11-11 20:21:21 -0800163 * with respect to synchronous messages. Asynchronous messages are not subject to
Jeff Browna2910d02012-08-25 12:29:46 -0700164 * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
165 *
166 * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
167 * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
168 *
169 * @hide
170 */
171 public Handler(boolean async) {
172 this(null, async);
173 }
174
175 /**
176 * Use the {@link Looper} for the current thread with the specified callback interface
177 * and set whether the handler should be asynchronous.
178 *
179 * Handlers are synchronous by default unless this constructor is used to make
180 * one that is strictly asynchronous.
181 *
182 * Asynchronous messages represent interrupts or events that do not require global ordering
Jeff Brown9840c072014-11-11 20:21:21 -0800183 * with respect to synchronous messages. Asynchronous messages are not subject to
Jeff Browna2910d02012-08-25 12:29:46 -0700184 * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
185 *
186 * @param callback The callback interface in which to handle messages, or null.
187 * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
188 * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
189 *
190 * @hide
191 */
192 public Handler(Callback callback, boolean async) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 if (FIND_POTENTIAL_LEAKS) {
194 final Class<? extends Handler> klass = getClass();
195 if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
196 (klass.getModifiers() & Modifier.STATIC) == 0) {
197 Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
198 klass.getCanonicalName());
199 }
200 }
201
202 mLooper = Looper.myLooper();
203 if (mLooper == null) {
204 throw new RuntimeException(
Eugene Susla8f07ee12017-11-14 17:41:03 -0800205 "Can't create handler inside thread " + Thread.currentThread()
206 + " that has not called Looper.prepare()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 }
208 mQueue = mLooper.mQueue;
209 mCallback = callback;
Jeff Browna2910d02012-08-25 12:29:46 -0700210 mAsynchronous = async;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 }
212
213 /**
Jeff Browna2910d02012-08-25 12:29:46 -0700214 * Use the provided {@link Looper} instead of the default one and take a callback
Jeff Brown109025d2012-08-14 20:41:30 -0700215 * interface in which to handle messages. Also set whether the handler
216 * should be asynchronous.
217 *
218 * Handlers are synchronous by default unless this constructor is used to make
219 * one that is strictly asynchronous.
220 *
221 * Asynchronous messages represent interrupts or events that do not require global ordering
Jeff Brown9840c072014-11-11 20:21:21 -0800222 * with respect to synchronous messages. Asynchronous messages are not subject to
Jeff Brown109025d2012-08-14 20:41:30 -0700223 * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
224 *
Jeff Browna2910d02012-08-25 12:29:46 -0700225 * @param looper The looper, must not be null.
226 * @param callback The callback interface in which to handle messages, or null.
Jeff Brown109025d2012-08-14 20:41:30 -0700227 * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
228 * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
229 *
230 * @hide
231 */
232 public Handler(Looper looper, Callback callback, boolean async) {
233 mLooper = looper;
234 mQueue = looper.mQueue;
235 mCallback = callback;
236 mAsynchronous = async;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 }
238
Eugene Suslaa38fbf62017-03-14 10:26:10 -0700239 /** @hide */
240 @NonNull
241 public static Handler getMain() {
242 if (MAIN_THREAD_HANDLER == null) {
243 MAIN_THREAD_HANDLER = new Handler(Looper.getMainLooper());
244 }
245 return MAIN_THREAD_HANDLER;
246 }
247
248 /** @hide */
249 @NonNull
250 public static Handler mainIfNull(@Nullable Handler handler) {
251 return handler == null ? getMain() : handler;
252 }
253
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600254 /** {@hide} */
255 public String getTraceName(Message message) {
256 final StringBuilder sb = new StringBuilder();
257 sb.append(getClass().getName()).append(": ");
258 if (message.callback != null) {
259 sb.append(message.callback.getClass().getName());
260 } else {
261 sb.append("#").append(message.what);
262 }
263 return sb.toString();
264 }
265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 /**
Romain Guyf9284692011-07-13 18:46:21 -0700267 * Returns a string representing the name of the specified message.
268 * The default implementation will either return the class name of the
269 * message callback if any, or the hexadecimal representation of the
270 * message "what" field.
271 *
272 * @param message The message whose name is being queried
273 */
274 public String getMessageName(Message message) {
275 if (message.callback != null) {
276 return message.callback.getClass().getName();
277 }
278 return "0x" + Integer.toHexString(message.what);
279 }
280
281 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 * Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
283 * creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
284 * If you don't want that facility, just call Message.obtain() instead.
285 */
286 public final Message obtainMessage()
287 {
288 return Message.obtain(this);
289 }
290
291 /**
292 * Same as {@link #obtainMessage()}, except that it also sets the what member of the returned Message.
293 *
294 * @param what Value to assign to the returned Message.what field.
295 * @return A Message from the global message pool.
296 */
297 public final Message obtainMessage(int what)
298 {
299 return Message.obtain(this, what);
300 }
301
302 /**
303 *
304 * Same as {@link #obtainMessage()}, except that it also sets the what and obj members
305 * of the returned Message.
306 *
307 * @param what Value to assign to the returned Message.what field.
308 * @param obj Value to assign to the returned Message.obj field.
309 * @return A Message from the global message pool.
310 */
311 public final Message obtainMessage(int what, Object obj)
312 {
313 return Message.obtain(this, what, obj);
314 }
315
316 /**
317 *
318 * Same as {@link #obtainMessage()}, except that it also sets the what, arg1 and arg2 members of the returned
319 * Message.
320 * @param what Value to assign to the returned Message.what field.
321 * @param arg1 Value to assign to the returned Message.arg1 field.
322 * @param arg2 Value to assign to the returned Message.arg2 field.
323 * @return A Message from the global message pool.
324 */
325 public final Message obtainMessage(int what, int arg1, int arg2)
326 {
327 return Message.obtain(this, what, arg1, arg2);
328 }
329
330 /**
331 *
332 * Same as {@link #obtainMessage()}, except that it also sets the what, obj, arg1,and arg2 values on the
333 * returned Message.
334 * @param what Value to assign to the returned Message.what field.
335 * @param arg1 Value to assign to the returned Message.arg1 field.
336 * @param arg2 Value to assign to the returned Message.arg2 field.
337 * @param obj Value to assign to the returned Message.obj field.
338 * @return A Message from the global message pool.
339 */
340 public final Message obtainMessage(int what, int arg1, int arg2, Object obj)
341 {
342 return Message.obtain(this, what, arg1, arg2, obj);
343 }
344
345 /**
346 * Causes the Runnable r to be added to the message queue.
347 * The runnable will be run on the thread to which this handler is
348 * attached.
349 *
350 * @param r The Runnable that will be executed.
351 *
352 * @return Returns true if the Runnable was successfully placed in to the
353 * message queue. Returns false on failure, usually because the
354 * looper processing the message queue is exiting.
355 */
356 public final boolean post(Runnable r)
357 {
358 return sendMessageDelayed(getPostMessage(r), 0);
359 }
360
361 /**
362 * Causes the Runnable r to be added to the message queue, to be run
363 * at a specific time given by <var>uptimeMillis</var>.
364 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
David Christiea8cf4f22013-12-19 18:30:06 -0800365 * Time spent in deep sleep will add an additional delay to execution.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 * The runnable will be run on the thread to which this handler is attached.
367 *
368 * @param r The Runnable that will be executed.
369 * @param uptimeMillis The absolute time at which the callback should run,
370 * using the {@link android.os.SystemClock#uptimeMillis} time-base.
371 *
372 * @return Returns true if the Runnable was successfully placed in to the
373 * message queue. Returns false on failure, usually because the
374 * looper processing the message queue is exiting. Note that a
375 * result of true does not mean the Runnable will be processed -- if
376 * the looper is quit before the delivery time of the message
377 * occurs then the message will be dropped.
378 */
379 public final boolean postAtTime(Runnable r, long uptimeMillis)
380 {
381 return sendMessageAtTime(getPostMessage(r), uptimeMillis);
382 }
383
384 /**
385 * Causes the Runnable r to be added to the message queue, to be run
386 * at a specific time given by <var>uptimeMillis</var>.
387 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
David Christiea8cf4f22013-12-19 18:30:06 -0800388 * Time spent in deep sleep will add an additional delay to execution.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 * The runnable will be run on the thread to which this handler is attached.
390 *
391 * @param r The Runnable that will be executed.
Jake Wharton820e3dd2018-01-02 22:18:24 -0500392 * @param token An instance which can be used to cancel {@code r} via
393 * {@link #removeCallbacksAndMessages}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394 * @param uptimeMillis The absolute time at which the callback should run,
395 * using the {@link android.os.SystemClock#uptimeMillis} time-base.
396 *
397 * @return Returns true if the Runnable was successfully placed in to the
398 * message queue. Returns false on failure, usually because the
399 * looper processing the message queue is exiting. Note that a
400 * result of true does not mean the Runnable will be processed -- if
401 * the looper is quit before the delivery time of the message
402 * occurs then the message will be dropped.
403 *
404 * @see android.os.SystemClock#uptimeMillis
405 */
406 public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
407 {
408 return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
409 }
410
411 /**
412 * Causes the Runnable r to be added to the message queue, to be run
413 * after the specified amount of time elapses.
414 * The runnable will be run on the thread to which this handler
415 * is attached.
David Christiea8cf4f22013-12-19 18:30:06 -0800416 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
417 * Time spent in deep sleep will add an additional delay to execution.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 *
419 * @param r The Runnable that will be executed.
420 * @param delayMillis The delay (in milliseconds) until the Runnable
421 * will be executed.
422 *
423 * @return Returns true if the Runnable was successfully placed in to the
424 * message queue. Returns false on failure, usually because the
425 * looper processing the message queue is exiting. Note that a
426 * result of true does not mean the Runnable will be processed --
427 * if the looper is quit before the delivery time of the message
428 * occurs then the message will be dropped.
429 */
430 public final boolean postDelayed(Runnable r, long delayMillis)
431 {
432 return sendMessageDelayed(getPostMessage(r), delayMillis);
433 }
434
435 /**
Jake Wharton820e3dd2018-01-02 22:18:24 -0500436 * Causes the Runnable r to be added to the message queue, to be run
437 * after the specified amount of time elapses.
438 * The runnable will be run on the thread to which this handler
439 * is attached.
440 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
441 * Time spent in deep sleep will add an additional delay to execution.
442 *
443 * @param r The Runnable that will be executed.
444 * @param token An instance which can be used to cancel {@code r} via
445 * {@link #removeCallbacksAndMessages}.
446 * @param delayMillis The delay (in milliseconds) until the Runnable
447 * will be executed.
448 *
449 * @return Returns true if the Runnable was successfully placed in to the
450 * message queue. Returns false on failure, usually because the
451 * looper processing the message queue is exiting. Note that a
452 * result of true does not mean the Runnable will be processed --
453 * if the looper is quit before the delivery time of the message
454 * occurs then the message will be dropped.
455 */
456 public final boolean postDelayed(Runnable r, Object token, long delayMillis)
457 {
458 return sendMessageDelayed(getPostMessage(r, token), delayMillis);
459 }
460
461 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 * Posts a message to an object that implements Runnable.
463 * Causes the Runnable r to executed on the next iteration through the
464 * message queue. The runnable will be run on the thread to which this
465 * handler is attached.
466 * <b>This method is only for use in very special circumstances -- it
467 * can easily starve the message queue, cause ordering problems, or have
468 * other unexpected side-effects.</b>
469 *
470 * @param r The Runnable that will be executed.
471 *
472 * @return Returns true if the message was successfully placed in to the
473 * message queue. Returns false on failure, usually because the
474 * looper processing the message queue is exiting.
475 */
476 public final boolean postAtFrontOfQueue(Runnable r)
477 {
478 return sendMessageAtFrontOfQueue(getPostMessage(r));
479 }
480
481 /**
Jeff Brownc53abc42012-08-29 04:43:25 -0700482 * Runs the specified task synchronously.
Jeff Brown8b60e452013-04-18 15:17:48 -0700483 * <p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700484 * If the current thread is the same as the handler thread, then the runnable
485 * runs immediately without being enqueued. Otherwise, posts the runnable
486 * to the handler and waits for it to complete before returning.
Jeff Brown8b60e452013-04-18 15:17:48 -0700487 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700488 * This method is dangerous! Improper use can result in deadlocks.
489 * Never call this method while any locks are held or use it in a
490 * possibly re-entrant manner.
Jeff Brown8b60e452013-04-18 15:17:48 -0700491 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700492 * This method is occasionally useful in situations where a background thread
493 * must synchronously await completion of a task that must run on the
494 * handler's thread. However, this problem is often a symptom of bad design.
495 * Consider improving the design (if possible) before resorting to this method.
Jeff Brown8b60e452013-04-18 15:17:48 -0700496 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700497 * One example of where you might want to use this method is when you just
498 * set up a Handler thread and need to perform some initialization steps on
499 * it before continuing execution.
Jeff Brown8b60e452013-04-18 15:17:48 -0700500 * </p><p>
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700501 * If timeout occurs then this method returns <code>false</code> but the runnable
502 * will remain posted on the handler and may already be in progress or
503 * complete at a later time.
Jeff Brown8b60e452013-04-18 15:17:48 -0700504 * </p><p>
505 * When using this method, be sure to use {@link Looper#quitSafely} when
506 * quitting the looper. Otherwise {@link #runWithScissors} may hang indefinitely.
507 * (TODO: We should fix this by making MessageQueue aware of blocking runnables.)
508 * </p>
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700509 *
Jeff Brownc53abc42012-08-29 04:43:25 -0700510 * @param r The Runnable that will be executed synchronously.
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700511 * @param timeout The timeout in milliseconds, or 0 to wait indefinitely.
Jeff Brownc53abc42012-08-29 04:43:25 -0700512 *
513 * @return Returns true if the Runnable was successfully executed.
514 * Returns false on failure, usually because the
515 * looper processing the message queue is exiting.
516 *
517 * @hide This method is prone to abuse and should probably not be in the API.
518 * If we ever do make it part of the API, we might want to rename it to something
519 * less funny like runUnsafe().
520 */
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700521 public final boolean runWithScissors(final Runnable r, long timeout) {
Jeff Brownc53abc42012-08-29 04:43:25 -0700522 if (r == null) {
523 throw new IllegalArgumentException("runnable must not be null");
524 }
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700525 if (timeout < 0) {
526 throw new IllegalArgumentException("timeout must be non-negative");
527 }
Jeff Brownc53abc42012-08-29 04:43:25 -0700528
529 if (Looper.myLooper() == mLooper) {
530 r.run();
531 return true;
532 }
533
534 BlockingRunnable br = new BlockingRunnable(r);
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700535 return br.postAndWait(this, timeout);
Jeff Brownc53abc42012-08-29 04:43:25 -0700536 }
537
538 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 * Remove any pending posts of Runnable r that are in the message queue.
540 */
541 public final void removeCallbacks(Runnable r)
542 {
543 mQueue.removeMessages(this, r, null);
544 }
545
546 /**
547 * Remove any pending posts of Runnable <var>r</var> with Object
Dianne Hackborn466ed242011-07-21 18:16:31 -0700548 * <var>token</var> that are in the message queue. If <var>token</var> is null,
549 * all callbacks will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 */
551 public final void removeCallbacks(Runnable r, Object token)
552 {
553 mQueue.removeMessages(this, r, token);
554 }
555
556 /**
557 * Pushes a message onto the end of the message queue after all pending messages
558 * before the current time. It will be received in {@link #handleMessage},
559 * in the thread attached to this handler.
560 *
561 * @return Returns true if the message was successfully placed in to the
562 * message queue. Returns false on failure, usually because the
563 * looper processing the message queue is exiting.
564 */
565 public final boolean sendMessage(Message msg)
566 {
567 return sendMessageDelayed(msg, 0);
568 }
569
570 /**
571 * Sends a Message containing only the what value.
572 *
573 * @return Returns true if the message was successfully placed in to the
574 * message queue. Returns false on failure, usually because the
575 * looper processing the message queue is exiting.
576 */
577 public final boolean sendEmptyMessage(int what)
578 {
579 return sendEmptyMessageDelayed(what, 0);
580 }
581
582 /**
583 * Sends a Message containing only the what value, to be delivered
584 * after the specified amount of time elapses.
585 * @see #sendMessageDelayed(android.os.Message, long)
586 *
587 * @return Returns true if the message was successfully placed in to the
588 * message queue. Returns false on failure, usually because the
589 * looper processing the message queue is exiting.
590 */
591 public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
592 Message msg = Message.obtain();
593 msg.what = what;
594 return sendMessageDelayed(msg, delayMillis);
595 }
596
597 /**
598 * Sends a Message containing only the what value, to be delivered
599 * at a specific time.
600 * @see #sendMessageAtTime(android.os.Message, long)
601 *
602 * @return Returns true if the message was successfully placed in to the
603 * message queue. Returns false on failure, usually because the
604 * looper processing the message queue is exiting.
605 */
606
607 public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
608 Message msg = Message.obtain();
609 msg.what = what;
610 return sendMessageAtTime(msg, uptimeMillis);
611 }
612
613 /**
614 * Enqueue a message into the message queue after all pending messages
615 * before (current time + delayMillis). You will receive it in
616 * {@link #handleMessage}, in the thread attached to this handler.
617 *
618 * @return Returns true if the message was successfully placed in to the
619 * message queue. Returns false on failure, usually because the
620 * looper processing the message queue is exiting. Note that a
621 * result of true does not mean the message will be processed -- if
622 * the looper is quit before the delivery time of the message
623 * occurs then the message will be dropped.
624 */
625 public final boolean sendMessageDelayed(Message msg, long delayMillis)
626 {
627 if (delayMillis < 0) {
628 delayMillis = 0;
629 }
630 return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
631 }
632
633 /**
634 * Enqueue a message into the message queue after all pending messages
635 * before the absolute time (in milliseconds) <var>uptimeMillis</var>.
636 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
David Christiea8cf4f22013-12-19 18:30:06 -0800637 * Time spent in deep sleep will add an additional delay to execution.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 * You will receive it in {@link #handleMessage}, in the thread attached
639 * to this handler.
640 *
641 * @param uptimeMillis The absolute time at which the message should be
642 * delivered, using the
643 * {@link android.os.SystemClock#uptimeMillis} time-base.
644 *
645 * @return Returns true if the message was successfully placed in to the
646 * message queue. Returns false on failure, usually because the
647 * looper processing the message queue is exiting. Note that a
648 * result of true does not mean the message will be processed -- if
649 * the looper is quit before the delivery time of the message
650 * occurs then the message will be dropped.
651 */
Jeff Brown109025d2012-08-14 20:41:30 -0700652 public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 MessageQueue queue = mQueue;
Jeff Brown109025d2012-08-14 20:41:30 -0700654 if (queue == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 RuntimeException e = new RuntimeException(
Jeff Brown109025d2012-08-14 20:41:30 -0700656 this + " sendMessageAtTime() called with no mQueue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 Log.w("Looper", e.getMessage(), e);
Jeff Brown109025d2012-08-14 20:41:30 -0700658 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 }
Jeff Brown109025d2012-08-14 20:41:30 -0700660 return enqueueMessage(queue, msg, uptimeMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 }
662
663 /**
664 * Enqueue a message at the front of the message queue, to be processed on
665 * the next iteration of the message loop. You will receive it in
666 * {@link #handleMessage}, in the thread attached to this handler.
667 * <b>This method is only for use in very special circumstances -- it
668 * can easily starve the message queue, cause ordering problems, or have
669 * other unexpected side-effects.</b>
670 *
671 * @return Returns true if the message was successfully placed in to the
672 * message queue. Returns false on failure, usually because the
673 * looper processing the message queue is exiting.
674 */
Jeff Brown109025d2012-08-14 20:41:30 -0700675 public final boolean sendMessageAtFrontOfQueue(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 MessageQueue queue = mQueue;
Jeff Brown109025d2012-08-14 20:41:30 -0700677 if (queue == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 RuntimeException e = new RuntimeException(
679 this + " sendMessageAtTime() called with no mQueue");
680 Log.w("Looper", e.getMessage(), e);
Jeff Brown109025d2012-08-14 20:41:30 -0700681 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 }
Jeff Brown109025d2012-08-14 20:41:30 -0700683 return enqueueMessage(queue, msg, 0);
684 }
685
686 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
687 msg.target = this;
688 if (mAsynchronous) {
689 msg.setAsynchronous(true);
690 }
691 return queue.enqueueMessage(msg, uptimeMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 }
693
694 /**
695 * Remove any pending posts of messages with code 'what' that are in the
696 * message queue.
697 */
698 public final void removeMessages(int what) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800699 mQueue.removeMessages(this, what, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 }
701
702 /**
703 * Remove any pending posts of messages with code 'what' and whose obj is
Jeff Brown32c81132012-04-30 16:28:32 -0700704 * 'object' that are in the message queue. If <var>object</var> is null,
Dianne Hackborn466ed242011-07-21 18:16:31 -0700705 * all messages will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 */
707 public final void removeMessages(int what, Object object) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800708 mQueue.removeMessages(this, what, object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 }
710
711 /**
712 * Remove any pending posts of callbacks and sent messages whose
Dianne Hackborn466ed242011-07-21 18:16:31 -0700713 * <var>obj</var> is <var>token</var>. If <var>token</var> is null,
714 * all callbacks and messages will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 */
716 public final void removeCallbacksAndMessages(Object token) {
717 mQueue.removeCallbacksAndMessages(this, token);
718 }
719
720 /**
721 * Check if there are any pending posts of messages with code 'what' in
722 * the message queue.
723 */
724 public final boolean hasMessages(int what) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800725 return mQueue.hasMessages(this, what, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 }
727
728 /**
Dianne Hackborncb015632017-06-14 17:30:15 -0700729 * Return whether there are any messages or callbacks currently scheduled on this handler.
730 * @hide
731 */
732 public final boolean hasMessagesOrCallbacks() {
733 return mQueue.hasMessages(this);
734 }
735
736 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 * Check if there are any pending posts of messages with code 'what' and
738 * whose obj is 'object' in the message queue.
739 */
740 public final boolean hasMessages(int what, Object object) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800741 return mQueue.hasMessages(this, what, object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 }
743
Romain Guyba6be8a2012-04-23 18:22:09 -0700744 /**
745 * Check if there are any pending posts of messages with callback r in
746 * the message queue.
747 *
748 * @hide
749 */
750 public final boolean hasCallbacks(Runnable r) {
751 return mQueue.hasMessages(this, r, null);
752 }
753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 // if we can get rid of this method, the handler need not remember its loop
755 // we could instead export a getMessageQueue() method...
756 public final Looper getLooper() {
757 return mLooper;
758 }
759
760 public final void dump(Printer pw, String prefix) {
761 pw.println(prefix + this + " @ " + SystemClock.uptimeMillis());
762 if (mLooper == null) {
763 pw.println(prefix + "looper uninitialized");
764 } else {
765 mLooper.dump(pw, prefix + " ");
766 }
767 }
768
Dianne Hackborncb015632017-06-14 17:30:15 -0700769 /**
770 * @hide
771 */
772 public final void dumpMine(Printer pw, String prefix) {
773 pw.println(prefix + this + " @ " + SystemClock.uptimeMillis());
774 if (mLooper == null) {
775 pw.println(prefix + "looper uninitialized");
776 } else {
777 mLooper.dump(pw, prefix + " ", this);
778 }
779 }
780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 @Override
782 public String toString() {
Kristian Monsen588d8562011-08-04 12:55:33 +0100783 return "Handler (" + getClass().getName() + ") {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 + Integer.toHexString(System.identityHashCode(this))
785 + "}";
786 }
787
788 final IMessenger getIMessenger() {
789 synchronized (mQueue) {
790 if (mMessenger != null) {
791 return mMessenger;
792 }
793 mMessenger = new MessengerImpl();
794 return mMessenger;
795 }
796 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 private final class MessengerImpl extends IMessenger.Stub {
799 public void send(Message msg) {
Dianne Hackborncb3ed1d2014-06-27 18:37:06 -0700800 msg.sendingUid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 Handler.this.sendMessage(msg);
802 }
803 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700804
Romain Guyba6be8a2012-04-23 18:22:09 -0700805 private static Message getPostMessage(Runnable r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 Message m = Message.obtain();
807 m.callback = r;
808 return m;
809 }
810
Romain Guyba6be8a2012-04-23 18:22:09 -0700811 private static Message getPostMessage(Runnable r, Object token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 Message m = Message.obtain();
813 m.obj = token;
814 m.callback = r;
815 return m;
816 }
817
Romain Guyba6be8a2012-04-23 18:22:09 -0700818 private static void handleCallback(Message message) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 message.callback.run();
820 }
821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 final Looper mLooper;
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600823 final MessageQueue mQueue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 final Callback mCallback;
Jeff Brown109025d2012-08-14 20:41:30 -0700825 final boolean mAsynchronous;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 IMessenger mMessenger;
Jeff Brownc53abc42012-08-29 04:43:25 -0700827
828 private static final class BlockingRunnable implements Runnable {
829 private final Runnable mTask;
830 private boolean mDone;
831
832 public BlockingRunnable(Runnable task) {
833 mTask = task;
834 }
835
836 @Override
837 public void run() {
838 try {
839 mTask.run();
840 } finally {
841 synchronized (this) {
842 mDone = true;
843 notifyAll();
844 }
845 }
846 }
847
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700848 public boolean postAndWait(Handler handler, long timeout) {
Jeff Brownc53abc42012-08-29 04:43:25 -0700849 if (!handler.post(this)) {
850 return false;
851 }
852
853 synchronized (this) {
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700854 if (timeout > 0) {
855 final long expirationTime = SystemClock.uptimeMillis() + timeout;
856 while (!mDone) {
857 long delay = expirationTime - SystemClock.uptimeMillis();
858 if (delay <= 0) {
859 return false; // timeout
860 }
861 try {
862 wait(delay);
863 } catch (InterruptedException ex) {
864 }
865 }
866 } else {
867 while (!mDone) {
868 try {
869 wait();
870 } catch (InterruptedException ex) {
871 }
Jeff Brownc53abc42012-08-29 04:43:25 -0700872 }
873 }
874 }
875 return true;
876 }
877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878}