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