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