blob: 684a8ee43c870e57e1ba93623316d2f349af3603 [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
Jeff Brown803c2af2015-03-05 10:52:53 -080019import android.annotation.NonNull;
20import android.annotation.Nullable;
Netta P958d0a52017-02-07 11:20:55 -080021import android.os.LooperProto;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080022import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.util.Printer;
Makoto Onuki99571512017-03-28 14:12:34 -070024import android.util.Slog;
Netta P958d0a52017-02-07 11:20:55 -080025import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
27/**
28 * Class used to run a message loop for a thread. Threads by default do
29 * not have a message loop associated with them; to create one, call
30 * {@link #prepare} in the thread that is to run the loop, and then
31 * {@link #loop} to have it process messages until the loop is stopped.
Jeff Brown803c2af2015-03-05 10:52:53 -080032 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033 * <p>Most interaction with a message loop is through the
34 * {@link Handler} class.
Jeff Brown803c2af2015-03-05 10:52:53 -080035 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036 * <p>This is a typical example of the implementation of a Looper thread,
37 * using the separation of {@link #prepare} and {@link #loop} to create an
38 * initial Handler to communicate with the Looper.
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080039 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040 * <pre>
41 * class LooperThread extends Thread {
42 * public Handler mHandler;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080043 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044 * public void run() {
45 * Looper.prepare();
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080046 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047 * mHandler = new Handler() {
48 * public void handleMessage(Message msg) {
49 * // process incoming messages here
50 * }
51 * };
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080052 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053 * Looper.loop();
54 * }
55 * }</pre>
56 */
Jeff Brown67fc67c2013-04-01 13:00:33 -070057public final class Looper {
Jeff Brown6c7b41a2015-02-26 14:43:53 -080058 /*
59 * API Implementation Note:
60 *
61 * This class contains the code required to set up and manage an event loop
62 * based on MessageQueue. APIs that affect the state of the queue should be
63 * defined on MessageQueue or Handler rather than on Looper itself. For example,
64 * idle handlers and sync barriers are defined on the queue whereas preparing the
Jeff Brown803c2af2015-03-05 10:52:53 -080065 * thread, looping, and quitting are defined on the looper.
Jeff Brown6c7b41a2015-02-26 14:43:53 -080066 */
67
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080068 private static final String TAG = "Looper";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
70 // sThreadLocal.get() will return null unless you've called prepare().
Xavier Ducrohet7f9f99ea2011-08-11 10:16:17 -070071 static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
Jeff Brown0f85ce32012-02-16 14:41:10 -080072 private static Looper sMainLooper; // guarded by Looper.class
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073
74 final MessageQueue mQueue;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080075 final Thread mThread;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080076
Jeff Brown0f85ce32012-02-16 14:41:10 -080077 private Printer mLogging;
Jeff Sharkey74cd3de2016-04-06 17:40:54 -060078 private long mTraceTag;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080079
Makoto Onuki712886f2018-04-27 15:22:50 -070080 /**
81 * If set, the looper will show a warning log if a message dispatch takes longer than this.
82 */
Makoto Onuki99571512017-03-28 14:12:34 -070083 private long mSlowDispatchThresholdMs;
84
Makoto Onuki712886f2018-04-27 15:22:50 -070085 /**
86 * If set, the looper will show a warning log if a message delivery (actual delivery time -
87 * post time) takes longer than this.
88 */
89 private long mSlowDeliveryThresholdMs;
90
91 /** Initialize the current thread as a looper.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 * This gives you a chance to create handlers that then reference
93 * this looper, before actually starting the loop. Be sure to call
94 * {@link #loop()} after calling this method, and end it by calling
95 * {@link #quit()}.
96 */
Romain Guyf9284692011-07-13 18:46:21 -070097 public static void prepare() {
Jeff Brown0f85ce32012-02-16 14:41:10 -080098 prepare(true);
99 }
100
101 private static void prepare(boolean quitAllowed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 if (sThreadLocal.get() != null) {
103 throw new RuntimeException("Only one Looper may be created per thread");
104 }
Jeff Brown0f85ce32012-02-16 14:41:10 -0800105 sThreadLocal.set(new Looper(quitAllowed));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800107
108 /**
109 * Initialize the current thread as a looper, marking it as an
110 * application's main looper. The main looper for your application
111 * is created by the Android environment, so you should never need
112 * to call this function yourself. See also: {@link #prepare()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 */
Romain Guyf9284692011-07-13 18:46:21 -0700114 public static void prepareMainLooper() {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800115 prepare(false);
116 synchronized (Looper.class) {
117 if (sMainLooper != null) {
118 throw new IllegalStateException("The main Looper has already been prepared.");
119 }
120 sMainLooper = myLooper();
121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800123
Jeff Brown803c2af2015-03-05 10:52:53 -0800124 /**
125 * Returns the application's main looper, which lives in the main thread of the application.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 */
Jeff Brown0f85ce32012-02-16 14:41:10 -0800127 public static Looper getMainLooper() {
128 synchronized (Looper.class) {
129 return sMainLooper;
130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 }
132
133 /**
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800134 * Run the message queue in this thread. Be sure to call
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 * {@link #quit()} to end the loop.
136 */
Romain Guyf9284692011-07-13 18:46:21 -0700137 public static void loop() {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800138 final Looper me = myLooper();
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800139 if (me == null) {
140 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
141 }
Jeff Brown0f85ce32012-02-16 14:41:10 -0800142 final MessageQueue queue = me.mQueue;
143
Dianne Hackborne5dea752011-02-09 14:19:23 -0800144 // Make sure the identity of this thread is that of the local process,
145 // and keep track of what that identity token actually is.
146 Binder.clearCallingIdentity();
147 final long ident = Binder.clearCallingIdentity();
Jeff Brown0f85ce32012-02-16 14:41:10 -0800148
Makoto Onuki712886f2018-04-27 15:22:50 -0700149 // Allow overriding a threshold with a system prop. e.g.
150 // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
151 final int thresholdOverride =
152 SystemProperties.getInt("log.looper."
153 + Process.myUid() + "."
154 + Thread.currentThread().getName()
155 + ".slow", 0);
156
157 boolean slowDeliveryDetected = false;
158
Jeff Brown0f85ce32012-02-16 14:41:10 -0800159 for (;;) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 Message msg = queue.next(); // might block
Jeff Brown0f85ce32012-02-16 14:41:10 -0800161 if (msg == null) {
162 // No message indicates that the message queue is quitting.
163 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 }
Jeff Brown0f85ce32012-02-16 14:41:10 -0800165
Jeff Brown0f85ce32012-02-16 14:41:10 -0800166 // This must be in a local variable, in case a UI event sets the logger
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600167 final Printer logging = me.mLogging;
Jeff Brown0f85ce32012-02-16 14:41:10 -0800168 if (logging != null) {
169 logging.println(">>>>> Dispatching to " + msg.target + " " +
170 msg.callback + ": " + msg.what);
Jeff Brown0f85ce32012-02-16 14:41:10 -0800171 }
172
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600173 final long traceTag = me.mTraceTag;
Makoto Onuki712886f2018-04-27 15:22:50 -0700174 long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
175 long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
176 if (thresholdOverride > 0) {
177 slowDispatchThresholdMs = thresholdOverride;
178 slowDeliveryThresholdMs = thresholdOverride;
179 }
180 final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
181 final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
182
183 final boolean needStartTime = logSlowDelivery || logSlowDispatch;
184 final boolean needEndTime = logSlowDispatch;
185
Jorim Jaggi407c0be2016-08-01 13:31:55 +0200186 if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600187 Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
188 }
Makoto Onuki712886f2018-04-27 15:22:50 -0700189
190 final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
191 final long dispatchEnd;
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600192 try {
193 msg.target.dispatchMessage(msg);
Makoto Onuki712886f2018-04-27 15:22:50 -0700194 dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600195 } finally {
196 if (traceTag != 0) {
197 Trace.traceEnd(traceTag);
198 }
199 }
Makoto Onuki712886f2018-04-27 15:22:50 -0700200 if (logSlowDelivery) {
201 if (slowDeliveryDetected) {
202 if ((dispatchStart - msg.when) <= 10) {
203 Slog.w(TAG, "Drained");
204 slowDeliveryDetected = false;
205 }
206 } else {
207 if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
208 msg)) {
209 // Once we write a slow delivery log, suppress until the queue drains.
210 slowDeliveryDetected = true;
211 }
Makoto Onuki99571512017-03-28 14:12:34 -0700212 }
213 }
Makoto Onuki712886f2018-04-27 15:22:50 -0700214 if (logSlowDispatch) {
215 showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
216 }
Jeff Brown0f85ce32012-02-16 14:41:10 -0800217
218 if (logging != null) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800219 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
Jeff Brown0f85ce32012-02-16 14:41:10 -0800220 }
221
222 // Make sure that during the course of dispatching the
223 // identity of the thread wasn't corrupted.
224 final long newIdent = Binder.clearCallingIdentity();
225 if (ident != newIdent) {
226 Log.wtf(TAG, "Thread identity changed from 0x"
227 + Long.toHexString(ident) + " to 0x"
228 + Long.toHexString(newIdent) + " while dispatching to "
229 + msg.target.getClass().getName() + " "
230 + msg.callback + " what=" + msg.what);
231 }
232
Jeff Brown9867ed72014-02-28 14:00:57 -0800233 msg.recycleUnchecked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 }
235 }
236
Makoto Onuki712886f2018-04-27 15:22:50 -0700237 private static boolean showSlowLog(long threshold, long measureStart, long measureEnd,
238 String what, Message msg) {
239 final long actualTime = measureEnd - measureStart;
240 if (actualTime < threshold) {
241 return false;
242 }
243 // For slow delivery, the current message isn't really important, but log it anyway.
244 Slog.w(TAG, "Slow " + what + " took " + actualTime + "ms "
245 + Thread.currentThread().getName() + " h="
246 + msg.target.getClass().getName() + " c=" + msg.callback + " m=" + msg.what);
247 return true;
248 }
249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 /**
251 * Return the Looper object associated with the current thread. Returns
252 * null if the calling thread is not associated with a Looper.
253 */
Jeff Brown803c2af2015-03-05 10:52:53 -0800254 public static @Nullable Looper myLooper() {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800255 return sThreadLocal.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 }
257
258 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 * Return the {@link MessageQueue} object associated with the current
260 * thread. This must be called from a thread running a Looper, or a
261 * NullPointerException will be thrown.
262 */
Jeff Brown803c2af2015-03-05 10:52:53 -0800263 public static @NonNull MessageQueue myQueue() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 return myLooper().mQueue;
265 }
266
Jeff Brown0f85ce32012-02-16 14:41:10 -0800267 private Looper(boolean quitAllowed) {
268 mQueue = new MessageQueue(quitAllowed);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 mThread = Thread.currentThread();
270 }
271
Jeff Brown0f85ce32012-02-16 14:41:10 -0800272 /**
Jeff Brownf9e989d2013-04-04 23:04:03 -0700273 * Returns true if the current thread is this looper's thread.
Jeff Brownf9e989d2013-04-04 23:04:03 -0700274 */
275 public boolean isCurrentThread() {
276 return Thread.currentThread() == mThread;
277 }
278
279 /**
Jeff Brown803c2af2015-03-05 10:52:53 -0800280 * Control logging of messages as they are processed by this Looper. If
281 * enabled, a log message will be written to <var>printer</var>
282 * at the beginning and ending of each message dispatch, identifying the
283 * target Handler and message contents.
284 *
285 * @param printer A Printer object that will receive log messages, or
286 * null to disable message logging.
287 */
288 public void setMessageLogging(@Nullable Printer printer) {
289 mLogging = printer;
290 }
291
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600292 /** {@hide} */
293 public void setTraceTag(long traceTag) {
294 mTraceTag = traceTag;
295 }
296
Makoto Onuki712886f2018-04-27 15:22:50 -0700297 /**
298 * Set a thresholds for slow dispatch/delivery log.
299 * {@hide}
300 */
301 public void setSlowLogThresholdMs(long slowDispatchThresholdMs, long slowDeliveryThresholdMs) {
Makoto Onuki99571512017-03-28 14:12:34 -0700302 mSlowDispatchThresholdMs = slowDispatchThresholdMs;
Makoto Onuki712886f2018-04-27 15:22:50 -0700303 mSlowDeliveryThresholdMs = slowDeliveryThresholdMs;
Makoto Onuki99571512017-03-28 14:12:34 -0700304 }
305
Jeff Brown803c2af2015-03-05 10:52:53 -0800306 /**
Jeff Brown0f85ce32012-02-16 14:41:10 -0800307 * Quits the looper.
Jeff Brown024136f2013-04-11 19:21:32 -0700308 * <p>
Jeff Brown8b60e452013-04-18 15:17:48 -0700309 * Causes the {@link #loop} method to terminate without processing any
310 * more messages in the message queue.
Jeff Brown024136f2013-04-11 19:21:32 -0700311 * </p><p>
Jeff Brown8b60e452013-04-18 15:17:48 -0700312 * Any attempt to post messages to the queue after the looper is asked to quit will fail.
313 * For example, the {@link Handler#sendMessage(Message)} method will return false.
314 * </p><p class="note">
315 * Using this method may be unsafe because some messages may not be delivered
316 * before the looper terminates. Consider using {@link #quitSafely} instead to ensure
317 * that all pending work is completed in an orderly manner.
Jeff Brown024136f2013-04-11 19:21:32 -0700318 * </p>
Jeff Brown8b60e452013-04-18 15:17:48 -0700319 *
320 * @see #quitSafely
Jeff Brown0f85ce32012-02-16 14:41:10 -0800321 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 public void quit() {
Jeff Brown8b60e452013-04-18 15:17:48 -0700323 mQueue.quit(false);
324 }
325
326 /**
327 * Quits the looper safely.
328 * <p>
329 * Causes the {@link #loop} method to terminate as soon as all remaining messages
330 * in the message queue that are already due to be delivered have been handled.
331 * However pending delayed messages with due times in the future will not be
332 * delivered before the loop terminates.
333 * </p><p>
334 * Any attempt to post messages to the queue after the looper is asked to quit will fail.
335 * For example, the {@link Handler#sendMessage(Message)} method will return false.
336 * </p>
337 */
338 public void quitSafely() {
339 mQueue.quit(true);
Jeff Brown0f85ce32012-02-16 14:41:10 -0800340 }
341
342 /**
Jeff Brown803c2af2015-03-05 10:52:53 -0800343 * Gets the Thread associated with this Looper.
344 *
345 * @return The looper's thread.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 */
Jeff Brown803c2af2015-03-05 10:52:53 -0800347 public @NonNull Thread getThread() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 return mThread;
349 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800350
Jeff Brown803c2af2015-03-05 10:52:53 -0800351 /**
352 * Gets this looper's message queue.
353 *
354 * @return The looper's message queue.
355 */
356 public @NonNull MessageQueue getQueue() {
Jeff Browna41ca772010-08-11 14:46:32 -0700357 return mQueue;
358 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800359
Jeff Brown803c2af2015-03-05 10:52:53 -0800360 /**
361 * Dumps the state of the looper for debugging purposes.
362 *
363 * @param pw A printer to receive the contents of the dump.
364 * @param prefix A prefix to prepend to each line which is printed.
365 */
366 public void dump(@NonNull Printer pw, @NonNull String prefix) {
Jeff Brown5182c782013-10-15 20:31:52 -0700367 pw.println(prefix + toString());
Dianne Hackborncb015632017-06-14 17:30:15 -0700368 mQueue.dump(pw, prefix + " ", null);
369 }
370
371 /**
372 * Dumps the state of the looper for debugging purposes.
373 *
374 * @param pw A printer to receive the contents of the dump.
375 * @param prefix A prefix to prepend to each line which is printed.
376 * @param handler Only dump messages for this Handler.
377 * @hide
378 */
379 public void dump(@NonNull Printer pw, @NonNull String prefix, Handler handler) {
380 pw.println(prefix + toString());
381 mQueue.dump(pw, prefix + " ", handler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 }
383
Netta P958d0a52017-02-07 11:20:55 -0800384 /** @hide */
385 public void writeToProto(ProtoOutputStream proto, long fieldId) {
386 final long looperToken = proto.start(fieldId);
387 proto.write(LooperProto.THREAD_NAME, mThread.getName());
388 proto.write(LooperProto.THREAD_ID, mThread.getId());
Kweku Adams15afdeb2018-09-04 11:54:46 -0700389 if (mQueue != null) {
390 mQueue.writeToProto(proto, LooperProto.QUEUE);
391 }
Netta P958d0a52017-02-07 11:20:55 -0800392 proto.end(looperToken);
393 }
394
Jeff Browndc3eb4b2015-03-05 18:21:06 -0800395 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 public String toString() {
Jeff Brown5182c782013-10-15 20:31:52 -0700397 return "Looper (" + mThread.getName() + ", tid " + mThread.getId()
398 + ") {" + Integer.toHexString(System.identityHashCode(this)) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400}