blob: e6c12c7972a2cbd08eb72e9f1b4b762080eb0925 [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
kopriva9b5c0392018-09-10 14:02:58 -070036 * runnables to be executed at some point in the future; and (2) to enqueue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037 * 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
Adam Powell8709ba82018-02-21 10:18:25 -0800223 * the synchronization barriers introduced by conditions such as display vsync.
Jeff Brown109025d2012-08-14 20:41:30 -0700224 *
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
Adam Powell8709ba82018-02-21 10:18:25 -0800239 /**
240 * Create a new Handler whose posted messages and runnables are not subject to
241 * synchronization barriers such as display vsync.
242 *
243 * <p>Messages sent to an async handler are guaranteed to be ordered with respect to one another,
244 * but not necessarily with respect to messages from other Handlers.</p>
245 *
246 * @see #createAsync(Looper, Callback) to create an async Handler with custom message handling.
247 *
248 * @param looper the Looper that the new Handler should be bound to
249 * @return a new async Handler instance
250 */
251 @NonNull
252 public static Handler createAsync(@NonNull Looper looper) {
253 if (looper == null) throw new NullPointerException("looper must not be null");
254 return new Handler(looper, null, true);
255 }
256
257 /**
258 * Create a new Handler whose posted messages and runnables are not subject to
259 * synchronization barriers such as display vsync.
260 *
261 * <p>Messages sent to an async handler are guaranteed to be ordered with respect to one another,
262 * but not necessarily with respect to messages from other Handlers.</p>
263 *
264 * @see #createAsync(Looper) to create an async Handler without custom message handling.
265 *
266 * @param looper the Looper that the new Handler should be bound to
267 * @return a new async Handler instance
268 */
269 @NonNull
270 public static Handler createAsync(@NonNull Looper looper, @NonNull Callback callback) {
271 if (looper == null) throw new NullPointerException("looper must not be null");
272 if (callback == null) throw new NullPointerException("callback must not be null");
273 return new Handler(looper, callback, true);
274 }
275
Eugene Suslaa38fbf62017-03-14 10:26:10 -0700276 /** @hide */
277 @NonNull
278 public static Handler getMain() {
279 if (MAIN_THREAD_HANDLER == null) {
280 MAIN_THREAD_HANDLER = new Handler(Looper.getMainLooper());
281 }
282 return MAIN_THREAD_HANDLER;
283 }
284
285 /** @hide */
286 @NonNull
287 public static Handler mainIfNull(@Nullable Handler handler) {
288 return handler == null ? getMain() : handler;
289 }
290
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600291 /** {@hide} */
292 public String getTraceName(Message message) {
293 final StringBuilder sb = new StringBuilder();
294 sb.append(getClass().getName()).append(": ");
295 if (message.callback != null) {
296 sb.append(message.callback.getClass().getName());
297 } else {
298 sb.append("#").append(message.what);
299 }
300 return sb.toString();
301 }
302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 /**
Romain Guyf9284692011-07-13 18:46:21 -0700304 * Returns a string representing the name of the specified message.
305 * The default implementation will either return the class name of the
306 * message callback if any, or the hexadecimal representation of the
307 * message "what" field.
308 *
309 * @param message The message whose name is being queried
310 */
311 public String getMessageName(Message message) {
312 if (message.callback != null) {
313 return message.callback.getClass().getName();
314 }
315 return "0x" + Integer.toHexString(message.what);
316 }
317
318 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 * Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
320 * creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
321 * If you don't want that facility, just call Message.obtain() instead.
322 */
323 public final Message obtainMessage()
324 {
325 return Message.obtain(this);
326 }
327
328 /**
329 * Same as {@link #obtainMessage()}, except that it also sets the what member of the returned Message.
330 *
331 * @param what Value to assign to the returned Message.what field.
332 * @return A Message from the global message pool.
333 */
334 public final Message obtainMessage(int what)
335 {
336 return Message.obtain(this, what);
337 }
338
339 /**
340 *
341 * Same as {@link #obtainMessage()}, except that it also sets the what and obj members
342 * of the returned Message.
343 *
344 * @param what Value to assign to the returned Message.what field.
345 * @param obj Value to assign to the returned Message.obj field.
346 * @return A Message from the global message pool.
347 */
348 public final Message obtainMessage(int what, Object obj)
349 {
350 return Message.obtain(this, what, obj);
351 }
352
353 /**
354 *
355 * Same as {@link #obtainMessage()}, except that it also sets the what, arg1 and arg2 members of the returned
356 * Message.
357 * @param what Value to assign to the returned Message.what field.
358 * @param arg1 Value to assign to the returned Message.arg1 field.
359 * @param arg2 Value to assign to the returned Message.arg2 field.
360 * @return A Message from the global message pool.
361 */
362 public final Message obtainMessage(int what, int arg1, int arg2)
363 {
364 return Message.obtain(this, what, arg1, arg2);
365 }
366
367 /**
368 *
369 * Same as {@link #obtainMessage()}, except that it also sets the what, obj, arg1,and arg2 values on the
370 * returned Message.
371 * @param what Value to assign to the returned Message.what field.
372 * @param arg1 Value to assign to the returned Message.arg1 field.
373 * @param arg2 Value to assign to the returned Message.arg2 field.
374 * @param obj Value to assign to the returned Message.obj field.
375 * @return A Message from the global message pool.
376 */
377 public final Message obtainMessage(int what, int arg1, int arg2, Object obj)
378 {
379 return Message.obtain(this, what, arg1, arg2, obj);
380 }
381
382 /**
383 * Causes the Runnable r to be added to the message queue.
384 * The runnable will be run on the thread to which this handler is
385 * attached.
386 *
387 * @param r The Runnable that 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.
392 */
393 public final boolean post(Runnable r)
394 {
395 return sendMessageDelayed(getPostMessage(r), 0);
396 }
397
398 /**
399 * Causes the Runnable r to be added to the message queue, to be run
400 * at a specific time given by <var>uptimeMillis</var>.
401 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
David Christiea8cf4f22013-12-19 18:30:06 -0800402 * Time spent in deep sleep will add an additional delay to execution.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 * The runnable will be run on the thread to which this handler is attached.
404 *
405 * @param r The Runnable that will be executed.
406 * @param uptimeMillis The absolute time at which the callback should run,
407 * using the {@link android.os.SystemClock#uptimeMillis} time-base.
408 *
409 * @return Returns true if the Runnable was successfully placed in to the
410 * message queue. Returns false on failure, usually because the
411 * looper processing the message queue is exiting. Note that a
412 * result of true does not mean the Runnable will be processed -- if
413 * the looper is quit before the delivery time of the message
414 * occurs then the message will be dropped.
415 */
416 public final boolean postAtTime(Runnable r, long uptimeMillis)
417 {
418 return sendMessageAtTime(getPostMessage(r), uptimeMillis);
419 }
420
421 /**
422 * Causes the Runnable r to be added to the message queue, to be run
423 * at a specific time given by <var>uptimeMillis</var>.
424 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
David Christiea8cf4f22013-12-19 18:30:06 -0800425 * Time spent in deep sleep will add an additional delay to execution.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 * The runnable will be run on the thread to which this handler is attached.
427 *
428 * @param r The Runnable that will be executed.
Jake Wharton820e3dd2018-01-02 22:18:24 -0500429 * @param token An instance which can be used to cancel {@code r} via
430 * {@link #removeCallbacksAndMessages}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 * @param uptimeMillis The absolute time at which the callback should run,
432 * using the {@link android.os.SystemClock#uptimeMillis} time-base.
433 *
434 * @return Returns true if the Runnable was successfully placed in to the
435 * message queue. Returns false on failure, usually because the
436 * looper processing the message queue is exiting. Note that a
437 * result of true does not mean the Runnable will be processed -- if
438 * the looper is quit before the delivery time of the message
439 * occurs then the message will be dropped.
440 *
441 * @see android.os.SystemClock#uptimeMillis
442 */
443 public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
444 {
445 return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
446 }
447
448 /**
449 * Causes the Runnable r to be added to the message queue, to be run
450 * after the specified amount of time elapses.
451 * The runnable will be run on the thread to which this handler
452 * is attached.
David Christiea8cf4f22013-12-19 18:30:06 -0800453 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
454 * Time spent in deep sleep will add an additional delay to execution.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 *
456 * @param r The Runnable that will be executed.
457 * @param delayMillis The delay (in milliseconds) until the Runnable
458 * will be executed.
459 *
460 * @return Returns true if the Runnable was successfully placed in to the
461 * message queue. Returns false on failure, usually because the
462 * looper processing the message queue is exiting. Note that a
463 * result of true does not mean the Runnable will be processed --
464 * if the looper is quit before the delivery time of the message
465 * occurs then the message will be dropped.
466 */
467 public final boolean postDelayed(Runnable r, long delayMillis)
468 {
469 return sendMessageDelayed(getPostMessage(r), delayMillis);
470 }
471
Felipe Leme3fe6e922019-02-04 17:52:27 -0800472 /** @hide */
473 public final boolean postDelayed(Runnable r, int what, long delayMillis) {
474 return sendMessageDelayed(getPostMessage(r).setWhat(what), delayMillis);
475 }
476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 /**
Jake Wharton820e3dd2018-01-02 22:18:24 -0500478 * Causes the Runnable r to be added to the message queue, to be run
479 * after the specified amount of time elapses.
480 * The runnable will be run on the thread to which this handler
481 * is attached.
482 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
483 * Time spent in deep sleep will add an additional delay to execution.
484 *
485 * @param r The Runnable that will be executed.
486 * @param token An instance which can be used to cancel {@code r} via
487 * {@link #removeCallbacksAndMessages}.
488 * @param delayMillis The delay (in milliseconds) until the Runnable
489 * will be executed.
490 *
491 * @return Returns true if the Runnable was successfully placed in to the
492 * message queue. Returns false on failure, usually because the
493 * looper processing the message queue is exiting. Note that a
494 * result of true does not mean the Runnable will be processed --
495 * if the looper is quit before the delivery time of the message
496 * occurs then the message will be dropped.
497 */
498 public final boolean postDelayed(Runnable r, Object token, long delayMillis)
499 {
500 return sendMessageDelayed(getPostMessage(r, token), delayMillis);
501 }
502
503 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 * Posts a message to an object that implements Runnable.
505 * Causes the Runnable r to executed on the next iteration through the
506 * message queue. The runnable will be run on the thread to which this
507 * handler is attached.
508 * <b>This method is only for use in very special circumstances -- it
509 * can easily starve the message queue, cause ordering problems, or have
510 * other unexpected side-effects.</b>
511 *
512 * @param r The Runnable that will be executed.
513 *
514 * @return Returns true if the message was successfully placed in to the
515 * message queue. Returns false on failure, usually because the
516 * looper processing the message queue is exiting.
517 */
518 public final boolean postAtFrontOfQueue(Runnable r)
519 {
520 return sendMessageAtFrontOfQueue(getPostMessage(r));
521 }
522
523 /**
Jeff Brownc53abc42012-08-29 04:43:25 -0700524 * Runs the specified task synchronously.
Jeff Brown8b60e452013-04-18 15:17:48 -0700525 * <p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700526 * If the current thread is the same as the handler thread, then the runnable
527 * runs immediately without being enqueued. Otherwise, posts the runnable
528 * to the handler and waits for it to complete before returning.
Jeff Brown8b60e452013-04-18 15:17:48 -0700529 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700530 * This method is dangerous! Improper use can result in deadlocks.
531 * Never call this method while any locks are held or use it in a
532 * possibly re-entrant manner.
Jeff Brown8b60e452013-04-18 15:17:48 -0700533 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700534 * This method is occasionally useful in situations where a background thread
535 * must synchronously await completion of a task that must run on the
536 * handler's thread. However, this problem is often a symptom of bad design.
537 * Consider improving the design (if possible) before resorting to this method.
Jeff Brown8b60e452013-04-18 15:17:48 -0700538 * </p><p>
Jeff Brownc53abc42012-08-29 04:43:25 -0700539 * One example of where you might want to use this method is when you just
540 * set up a Handler thread and need to perform some initialization steps on
541 * it before continuing execution.
Jeff Brown8b60e452013-04-18 15:17:48 -0700542 * </p><p>
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700543 * If timeout occurs then this method returns <code>false</code> but the runnable
544 * will remain posted on the handler and may already be in progress or
545 * complete at a later time.
Jeff Brown8b60e452013-04-18 15:17:48 -0700546 * </p><p>
547 * When using this method, be sure to use {@link Looper#quitSafely} when
548 * quitting the looper. Otherwise {@link #runWithScissors} may hang indefinitely.
549 * (TODO: We should fix this by making MessageQueue aware of blocking runnables.)
550 * </p>
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700551 *
Jeff Brownc53abc42012-08-29 04:43:25 -0700552 * @param r The Runnable that will be executed synchronously.
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700553 * @param timeout The timeout in milliseconds, or 0 to wait indefinitely.
Jeff Brownc53abc42012-08-29 04:43:25 -0700554 *
555 * @return Returns true if the Runnable was successfully executed.
556 * Returns false on failure, usually because the
557 * looper processing the message queue is exiting.
558 *
559 * @hide This method is prone to abuse and should probably not be in the API.
560 * If we ever do make it part of the API, we might want to rename it to something
561 * less funny like runUnsafe().
562 */
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700563 public final boolean runWithScissors(final Runnable r, long timeout) {
Jeff Brownc53abc42012-08-29 04:43:25 -0700564 if (r == null) {
565 throw new IllegalArgumentException("runnable must not be null");
566 }
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700567 if (timeout < 0) {
568 throw new IllegalArgumentException("timeout must be non-negative");
569 }
Jeff Brownc53abc42012-08-29 04:43:25 -0700570
571 if (Looper.myLooper() == mLooper) {
572 r.run();
573 return true;
574 }
575
576 BlockingRunnable br = new BlockingRunnable(r);
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700577 return br.postAndWait(this, timeout);
Jeff Brownc53abc42012-08-29 04:43:25 -0700578 }
579
580 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 * Remove any pending posts of Runnable r that are in the message queue.
582 */
583 public final void removeCallbacks(Runnable r)
584 {
585 mQueue.removeMessages(this, r, null);
586 }
587
588 /**
589 * Remove any pending posts of Runnable <var>r</var> with Object
Dianne Hackborn466ed242011-07-21 18:16:31 -0700590 * <var>token</var> that are in the message queue. If <var>token</var> is null,
591 * all callbacks will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 */
593 public final void removeCallbacks(Runnable r, Object token)
594 {
595 mQueue.removeMessages(this, r, token);
596 }
597
598 /**
599 * Pushes a message onto the end of the message queue after all pending messages
600 * before the current time. It will be received in {@link #handleMessage},
601 * in the thread attached to this handler.
602 *
603 * @return Returns true if the message was successfully placed in to the
604 * message queue. Returns false on failure, usually because the
605 * looper processing the message queue is exiting.
606 */
607 public final boolean sendMessage(Message msg)
608 {
609 return sendMessageDelayed(msg, 0);
610 }
611
612 /**
613 * Sends a Message containing only the what value.
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.
618 */
619 public final boolean sendEmptyMessage(int what)
620 {
621 return sendEmptyMessageDelayed(what, 0);
622 }
623
624 /**
625 * Sends a Message containing only the what value, to be delivered
626 * after the specified amount of time elapses.
627 * @see #sendMessageDelayed(android.os.Message, long)
628 *
629 * @return Returns true if the message was successfully placed in to the
630 * message queue. Returns false on failure, usually because the
631 * looper processing the message queue is exiting.
632 */
633 public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
634 Message msg = Message.obtain();
635 msg.what = what;
636 return sendMessageDelayed(msg, delayMillis);
637 }
638
639 /**
640 * Sends a Message containing only the what value, to be delivered
641 * at a specific time.
642 * @see #sendMessageAtTime(android.os.Message, long)
643 *
644 * @return Returns true if the message was successfully placed in to the
645 * message queue. Returns false on failure, usually because the
646 * looper processing the message queue is exiting.
647 */
648
649 public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
650 Message msg = Message.obtain();
651 msg.what = what;
652 return sendMessageAtTime(msg, uptimeMillis);
653 }
654
655 /**
656 * Enqueue a message into the message queue after all pending messages
657 * before (current time + delayMillis). You will receive it in
658 * {@link #handleMessage}, in the thread attached to this handler.
659 *
660 * @return Returns true if the message was successfully placed in to the
661 * message queue. Returns false on failure, usually because the
662 * looper processing the message queue is exiting. Note that a
663 * result of true does not mean the message will be processed -- if
664 * the looper is quit before the delivery time of the message
665 * occurs then the message will be dropped.
666 */
667 public final boolean sendMessageDelayed(Message msg, long delayMillis)
668 {
669 if (delayMillis < 0) {
670 delayMillis = 0;
671 }
672 return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
673 }
674
675 /**
676 * Enqueue a message into the message queue after all pending messages
677 * before the absolute time (in milliseconds) <var>uptimeMillis</var>.
678 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
David Christiea8cf4f22013-12-19 18:30:06 -0800679 * Time spent in deep sleep will add an additional delay to execution.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 * You will receive it in {@link #handleMessage}, in the thread attached
681 * to this handler.
682 *
683 * @param uptimeMillis The absolute time at which the message should be
684 * delivered, using the
685 * {@link android.os.SystemClock#uptimeMillis} time-base.
686 *
687 * @return Returns true if the message was successfully placed in to the
688 * message queue. Returns false on failure, usually because the
689 * looper processing the message queue is exiting. Note that a
690 * result of true does not mean the message will be processed -- if
691 * the looper is quit before the delivery time of the message
692 * occurs then the message will be dropped.
693 */
Jeff Brown109025d2012-08-14 20:41:30 -0700694 public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 MessageQueue queue = mQueue;
Jeff Brown109025d2012-08-14 20:41:30 -0700696 if (queue == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 RuntimeException e = new RuntimeException(
Jeff Brown109025d2012-08-14 20:41:30 -0700698 this + " sendMessageAtTime() called with no mQueue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 Log.w("Looper", e.getMessage(), e);
Jeff Brown109025d2012-08-14 20:41:30 -0700700 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 }
Jeff Brown109025d2012-08-14 20:41:30 -0700702 return enqueueMessage(queue, msg, uptimeMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 }
704
705 /**
706 * Enqueue a message at the front of the message queue, to be processed on
707 * the next iteration of the message loop. You will receive it in
708 * {@link #handleMessage}, in the thread attached to this handler.
709 * <b>This method is only for use in very special circumstances -- it
710 * can easily starve the message queue, cause ordering problems, or have
711 * other unexpected side-effects.</b>
712 *
713 * @return Returns true if the message was successfully placed in to the
714 * message queue. Returns false on failure, usually because the
715 * looper processing the message queue is exiting.
716 */
Jeff Brown109025d2012-08-14 20:41:30 -0700717 public final boolean sendMessageAtFrontOfQueue(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 MessageQueue queue = mQueue;
Jeff Brown109025d2012-08-14 20:41:30 -0700719 if (queue == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 RuntimeException e = new RuntimeException(
721 this + " sendMessageAtTime() called with no mQueue");
722 Log.w("Looper", e.getMessage(), e);
Jeff Brown109025d2012-08-14 20:41:30 -0700723 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 }
Jeff Brown109025d2012-08-14 20:41:30 -0700725 return enqueueMessage(queue, msg, 0);
726 }
727
Eugene Susla9f35ca92018-02-12 16:17:26 -0800728 /**
729 * Executes the message synchronously if called on the same thread this handler corresponds to,
730 * or {@link #sendMessage pushes it to the queue} otherwise
731 *
732 * @return Returns true if the message was successfully ran or placed in to the
733 * message queue. Returns false on failure, usually because the
734 * looper processing the message queue is exiting.
735 * @hide
736 */
737 public final boolean executeOrSendMessage(Message msg) {
738 if (mLooper == Looper.myLooper()) {
739 dispatchMessage(msg);
740 return true;
741 }
742 return sendMessage(msg);
743 }
744
Jeff Brown109025d2012-08-14 20:41:30 -0700745 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
746 msg.target = this;
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000747 msg.workSourceUid = ThreadLocalWorkSource.getUid();
Marcin Oczeretkoec758722018-09-12 12:53:47 +0100748
Jeff Brown109025d2012-08-14 20:41:30 -0700749 if (mAsynchronous) {
750 msg.setAsynchronous(true);
751 }
752 return queue.enqueueMessage(msg, uptimeMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 }
754
755 /**
756 * Remove any pending posts of messages with code 'what' that are in the
757 * message queue.
758 */
759 public final void removeMessages(int what) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800760 mQueue.removeMessages(this, what, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 }
762
763 /**
764 * Remove any pending posts of messages with code 'what' and whose obj is
Jeff Brown32c81132012-04-30 16:28:32 -0700765 * 'object' that are in the message queue. If <var>object</var> is null,
Dianne Hackborn466ed242011-07-21 18:16:31 -0700766 * all messages will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 */
768 public final void removeMessages(int what, Object object) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800769 mQueue.removeMessages(this, what, object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 }
771
772 /**
773 * Remove any pending posts of callbacks and sent messages whose
Dianne Hackborn466ed242011-07-21 18:16:31 -0700774 * <var>obj</var> is <var>token</var>. If <var>token</var> is null,
775 * all callbacks and messages will be removed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 */
777 public final void removeCallbacksAndMessages(Object token) {
778 mQueue.removeCallbacksAndMessages(this, token);
779 }
780
781 /**
782 * Check if there are any pending posts of messages with code 'what' in
783 * the message queue.
784 */
785 public final boolean hasMessages(int what) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800786 return mQueue.hasMessages(this, what, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 }
788
789 /**
Dianne Hackborncb015632017-06-14 17:30:15 -0700790 * Return whether there are any messages or callbacks currently scheduled on this handler.
791 * @hide
792 */
793 public final boolean hasMessagesOrCallbacks() {
794 return mQueue.hasMessages(this);
795 }
796
797 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 * Check if there are any pending posts of messages with code 'what' and
799 * whose obj is 'object' in the message queue.
800 */
801 public final boolean hasMessages(int what, Object object) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800802 return mQueue.hasMessages(this, what, object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 }
804
Romain Guyba6be8a2012-04-23 18:22:09 -0700805 /**
806 * Check if there are any pending posts of messages with callback r in
807 * the message queue.
Romain Guyba6be8a2012-04-23 18:22:09 -0700808 */
809 public final boolean hasCallbacks(Runnable r) {
810 return mQueue.hasMessages(this, r, null);
811 }
812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 // if we can get rid of this method, the handler need not remember its loop
814 // we could instead export a getMessageQueue() method...
815 public final Looper getLooper() {
816 return mLooper;
817 }
818
819 public final void dump(Printer pw, String prefix) {
820 pw.println(prefix + this + " @ " + SystemClock.uptimeMillis());
821 if (mLooper == null) {
822 pw.println(prefix + "looper uninitialized");
823 } else {
824 mLooper.dump(pw, prefix + " ");
825 }
826 }
827
Dianne Hackborncb015632017-06-14 17:30:15 -0700828 /**
829 * @hide
830 */
831 public final void dumpMine(Printer pw, String prefix) {
832 pw.println(prefix + this + " @ " + SystemClock.uptimeMillis());
833 if (mLooper == null) {
834 pw.println(prefix + "looper uninitialized");
835 } else {
836 mLooper.dump(pw, prefix + " ", this);
837 }
838 }
839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 @Override
841 public String toString() {
Kristian Monsen588d8562011-08-04 12:55:33 +0100842 return "Handler (" + getClass().getName() + ") {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 + Integer.toHexString(System.identityHashCode(this))
844 + "}";
845 }
846
847 final IMessenger getIMessenger() {
848 synchronized (mQueue) {
849 if (mMessenger != null) {
850 return mMessenger;
851 }
852 mMessenger = new MessengerImpl();
853 return mMessenger;
854 }
855 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 private final class MessengerImpl extends IMessenger.Stub {
858 public void send(Message msg) {
Dianne Hackborncb3ed1d2014-06-27 18:37:06 -0700859 msg.sendingUid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 Handler.this.sendMessage(msg);
861 }
862 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700863
Romain Guyba6be8a2012-04-23 18:22:09 -0700864 private static Message getPostMessage(Runnable r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 Message m = Message.obtain();
866 m.callback = r;
867 return m;
868 }
869
Romain Guyba6be8a2012-04-23 18:22:09 -0700870 private static Message getPostMessage(Runnable r, Object token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 Message m = Message.obtain();
872 m.obj = token;
873 m.callback = r;
874 return m;
875 }
876
Romain Guyba6be8a2012-04-23 18:22:09 -0700877 private static void handleCallback(Message message) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 message.callback.run();
879 }
880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 final Looper mLooper;
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600882 final MessageQueue mQueue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 final Callback mCallback;
Jeff Brown109025d2012-08-14 20:41:30 -0700884 final boolean mAsynchronous;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 IMessenger mMessenger;
Jeff Brownc53abc42012-08-29 04:43:25 -0700886
887 private static final class BlockingRunnable implements Runnable {
888 private final Runnable mTask;
889 private boolean mDone;
890
891 public BlockingRunnable(Runnable task) {
892 mTask = task;
893 }
894
895 @Override
896 public void run() {
897 try {
898 mTask.run();
899 } finally {
900 synchronized (this) {
901 mDone = true;
902 notifyAll();
903 }
904 }
905 }
906
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700907 public boolean postAndWait(Handler handler, long timeout) {
Jeff Brownc53abc42012-08-29 04:43:25 -0700908 if (!handler.post(this)) {
909 return false;
910 }
911
912 synchronized (this) {
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700913 if (timeout > 0) {
914 final long expirationTime = SystemClock.uptimeMillis() + timeout;
915 while (!mDone) {
916 long delay = expirationTime - SystemClock.uptimeMillis();
917 if (delay <= 0) {
918 return false; // timeout
919 }
920 try {
921 wait(delay);
922 } catch (InterruptedException ex) {
923 }
924 }
925 } else {
926 while (!mDone) {
927 try {
928 wait();
929 } catch (InterruptedException ex) {
930 }
Jeff Brownc53abc42012-08-29 04:43:25 -0700931 }
932 }
933 }
934 return true;
935 }
936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937}