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