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.os.LooperProto;
     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     static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
     72     private static Looper sMainLooper;  // guarded by Looper.class
     73 
     74     final MessageQueue mQueue;
     75     final Thread mThread;
     76 
     77     private Printer mLogging;
     78     private long mTraceTag;
     79 
     80     /**
     81      * If set, the looper will show a warning log if a message dispatch takes longer than this.
     82      */
     83     private long mSlowDispatchThresholdMs;
     84 
     85     /**
     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.
     92       * 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       */
     97     public static void prepare() {
     98         prepare(true);
     99     }
    100 
    101     private static void prepare(boolean quitAllowed) {
    102         if (sThreadLocal.get() != null) {
    103             throw new RuntimeException("Only one Looper may be created per thread");
    104         }
    105         sThreadLocal.set(new Looper(quitAllowed));
    106     }
    107 
    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()}
    113      */
    114     public static void prepareMainLooper() {
    115         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         }
    122     }
    123 
    124     /**
    125      * Returns the application's main looper, which lives in the main thread of the application.
    126      */
    127     public static Looper getMainLooper() {
    128         synchronized (Looper.class) {
    129             return sMainLooper;
    130         }
    131     }
    132 
    133     /**
    134      * Run the message queue in this thread. Be sure to call
    135      * {@link #quit()} to end the loop.
    136      */
    137     public static void loop() {
    138         final Looper me = myLooper();
    139         if (me == null) {
    140             throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    141         }
    142         final MessageQueue queue = me.mQueue;
    143 
    144         // 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();
    148 
    149         // 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 
    159         for (;;) {
    160             Message msg = queue.next(); // might block
    161             if (msg == null) {
    162                 // No message indicates that the message queue is quitting.
    163                 return;
    164             }
    165 
    166             // This must be in a local variable, in case a UI event sets the logger
    167             final Printer logging = me.mLogging;
    168             if (logging != null) {
    169                 logging.println(">>>>> Dispatching to " + msg.target + " " +
    170                         msg.callback + ": " + msg.what);
    171             }
    172 
    173             final long traceTag = me.mTraceTag;
    174             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 
    186             if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
    187                 Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
    188             }
    189 
    190             final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
    191             final long dispatchEnd;
    192             try {
    193                 msg.target.dispatchMessage(msg);
    194                 dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
    195             } finally {
    196                 if (traceTag != 0) {
    197                     Trace.traceEnd(traceTag);
    198                 }
    199             }
    200             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                     }
    212                 }
    213             }
    214             if (logSlowDispatch) {
    215                 showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
    216             }
    217 
    218             if (logging != null) {
    219                 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
    220             }
    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 
    233             msg.recycleUnchecked();
    234         }
    235     }
    236 
    237     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 
    250     /**
    251      * Return the Looper object associated with the current thread.  Returns
    252      * null if the calling thread is not associated with a Looper.
    253      */
    254     public static @Nullable Looper myLooper() {
    255         return sThreadLocal.get();
    256     }
    257 
    258     /**
    259      * 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      */
    263     public static @NonNull MessageQueue myQueue() {
    264         return myLooper().mQueue;
    265     }
    266 
    267     private Looper(boolean quitAllowed) {
    268         mQueue = new MessageQueue(quitAllowed);
    269         mThread = Thread.currentThread();
    270     }
    271 
    272     /**
    273      * Returns true if the current thread is this looper's thread.
    274      */
    275     public boolean isCurrentThread() {
    276         return Thread.currentThread() == mThread;
    277     }
    278 
    279     /**
    280      * 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 
    292     /** {@hide} */
    293     public void setTraceTag(long traceTag) {
    294         mTraceTag = traceTag;
    295     }
    296 
    297     /**
    298      * Set a thresholds for slow dispatch/delivery log.
    299      * {@hide}
    300      */
    301     public void setSlowLogThresholdMs(long slowDispatchThresholdMs, long slowDeliveryThresholdMs) {
    302         mSlowDispatchThresholdMs = slowDispatchThresholdMs;
    303         mSlowDeliveryThresholdMs = slowDeliveryThresholdMs;
    304     }
    305 
    306     /**
    307      * Quits the looper.
    308      * <p>
    309      * Causes the {@link #loop} method to terminate without processing any
    310      * more messages in the message queue.
    311      * </p><p>
    312      * 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.
    318      * </p>
    319      *
    320      * @see #quitSafely
    321      */
    322     public void quit() {
    323         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);
    340     }
    341 
    342     /**
    343      * Gets the Thread associated with this Looper.
    344      *
    345      * @return The looper's thread.
    346      */
    347     public @NonNull Thread getThread() {
    348         return mThread;
    349     }
    350 
    351     /**
    352      * Gets this looper's message queue.
    353      *
    354      * @return The looper's message queue.
    355      */
    356     public @NonNull MessageQueue getQueue() {
    357         return mQueue;
    358     }
    359 
    360     /**
    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) {
    367         pw.println(prefix + toString());
    368         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);
    382     }
    383 
    384     /** @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());
    389         mQueue.writeToProto(proto, LooperProto.QUEUE);
    390         proto.end(looperToken);
    391     }
    392 
    393     @Override
    394     public String toString() {
    395         return "Looper (" + mThread.getName() + ", tid " + mThread.getId()
    396                 + ") {" + Integer.toHexString(System.identityHashCode(this)) + "}";
    397     }
    398 }
    399