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