1 /* 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 17 package android.os; 18 19 import android.annotation.NonNull; 20 import android.annotation.Nullable; 21 import android.compat.annotation.UnsupportedAppUsage; 22 import android.util.Log; 23 import android.util.Printer; 24 import android.util.Slog; 25 import android.util.proto.ProtoOutputStream; 26 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. 32 * 33 * <p>Most interaction with a message loop is through the 34 * {@link Handler} class. 35 * 36 * <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. 39 * 40 * <pre> 41 * class LooperThread extends Thread { 42 * public Handler mHandler; 43 * 44 * public void run() { 45 * Looper.prepare(); 46 * 47 * mHandler = new Handler(Looper.myLooper()) { 48 * public void handleMessage(Message msg) { 49 * // process incoming messages here 50 * } 51 * }; 52 * 53 * Looper.loop(); 54 * } 55 * }</pre> 56 */ 57 public final class Looper { 58 /* 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 65 * thread, looping, and quitting are defined on the looper. 66 */ 67 68 private static final String TAG = "Looper"; 69 70 // sThreadLocal.get() will return null unless you've called prepare(). 71 @UnsupportedAppUsage 72 static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); 73 @UnsupportedAppUsage 74 private static Looper sMainLooper; // guarded by Looper.class 75 private static Observer sObserver; 76 77 @UnsupportedAppUsage 78 final MessageQueue mQueue; 79 final Thread mThread; 80 private boolean mInLoop; 81 82 @UnsupportedAppUsage 83 private Printer mLogging; 84 private long mTraceTag; 85 86 /** 87 * If set, the looper will show a warning log if a message dispatch takes longer than this. 88 */ 89 private long mSlowDispatchThresholdMs; 90 91 /** 92 * If set, the looper will show a warning log if a message delivery (actual delivery time - 93 * post time) takes longer than this. 94 */ 95 private long mSlowDeliveryThresholdMs; 96 97 /** 98 * True if a message delivery takes longer than {@link #mSlowDeliveryThresholdMs}. 99 */ 100 private boolean mSlowDeliveryDetected; 101 102 /** Initialize the current thread as a looper. 103 * This gives you a chance to create handlers that then reference 104 * this looper, before actually starting the loop. Be sure to call 105 * {@link #loop()} after calling this method, and end it by calling 106 * {@link #quit()}. 107 */ prepare()108 public static void prepare() { 109 prepare(true); 110 } 111 prepare(boolean quitAllowed)112 private static void prepare(boolean quitAllowed) { 113 if (sThreadLocal.get() != null) { 114 throw new RuntimeException("Only one Looper may be created per thread"); 115 } 116 sThreadLocal.set(new Looper(quitAllowed)); 117 } 118 119 /** 120 * Initialize the current thread as a looper, marking it as an 121 * application's main looper. See also: {@link #prepare()} 122 * 123 * @deprecated The main looper for your application is created by the Android environment, 124 * so you should never need to call this function yourself. 125 */ 126 @Deprecated prepareMainLooper()127 public static void prepareMainLooper() { 128 prepare(false); 129 synchronized (Looper.class) { 130 if (sMainLooper != null) { 131 throw new IllegalStateException("The main Looper has already been prepared."); 132 } 133 sMainLooper = myLooper(); 134 } 135 } 136 137 /** 138 * Returns the application's main looper, which lives in the main thread of the application. 139 */ getMainLooper()140 public static Looper getMainLooper() { 141 synchronized (Looper.class) { 142 return sMainLooper; 143 } 144 } 145 146 /** 147 * Set the transaction observer for all Loopers in this process. 148 * 149 * @hide 150 */ setObserver(@ullable Observer observer)151 public static void setObserver(@Nullable Observer observer) { 152 sObserver = observer; 153 } 154 155 /** 156 * Poll and deliver single message, return true if the outer loop should continue. 157 */ 158 @SuppressWarnings("AndroidFrameworkBinderIdentity") loopOnce(final Looper me, final long ident, final int thresholdOverride)159 private static boolean loopOnce(final Looper me, 160 final long ident, final int thresholdOverride) { 161 Message msg = me.mQueue.next(); // might block 162 if (msg == null) { 163 // No message indicates that the message queue is quitting. 164 return false; 165 } 166 167 // This must be in a local variable, in case a UI event sets the logger 168 final Printer logging = me.mLogging; 169 if (logging != null) { 170 logging.println(">>>>> Dispatching to " + msg.target + " " 171 + msg.callback + ": " + msg.what); 172 } 173 // Make sure the observer won't change while processing a transaction. 174 final Observer observer = sObserver; 175 176 final long traceTag = me.mTraceTag; 177 long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs; 178 long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs; 179 if (thresholdOverride > 0) { 180 slowDispatchThresholdMs = thresholdOverride; 181 slowDeliveryThresholdMs = thresholdOverride; 182 } 183 final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0); 184 final boolean logSlowDispatch = (slowDispatchThresholdMs > 0); 185 186 final boolean needStartTime = logSlowDelivery || logSlowDispatch; 187 final boolean needEndTime = logSlowDispatch; 188 189 if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { 190 Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); 191 } 192 193 final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0; 194 final long dispatchEnd; 195 Object token = null; 196 if (observer != null) { 197 token = observer.messageDispatchStarting(); 198 } 199 long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid); 200 try { 201 msg.target.dispatchMessage(msg); 202 if (observer != null) { 203 observer.messageDispatched(token, msg); 204 } 205 dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0; 206 } catch (Exception exception) { 207 if (observer != null) { 208 observer.dispatchingThrewException(token, msg, exception); 209 } 210 throw exception; 211 } finally { 212 ThreadLocalWorkSource.restore(origWorkSource); 213 if (traceTag != 0) { 214 Trace.traceEnd(traceTag); 215 } 216 } 217 if (logSlowDelivery) { 218 if (me.mSlowDeliveryDetected) { 219 if ((dispatchStart - msg.when) <= 10) { 220 Slog.w(TAG, "Drained"); 221 me.mSlowDeliveryDetected = false; 222 } 223 } else { 224 if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery", 225 msg)) { 226 // Once we write a slow delivery log, suppress until the queue drains. 227 me.mSlowDeliveryDetected = true; 228 } 229 } 230 } 231 if (logSlowDispatch) { 232 showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg); 233 } 234 235 if (logging != null) { 236 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); 237 } 238 239 // Make sure that during the course of dispatching the 240 // identity of the thread wasn't corrupted. 241 final long newIdent = Binder.clearCallingIdentity(); 242 if (ident != newIdent) { 243 Log.wtf(TAG, "Thread identity changed from 0x" 244 + Long.toHexString(ident) + " to 0x" 245 + Long.toHexString(newIdent) + " while dispatching to " 246 + msg.target.getClass().getName() + " " 247 + msg.callback + " what=" + msg.what); 248 } 249 250 msg.recycleUnchecked(); 251 252 return true; 253 } 254 255 /** 256 * Run the message queue in this thread. Be sure to call 257 * {@link #quit()} to end the loop. 258 */ 259 @SuppressWarnings("AndroidFrameworkBinderIdentity") loop()260 public static void loop() { 261 final Looper me = myLooper(); 262 if (me == null) { 263 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); 264 } 265 if (me.mInLoop) { 266 Slog.w(TAG, "Loop again would have the queued messages be executed" 267 + " before this one completed."); 268 } 269 270 me.mInLoop = true; 271 272 // Make sure the identity of this thread is that of the local process, 273 // and keep track of what that identity token actually is. 274 Binder.clearCallingIdentity(); 275 final long ident = Binder.clearCallingIdentity(); 276 277 // Allow overriding a threshold with a system prop. e.g. 278 // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start' 279 final int thresholdOverride = 280 SystemProperties.getInt("log.looper." 281 + Process.myUid() + "." 282 + Thread.currentThread().getName() 283 + ".slow", 0); 284 285 me.mSlowDeliveryDetected = false; 286 287 for (;;) { 288 if (!loopOnce(me, ident, thresholdOverride)) { 289 return; 290 } 291 } 292 } 293 showSlowLog(long threshold, long measureStart, long measureEnd, String what, Message msg)294 private static boolean showSlowLog(long threshold, long measureStart, long measureEnd, 295 String what, Message msg) { 296 final long actualTime = measureEnd - measureStart; 297 if (actualTime < threshold) { 298 return false; 299 } 300 // For slow delivery, the current message isn't really important, but log it anyway. 301 Slog.w(TAG, "Slow " + what + " took " + actualTime + "ms " 302 + Thread.currentThread().getName() + " h=" 303 + msg.target.getClass().getName() + " c=" + msg.callback + " m=" + msg.what); 304 return true; 305 } 306 307 /** 308 * Return the Looper object associated with the current thread. Returns 309 * null if the calling thread is not associated with a Looper. 310 */ myLooper()311 public static @Nullable Looper myLooper() { 312 return sThreadLocal.get(); 313 } 314 315 /** 316 * Return the {@link MessageQueue} object associated with the current 317 * thread. This must be called from a thread running a Looper, or a 318 * NullPointerException will be thrown. 319 */ myQueue()320 public static @NonNull MessageQueue myQueue() { 321 return myLooper().mQueue; 322 } 323 Looper(boolean quitAllowed)324 private Looper(boolean quitAllowed) { 325 mQueue = new MessageQueue(quitAllowed); 326 mThread = Thread.currentThread(); 327 } 328 329 /** 330 * Returns true if the current thread is this looper's thread. 331 */ isCurrentThread()332 public boolean isCurrentThread() { 333 return Thread.currentThread() == mThread; 334 } 335 336 /** 337 * Control logging of messages as they are processed by this Looper. If 338 * enabled, a log message will be written to <var>printer</var> 339 * at the beginning and ending of each message dispatch, identifying the 340 * target Handler and message contents. 341 * 342 * @param printer A Printer object that will receive log messages, or 343 * null to disable message logging. 344 */ setMessageLogging(@ullable Printer printer)345 public void setMessageLogging(@Nullable Printer printer) { 346 mLogging = printer; 347 } 348 349 /** {@hide} */ 350 @UnsupportedAppUsage setTraceTag(long traceTag)351 public void setTraceTag(long traceTag) { 352 mTraceTag = traceTag; 353 } 354 355 /** 356 * Set a thresholds for slow dispatch/delivery log. 357 * {@hide} 358 */ setSlowLogThresholdMs(long slowDispatchThresholdMs, long slowDeliveryThresholdMs)359 public void setSlowLogThresholdMs(long slowDispatchThresholdMs, long slowDeliveryThresholdMs) { 360 mSlowDispatchThresholdMs = slowDispatchThresholdMs; 361 mSlowDeliveryThresholdMs = slowDeliveryThresholdMs; 362 } 363 364 /** 365 * Quits the looper. 366 * <p> 367 * Causes the {@link #loop} method to terminate without processing any 368 * more messages in the message queue. 369 * </p><p> 370 * Any attempt to post messages to the queue after the looper is asked to quit will fail. 371 * For example, the {@link Handler#sendMessage(Message)} method will return false. 372 * </p><p class="note"> 373 * Using this method may be unsafe because some messages may not be delivered 374 * before the looper terminates. Consider using {@link #quitSafely} instead to ensure 375 * that all pending work is completed in an orderly manner. 376 * </p> 377 * 378 * @see #quitSafely 379 */ quit()380 public void quit() { 381 mQueue.quit(false); 382 } 383 384 /** 385 * Quits the looper safely. 386 * <p> 387 * Causes the {@link #loop} method to terminate as soon as all remaining messages 388 * in the message queue that are already due to be delivered have been handled. 389 * However pending delayed messages with due times in the future will not be 390 * delivered before the loop terminates. 391 * </p><p> 392 * Any attempt to post messages to the queue after the looper is asked to quit will fail. 393 * For example, the {@link Handler#sendMessage(Message)} method will return false. 394 * </p> 395 */ quitSafely()396 public void quitSafely() { 397 mQueue.quit(true); 398 } 399 400 /** 401 * Gets the Thread associated with this Looper. 402 * 403 * @return The looper's thread. 404 */ getThread()405 public @NonNull Thread getThread() { 406 return mThread; 407 } 408 409 /** 410 * Gets this looper's message queue. 411 * 412 * @return The looper's message queue. 413 */ getQueue()414 public @NonNull MessageQueue getQueue() { 415 return mQueue; 416 } 417 418 /** 419 * Dumps the state of the looper for debugging purposes. 420 * 421 * @param pw A printer to receive the contents of the dump. 422 * @param prefix A prefix to prepend to each line which is printed. 423 */ dump(@onNull Printer pw, @NonNull String prefix)424 public void dump(@NonNull Printer pw, @NonNull String prefix) { 425 pw.println(prefix + toString()); 426 mQueue.dump(pw, prefix + " ", null); 427 } 428 429 /** 430 * Dumps the state of the looper for debugging purposes. 431 * 432 * @param pw A printer to receive the contents of the dump. 433 * @param prefix A prefix to prepend to each line which is printed. 434 * @param handler Only dump messages for this Handler. 435 * @hide 436 */ dump(@onNull Printer pw, @NonNull String prefix, Handler handler)437 public void dump(@NonNull Printer pw, @NonNull String prefix, Handler handler) { 438 pw.println(prefix + toString()); 439 mQueue.dump(pw, prefix + " ", handler); 440 } 441 442 /** @hide */ dumpDebug(ProtoOutputStream proto, long fieldId)443 public void dumpDebug(ProtoOutputStream proto, long fieldId) { 444 final long looperToken = proto.start(fieldId); 445 proto.write(LooperProto.THREAD_NAME, mThread.getName()); 446 proto.write(LooperProto.THREAD_ID, mThread.getId()); 447 if (mQueue != null) { 448 mQueue.dumpDebug(proto, LooperProto.QUEUE); 449 } 450 proto.end(looperToken); 451 } 452 453 @Override toString()454 public String toString() { 455 return "Looper (" + mThread.getName() + ", tid " + mThread.getId() 456 + ") {" + Integer.toHexString(System.identityHashCode(this)) + "}"; 457 } 458 459 /** {@hide} */ 460 public interface Observer { 461 /** 462 * Called right before a message is dispatched. 463 * 464 * <p> The token type is not specified to allow the implementation to specify its own type. 465 * 466 * @return a token used for collecting telemetry when dispatching a single message. 467 * The token token must be passed back exactly once to either 468 * {@link Observer#messageDispatched} or {@link Observer#dispatchingThrewException} 469 * and must not be reused again. 470 * 471 */ messageDispatchStarting()472 Object messageDispatchStarting(); 473 474 /** 475 * Called when a message was processed by a Handler. 476 * 477 * @param token Token obtained by previously calling 478 * {@link Observer#messageDispatchStarting} on the same Observer instance. 479 * @param msg The message that was dispatched. 480 */ messageDispatched(Object token, Message msg)481 void messageDispatched(Object token, Message msg); 482 483 /** 484 * Called when an exception was thrown while processing a message. 485 * 486 * @param token Token obtained by previously calling 487 * {@link Observer#messageDispatchStarting} on the same Observer instance. 488 * @param msg The message that was dispatched and caused an exception. 489 * @param exception The exception that was thrown. 490 */ dispatchingThrewException(Object token, Message msg, Exception exception)491 void dispatchingThrewException(Object token, Message msg, Exception exception); 492 } 493 } 494