Looper.java revision 10e89712863f5b91a2982dc1783fbdfe39c1485d
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; 21import android.util.PrefixPrinter; 22 23/** 24 * Class used to run a message loop for a thread. Threads by default do 25 * not have a message loop associated with them; to create one, call 26 * {@link #prepare} in the thread that is to run the loop, and then 27 * {@link #loop} to have it process messages until the loop is stopped. 28 * 29 * <p>Most interaction with a message loop is through the 30 * {@link Handler} class. 31 * 32 * <p>This is a typical example of the implementation of a Looper thread, 33 * using the separation of {@link #prepare} and {@link #loop} to create an 34 * initial Handler to communicate with the Looper. 35 * 36 * <pre> 37 * class LooperThread extends Thread { 38 * public Handler mHandler; 39 * 40 * public void run() { 41 * Looper.prepare(); 42 * 43 * mHandler = new Handler() { 44 * public void handleMessage(Message msg) { 45 * // process incoming messages here 46 * } 47 * }; 48 * 49 * Looper.loop(); 50 * } 51 * }</pre> 52 */ 53public class Looper { 54 private static final String TAG = "Looper"; 55 private static final boolean LOG_V = Log.isLoggable(TAG, Log.VERBOSE); 56 57 // sThreadLocal.get() will return null unless you've called prepare(). 58 private static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); 59 60 final MessageQueue mQueue; 61 final Thread mThread; 62 volatile boolean mRun; 63 64 private Printer mLogging = null; 65 private static Looper mMainLooper = null; // guarded by Looper.class 66 67 /** Initialize the current thread as a looper. 68 * This gives you a chance to create handlers that then reference 69 * this looper, before actually starting the loop. Be sure to call 70 * {@link #loop()} after calling this method, and end it by calling 71 * {@link #quit()}. 72 */ 73 public static final void prepare() { 74 if (sThreadLocal.get() != null) { 75 throw new RuntimeException("Only one Looper may be created per thread"); 76 } 77 sThreadLocal.set(new Looper()); 78 } 79 80 /** 81 * Initialize the current thread as a looper, marking it as an 82 * application's main looper. The main looper for your application 83 * is created by the Android environment, so you should never need 84 * to call this function yourself. See also: {@link #prepare()} 85 */ 86 public static final void prepareMainLooper() { 87 prepare(); 88 setMainLooper(myLooper()); 89 myLooper().mQueue.mQuitAllowed = false; 90 } 91 92 private synchronized static void setMainLooper(Looper looper) { 93 mMainLooper = looper; 94 } 95 96 /** Returns the application's main looper, which lives in the main thread of the application. 97 */ 98 public synchronized static final Looper getMainLooper() { 99 return mMainLooper; 100 } 101 102 /** 103 * Run the message queue in this thread. Be sure to call 104 * {@link #quit()} to end the loop. 105 */ 106 public static final void loop() { 107 Looper me = myLooper(); 108 if (me == null) { 109 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); 110 } 111 MessageQueue queue = me.mQueue; 112 113 // Make sure the identity of this thread is that of the local process, 114 // and keep track of what that identity token actually is. 115 Binder.clearCallingIdentity(); 116 final long ident = Binder.clearCallingIdentity(); 117 118 while (true) { 119 Message msg = queue.next(); // might block 120 if (msg != null) { 121 if (msg.target == null) { 122 // No target is a magic identifier for the quit message. 123 return; 124 } 125 if (me.mLogging != null) me.mLogging.println( 126 ">>>>> Dispatching to " + msg.target + " " 127 + msg.callback + ": " + msg.what 128 ); 129 msg.target.dispatchMessage(msg); 130 if (me.mLogging != null) me.mLogging.println( 131 "<<<<< Finished to " + msg.target + " " 132 + msg.callback); 133 134 // Make sure that during the course of dispatching the 135 // identity of the thread wasn't corrupted. 136 final long newIdent = Binder.clearCallingIdentity(); 137 if (ident != newIdent) { 138 Log.wtf("Looper", "Thread identity changed from 0x" 139 + Long.toHexString(ident) + " to 0x" 140 + Long.toHexString(newIdent) + " while dispatching to " 141 + msg.target.getClass().getName() + " " 142 + msg.callback + " what=" + msg.what); 143 } 144 145 msg.recycle(); 146 } 147 } 148 } 149 150 /** 151 * Return the Looper object associated with the current thread. Returns 152 * null if the calling thread is not associated with a Looper. 153 */ 154 public static final Looper myLooper() { 155 return sThreadLocal.get(); 156 } 157 158 /** 159 * Control logging of messages as they are processed by this Looper. If 160 * enabled, a log message will be written to <var>printer</var> 161 * at the beginning and ending of each message dispatch, identifying the 162 * target Handler and message contents. 163 * 164 * @param printer A Printer object that will receive log messages, or 165 * null to disable message logging. 166 */ 167 public void setMessageLogging(Printer printer) { 168 mLogging = printer; 169 } 170 171 /** 172 * Return the {@link MessageQueue} object associated with the current 173 * thread. This must be called from a thread running a Looper, or a 174 * NullPointerException will be thrown. 175 */ 176 public static final MessageQueue myQueue() { 177 return myLooper().mQueue; 178 } 179 180 private Looper() { 181 mQueue = new MessageQueue(); 182 mRun = true; 183 mThread = Thread.currentThread(); 184 } 185 186 public void quit() { 187 Message msg = Message.obtain(); 188 // NOTE: By enqueueing directly into the message queue, the 189 // message is left with a null target. This is how we know it is 190 // a quit message. 191 mQueue.enqueueMessage(msg, 0); 192 } 193 194 /** 195 * Return the Thread associated with this Looper. 196 */ 197 public Thread getThread() { 198 return mThread; 199 } 200 201 /** @hide */ 202 public MessageQueue getQueue() { 203 return mQueue; 204 } 205 206 public void dump(Printer pw, String prefix) { 207 pw = PrefixPrinter.create(pw, prefix); 208 pw.println(this.toString()); 209 pw.println("mRun=" + mRun); 210 pw.println("mThread=" + mThread); 211 pw.println("mQueue=" + ((mQueue != null) ? mQueue : "(null")); 212 if (mQueue != null) { 213 synchronized (mQueue) { 214 long now = SystemClock.uptimeMillis(); 215 Message msg = mQueue.mMessages; 216 int n = 0; 217 while (msg != null) { 218 pw.println(" Message " + n + ": " + msg.toString(now)); 219 n++; 220 msg = msg.next; 221 } 222 pw.println("(Total messages: " + n + ")"); 223 } 224 } 225 } 226 227 public String toString() { 228 return "Looper{" 229 + Integer.toHexString(System.identityHashCode(this)) 230 + "}"; 231 } 232 233 static class HandlerException extends Exception { 234 235 HandlerException(Message message, Throwable cause) { 236 super(createMessage(cause), cause); 237 } 238 239 static String createMessage(Throwable cause) { 240 String causeMsg = cause.getMessage(); 241 if (causeMsg == null) { 242 causeMsg = cause.toString(); 243 } 244 return causeMsg; 245 } 246 } 247} 248