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.util.Log; 22 import android.util.Printer; 23 24 /** 25 * Class used to run a message loop for a thread. Threads by default do 26 * not have a message loop associated with them; to create one, call 27 * {@link #prepare} in the thread that is to run the loop, and then 28 * {@link #loop} to have it process messages until the loop is stopped. 29 * 30 * <p>Most interaction with a message loop is through the 31 * {@link Handler} class. 32 * 33 * <p>This is a typical example of the implementation of a Looper thread, 34 * using the separation of {@link #prepare} and {@link #loop} to create an 35 * initial Handler to communicate with the Looper. 36 * 37 * <pre> 38 * class LooperThread extends Thread { 39 * public Handler mHandler; 40 * 41 * public void run() { 42 * Looper.prepare(); 43 * 44 * mHandler = new Handler() { 45 * public void handleMessage(Message msg) { 46 * // process incoming messages here 47 * } 48 * }; 49 * 50 * Looper.loop(); 51 * } 52 * }</pre> 53 */ 54 public final class Looper { 55 /* 56 * API Implementation Note: 57 * 58 * This class contains the code required to set up and manage an event loop 59 * based on MessageQueue. APIs that affect the state of the queue should be 60 * defined on MessageQueue or Handler rather than on Looper itself. For example, 61 * idle handlers and sync barriers are defined on the queue whereas preparing the 62 * thread, looping, and quitting are defined on the looper. 63 */ 64 65 private static final String TAG = "Looper"; 66 67 // sThreadLocal.get() will return null unless you've called prepare(). 68 static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); 69 private static Looper sMainLooper; // guarded by Looper.class 70 71 final MessageQueue mQueue; 72 final Thread mThread; 73 74 private Printer mLogging; 75 private long mTraceTag; 76 77 /** Initialize the current thread as a looper. 78 * This gives you a chance to create handlers that then reference 79 * this looper, before actually starting the loop. Be sure to call 80 * {@link #loop()} after calling this method, and end it by calling 81 * {@link #quit()}. 82 */ prepare()83 public static void prepare() { 84 prepare(true); 85 } 86 prepare(boolean quitAllowed)87 private static void prepare(boolean quitAllowed) { 88 if (sThreadLocal.get() != null) { 89 throw new RuntimeException("Only one Looper may be created per thread"); 90 } 91 sThreadLocal.set(new Looper(quitAllowed)); 92 } 93 94 /** 95 * Initialize the current thread as a looper, marking it as an 96 * application's main looper. The main looper for your application 97 * is created by the Android environment, so you should never need 98 * to call this function yourself. See also: {@link #prepare()} 99 */ prepareMainLooper()100 public static void prepareMainLooper() { 101 prepare(false); 102 synchronized (Looper.class) { 103 if (sMainLooper != null) { 104 throw new IllegalStateException("The main Looper has already been prepared."); 105 } 106 sMainLooper = myLooper(); 107 } 108 } 109 110 /** 111 * Returns the application's main looper, which lives in the main thread of the application. 112 */ getMainLooper()113 public static Looper getMainLooper() { 114 synchronized (Looper.class) { 115 return sMainLooper; 116 } 117 } 118 119 /** 120 * Run the message queue in this thread. Be sure to call 121 * {@link #quit()} to end the loop. 122 */ loop()123 public static void loop() { 124 final Looper me = myLooper(); 125 if (me == null) { 126 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); 127 } 128 final MessageQueue queue = me.mQueue; 129 130 // Make sure the identity of this thread is that of the local process, 131 // and keep track of what that identity token actually is. 132 Binder.clearCallingIdentity(); 133 final long ident = Binder.clearCallingIdentity(); 134 135 for (;;) { 136 Message msg = queue.next(); // might block 137 if (msg == null) { 138 // No message indicates that the message queue is quitting. 139 return; 140 } 141 142 // This must be in a local variable, in case a UI event sets the logger 143 final Printer logging = me.mLogging; 144 if (logging != null) { 145 logging.println(">>>>> Dispatching to " + msg.target + " " + 146 msg.callback + ": " + msg.what); 147 } 148 149 final long traceTag = me.mTraceTag; 150 if (traceTag != 0) { 151 Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); 152 } 153 try { 154 msg.target.dispatchMessage(msg); 155 } finally { 156 if (traceTag != 0) { 157 Trace.traceEnd(traceTag); 158 } 159 } 160 161 if (logging != null) { 162 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); 163 } 164 165 // Make sure that during the course of dispatching the 166 // identity of the thread wasn't corrupted. 167 final long newIdent = Binder.clearCallingIdentity(); 168 if (ident != newIdent) { 169 Log.wtf(TAG, "Thread identity changed from 0x" 170 + Long.toHexString(ident) + " to 0x" 171 + Long.toHexString(newIdent) + " while dispatching to " 172 + msg.target.getClass().getName() + " " 173 + msg.callback + " what=" + msg.what); 174 } 175 176 msg.recycleUnchecked(); 177 } 178 } 179 180 /** 181 * Return the Looper object associated with the current thread. Returns 182 * null if the calling thread is not associated with a Looper. 183 */ myLooper()184 public static @Nullable Looper myLooper() { 185 return sThreadLocal.get(); 186 } 187 188 /** 189 * Return the {@link MessageQueue} object associated with the current 190 * thread. This must be called from a thread running a Looper, or a 191 * NullPointerException will be thrown. 192 */ myQueue()193 public static @NonNull MessageQueue myQueue() { 194 return myLooper().mQueue; 195 } 196 Looper(boolean quitAllowed)197 private Looper(boolean quitAllowed) { 198 mQueue = new MessageQueue(quitAllowed); 199 mThread = Thread.currentThread(); 200 } 201 202 /** 203 * Returns true if the current thread is this looper's thread. 204 */ isCurrentThread()205 public boolean isCurrentThread() { 206 return Thread.currentThread() == mThread; 207 } 208 209 /** 210 * Control logging of messages as they are processed by this Looper. If 211 * enabled, a log message will be written to <var>printer</var> 212 * at the beginning and ending of each message dispatch, identifying the 213 * target Handler and message contents. 214 * 215 * @param printer A Printer object that will receive log messages, or 216 * null to disable message logging. 217 */ setMessageLogging(@ullable Printer printer)218 public void setMessageLogging(@Nullable Printer printer) { 219 mLogging = printer; 220 } 221 222 /** {@hide} */ setTraceTag(long traceTag)223 public void setTraceTag(long traceTag) { 224 mTraceTag = traceTag; 225 } 226 227 /** 228 * Quits the looper. 229 * <p> 230 * Causes the {@link #loop} method to terminate without processing any 231 * more messages in the message queue. 232 * </p><p> 233 * Any attempt to post messages to the queue after the looper is asked to quit will fail. 234 * For example, the {@link Handler#sendMessage(Message)} method will return false. 235 * </p><p class="note"> 236 * Using this method may be unsafe because some messages may not be delivered 237 * before the looper terminates. Consider using {@link #quitSafely} instead to ensure 238 * that all pending work is completed in an orderly manner. 239 * </p> 240 * 241 * @see #quitSafely 242 */ quit()243 public void quit() { 244 mQueue.quit(false); 245 } 246 247 /** 248 * Quits the looper safely. 249 * <p> 250 * Causes the {@link #loop} method to terminate as soon as all remaining messages 251 * in the message queue that are already due to be delivered have been handled. 252 * However pending delayed messages with due times in the future will not be 253 * delivered before the loop terminates. 254 * </p><p> 255 * Any attempt to post messages to the queue after the looper is asked to quit will fail. 256 * For example, the {@link Handler#sendMessage(Message)} method will return false. 257 * </p> 258 */ quitSafely()259 public void quitSafely() { 260 mQueue.quit(true); 261 } 262 263 /** 264 * Gets the Thread associated with this Looper. 265 * 266 * @return The looper's thread. 267 */ getThread()268 public @NonNull Thread getThread() { 269 return mThread; 270 } 271 272 /** 273 * Gets this looper's message queue. 274 * 275 * @return The looper's message queue. 276 */ getQueue()277 public @NonNull MessageQueue getQueue() { 278 return mQueue; 279 } 280 281 /** 282 * Dumps the state of the looper for debugging purposes. 283 * 284 * @param pw A printer to receive the contents of the dump. 285 * @param prefix A prefix to prepend to each line which is printed. 286 */ dump(@onNull Printer pw, @NonNull String prefix)287 public void dump(@NonNull Printer pw, @NonNull String prefix) { 288 pw.println(prefix + toString()); 289 mQueue.dump(pw, prefix + " "); 290 } 291 292 @Override toString()293 public String toString() { 294 return "Looper (" + mThread.getName() + ", tid " + mThread.getId() 295 + ") {" + Integer.toHexString(System.identityHashCode(this)) + "}"; 296 } 297 } 298