blob: a06aadb6d131a04f8e5a22ac90c05b76a7e62e69 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080019import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.util.Printer;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080021import android.util.PrefixPrinter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022
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.
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080035 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036 * <pre>
37 * class LooperThread extends Thread {
38 * public Handler mHandler;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080039 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040 * public void run() {
41 * Looper.prepare();
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080042 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043 * mHandler = new Handler() {
44 * public void handleMessage(Message msg) {
45 * // process incoming messages here
46 * }
47 * };
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080048 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049 * Looper.loop();
50 * }
51 * }</pre>
52 */
53public class Looper {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080054 private static final String TAG = "Looper";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055
56 // sThreadLocal.get() will return null unless you've called prepare().
Xavier Ducrohet7f9f99ea2011-08-11 10:16:17 -070057 static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
Jeff Brown0f85ce32012-02-16 14:41:10 -080058 private static Looper sMainLooper; // guarded by Looper.class
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059
60 final MessageQueue mQueue;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080061 final Thread mThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 volatile boolean mRun;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080063
Jeff Brown0f85ce32012-02-16 14:41:10 -080064 private Printer mLogging;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 /** Initialize the current thread as a looper.
67 * This gives you a chance to create handlers that then reference
68 * this looper, before actually starting the loop. Be sure to call
69 * {@link #loop()} after calling this method, and end it by calling
70 * {@link #quit()}.
71 */
Romain Guyf9284692011-07-13 18:46:21 -070072 public static void prepare() {
Jeff Brown0f85ce32012-02-16 14:41:10 -080073 prepare(true);
74 }
75
76 private static void prepare(boolean quitAllowed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 if (sThreadLocal.get() != null) {
78 throw new RuntimeException("Only one Looper may be created per thread");
79 }
Jeff Brown0f85ce32012-02-16 14:41:10 -080080 sThreadLocal.set(new Looper(quitAllowed));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080082
83 /**
84 * Initialize the current thread as a looper, marking it as an
85 * application's main looper. The main looper for your application
86 * is created by the Android environment, so you should never need
87 * to call this function yourself. See also: {@link #prepare()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 */
Romain Guyf9284692011-07-13 18:46:21 -070089 public static void prepareMainLooper() {
Jeff Brown0f85ce32012-02-16 14:41:10 -080090 prepare(false);
91 synchronized (Looper.class) {
92 if (sMainLooper != null) {
93 throw new IllegalStateException("The main Looper has already been prepared.");
94 }
95 sMainLooper = myLooper();
96 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 /** Returns the application's main looper, which lives in the main thread of the application.
100 */
Jeff Brown0f85ce32012-02-16 14:41:10 -0800101 public static Looper getMainLooper() {
102 synchronized (Looper.class) {
103 return sMainLooper;
104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 }
106
107 /**
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800108 * Run the message queue in this thread. Be sure to call
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 * {@link #quit()} to end the loop.
110 */
Romain Guyf9284692011-07-13 18:46:21 -0700111 public static void loop() {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800112 final Looper me = myLooper();
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800113 if (me == null) {
114 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
115 }
Jeff Brown0f85ce32012-02-16 14:41:10 -0800116 final MessageQueue queue = me.mQueue;
117
Dianne Hackborne5dea752011-02-09 14:19:23 -0800118 // Make sure the identity of this thread is that of the local process,
119 // and keep track of what that identity token actually is.
120 Binder.clearCallingIdentity();
121 final long ident = Binder.clearCallingIdentity();
Jeff Brown0f85ce32012-02-16 14:41:10 -0800122
123 for (;;) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 Message msg = queue.next(); // might block
Jeff Brown0f85ce32012-02-16 14:41:10 -0800125 if (msg == null) {
126 // No message indicates that the message queue is quitting.
127 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 }
Jeff Brown0f85ce32012-02-16 14:41:10 -0800129
130 long wallStart = 0;
131 long threadStart = 0;
132
133 // This must be in a local variable, in case a UI event sets the logger
134 Printer logging = me.mLogging;
135 if (logging != null) {
136 logging.println(">>>>> Dispatching to " + msg.target + " " +
137 msg.callback + ": " + msg.what);
138 wallStart = SystemClock.currentTimeMicro();
139 threadStart = SystemClock.currentThreadTimeMicro();
140 }
141
142 msg.target.dispatchMessage(msg);
143
144 if (logging != null) {
145 long wallTime = SystemClock.currentTimeMicro() - wallStart;
146 long threadTime = SystemClock.currentThreadTimeMicro() - threadStart;
147
148 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
149 if (logging instanceof Profiler) {
150 ((Profiler) logging).profile(msg, wallStart, wallTime,
151 threadStart, threadTime);
152 }
153 }
154
155 // Make sure that during the course of dispatching the
156 // identity of the thread wasn't corrupted.
157 final long newIdent = Binder.clearCallingIdentity();
158 if (ident != newIdent) {
159 Log.wtf(TAG, "Thread identity changed from 0x"
160 + Long.toHexString(ident) + " to 0x"
161 + Long.toHexString(newIdent) + " while dispatching to "
162 + msg.target.getClass().getName() + " "
163 + msg.callback + " what=" + msg.what);
164 }
165
166 msg.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 }
168 }
169
170 /**
171 * Return the Looper object associated with the current thread. Returns
172 * null if the calling thread is not associated with a Looper.
173 */
Romain Guyf9284692011-07-13 18:46:21 -0700174 public static Looper myLooper() {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800175 return sThreadLocal.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 }
177
178 /**
179 * Control logging of messages as they are processed by this Looper. If
180 * enabled, a log message will be written to <var>printer</var>
181 * at the beginning and ending of each message dispatch, identifying the
182 * target Handler and message contents.
183 *
184 * @param printer A Printer object that will receive log messages, or
185 * null to disable message logging.
186 */
187 public void setMessageLogging(Printer printer) {
188 mLogging = printer;
189 }
190
191 /**
192 * Return the {@link MessageQueue} object associated with the current
193 * thread. This must be called from a thread running a Looper, or a
194 * NullPointerException will be thrown.
195 */
Romain Guyf9284692011-07-13 18:46:21 -0700196 public static MessageQueue myQueue() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 return myLooper().mQueue;
198 }
199
Jeff Brown0f85ce32012-02-16 14:41:10 -0800200 private Looper(boolean quitAllowed) {
201 mQueue = new MessageQueue(quitAllowed);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 mRun = true;
203 mThread = Thread.currentThread();
204 }
205
Jeff Brown0f85ce32012-02-16 14:41:10 -0800206 /**
207 * Quits the looper.
208 *
209 * Causes the {@link #loop} method to terminate as soon as possible.
210 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 public void quit() {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800212 mQueue.quit();
213 }
214
215 /**
216 * Posts a synchronization barrier to the Looper's message queue.
217 *
218 * Message processing occurs as usual until the message queue encounters the
219 * synchronization barrier that has been posted. When the barrier is encountered,
220 * later synchronous messages in the queue are stalled (prevented from being executed)
221 * until the barrier is released by calling {@link #removeSyncBarrier} and specifying
222 * the token that identifies the synchronization barrier.
223 *
224 * This method is used to immediately postpone execution of all subsequently posted
225 * synchronous messages until a condition is met that releases the barrier.
226 * Asynchronous messages (see {@link Message#isAsynchronous} are exempt from the barrier
227 * and continue to be processed as usual.
228 *
229 * This call must be always matched by a call to {@link #removeSyncBarrier} with
230 * the same token to ensure that the message queue resumes normal operation.
231 * Otherwise the application will probably hang!
232 *
233 * @return A token that uniquely identifies the barrier. This token must be
234 * passed to {@link #removeSyncBarrier} to release the barrier.
235 *
236 * @hide
237 */
238 public final int postSyncBarrier() {
239 return mQueue.enqueueSyncBarrier(SystemClock.uptimeMillis());
240 }
241
242
243 /**
244 * Removes a synchronization barrier.
245 *
246 * @param token The synchronization barrier token that was returned by
247 * {@link #postSyncBarrier}.
248 *
249 * @throws IllegalStateException if the barrier was not found.
250 *
251 * @hide
252 */
253 public final void removeSyncBarrier(int token) {
254 mQueue.removeSyncBarrier(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 }
256
257 /**
258 * Return the Thread associated with this Looper.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 */
260 public Thread getThread() {
261 return mThread;
262 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800263
Jeff Browna41ca772010-08-11 14:46:32 -0700264 /** @hide */
265 public MessageQueue getQueue() {
266 return mQueue;
267 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 public void dump(Printer pw, String prefix) {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800270 pw = PrefixPrinter.create(pw, prefix);
271 pw.println(this.toString());
272 pw.println("mRun=" + mRun);
273 pw.println("mThread=" + mThread);
274 pw.println("mQueue=" + ((mQueue != null) ? mQueue : "(null"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 if (mQueue != null) {
276 synchronized (mQueue) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700277 long now = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 Message msg = mQueue.mMessages;
279 int n = 0;
280 while (msg != null) {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800281 pw.println(" Message " + n + ": " + msg.toString(now));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 n++;
283 msg = msg.next;
284 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800285 pw.println("(Total messages: " + n + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 }
287 }
288 }
289
290 public String toString() {
Romain Guyf9284692011-07-13 18:46:21 -0700291 return "Looper{" + Integer.toHexString(System.identityHashCode(this)) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 }
293
Romain Guyf9284692011-07-13 18:46:21 -0700294 /**
295 * @hide
296 */
297 public static interface Profiler {
Romain Guy648bee12011-07-20 18:47:17 -0700298 void profile(Message message, long wallStart, long wallTime,
299 long threadStart, long threadTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300 }
301}