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