blob: 720e802b66ea75785906ee6451d1b9991c356a01 [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().
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080057 private static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058
59 final MessageQueue mQueue;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080060 final Thread mThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061 volatile boolean mRun;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063 private Printer mLogging = null;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080064 private static Looper mMainLooper = null; // guarded by Looper.class
65
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() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073 if (sThreadLocal.get() != null) {
74 throw new RuntimeException("Only one Looper may be created per thread");
75 }
76 sThreadLocal.set(new Looper());
77 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080078
79 /**
80 * Initialize the current thread as a looper, marking it as an
81 * application's main looper. The main looper for your application
82 * is created by the Android environment, so you should never need
83 * to call this function yourself. See also: {@link #prepare()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 */
Romain Guyf9284692011-07-13 18:46:21 -070085 public static void prepareMainLooper() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 prepare();
87 setMainLooper(myLooper());
Jeff Brown10e89712011-07-08 18:52:57 -070088 myLooper().mQueue.mQuitAllowed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089 }
90
91 private synchronized static void setMainLooper(Looper looper) {
92 mMainLooper = looper;
93 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 /** Returns the application's main looper, which lives in the main thread of the application.
96 */
Romain Guyf9284692011-07-13 18:46:21 -070097 public synchronized static Looper getMainLooper() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 return mMainLooper;
99 }
100
101 /**
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800102 * Run the message queue in this thread. Be sure to call
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 * {@link #quit()} to end the loop.
104 */
Romain Guyf9284692011-07-13 18:46:21 -0700105 public static void loop() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 Looper me = myLooper();
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800107 if (me == null) {
108 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 MessageQueue queue = me.mQueue;
Dianne Hackborne5dea752011-02-09 14:19:23 -0800111
112 // Make sure the identity of this thread is that of the local process,
113 // and keep track of what that identity token actually is.
114 Binder.clearCallingIdentity();
115 final long ident = Binder.clearCallingIdentity();
116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 while (true) {
118 Message msg = queue.next(); // might block
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 if (msg != null) {
120 if (msg.target == null) {
121 // No target is a magic identifier for the quit message.
122 return;
123 }
Romain Guyf9284692011-07-13 18:46:21 -0700124
125 long wallStart = 0;
126 long threadStart = 0;
127
128 // This must be in a local variable, in case a UI event sets the logger
129 Printer logging = me.mLogging;
130 if (logging != null) {
131 logging.println(">>>>> Dispatching to " + msg.target + " " +
132 msg.callback + ": " + msg.what);
133 wallStart = System.currentTimeMillis();
134 threadStart = SystemClock.currentThreadTimeMillis();
135 }
136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 msg.target.dispatchMessage(msg);
Romain Guyf9284692011-07-13 18:46:21 -0700138
139 if (logging != null) {
140 long wallTime = System.currentTimeMillis() - wallStart;
141 long threadTime = SystemClock.currentThreadTimeMillis() - threadStart;
142
143 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
144 if (logging instanceof Profiler) {
145 ((Profiler) logging).profile(msg, wallStart, wallTime, threadTime);
146 }
147 }
148
Dianne Hackborne5dea752011-02-09 14:19:23 -0800149 // Make sure that during the course of dispatching the
150 // identity of the thread wasn't corrupted.
151 final long newIdent = Binder.clearCallingIdentity();
152 if (ident != newIdent) {
Romain Guyf9284692011-07-13 18:46:21 -0700153 Log.wtf(TAG, "Thread identity changed from 0x"
Dianne Hackborne5dea752011-02-09 14:19:23 -0800154 + Long.toHexString(ident) + " to 0x"
155 + Long.toHexString(newIdent) + " while dispatching to "
Dianne Hackborn1ab43772011-03-15 14:38:02 -0700156 + msg.target.getClass().getName() + " "
157 + msg.callback + " what=" + msg.what);
Dianne Hackborne5dea752011-02-09 14:19:23 -0800158 }
159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 msg.recycle();
161 }
162 }
163 }
164
165 /**
166 * Return the Looper object associated with the current thread. Returns
167 * null if the calling thread is not associated with a Looper.
168 */
Romain Guyf9284692011-07-13 18:46:21 -0700169 public static Looper myLooper() {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800170 return sThreadLocal.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 }
172
173 /**
174 * Control logging of messages as they are processed by this Looper. If
175 * enabled, a log message will be written to <var>printer</var>
176 * at the beginning and ending of each message dispatch, identifying the
177 * target Handler and message contents.
178 *
179 * @param printer A Printer object that will receive log messages, or
180 * null to disable message logging.
181 */
182 public void setMessageLogging(Printer printer) {
183 mLogging = printer;
184 }
185
186 /**
187 * Return the {@link MessageQueue} object associated with the current
188 * thread. This must be called from a thread running a Looper, or a
189 * NullPointerException will be thrown.
190 */
Romain Guyf9284692011-07-13 18:46:21 -0700191 public static MessageQueue myQueue() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 return myLooper().mQueue;
193 }
194
195 private Looper() {
196 mQueue = new MessageQueue();
197 mRun = true;
198 mThread = Thread.currentThread();
199 }
200
201 public void quit() {
202 Message msg = Message.obtain();
203 // NOTE: By enqueueing directly into the message queue, the
204 // message is left with a null target. This is how we know it is
205 // a quit message.
206 mQueue.enqueueMessage(msg, 0);
207 }
208
209 /**
210 * Return the Thread associated with this Looper.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 */
212 public Thread getThread() {
213 return mThread;
214 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800215
Jeff Browna41ca772010-08-11 14:46:32 -0700216 /** @hide */
217 public MessageQueue getQueue() {
218 return mQueue;
219 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 public void dump(Printer pw, String prefix) {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800222 pw = PrefixPrinter.create(pw, prefix);
223 pw.println(this.toString());
224 pw.println("mRun=" + mRun);
225 pw.println("mThread=" + mThread);
226 pw.println("mQueue=" + ((mQueue != null) ? mQueue : "(null"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 if (mQueue != null) {
228 synchronized (mQueue) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700229 long now = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 Message msg = mQueue.mMessages;
231 int n = 0;
232 while (msg != null) {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800233 pw.println(" Message " + n + ": " + msg.toString(now));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 n++;
235 msg = msg.next;
236 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800237 pw.println("(Total messages: " + n + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 }
239 }
240 }
241
242 public String toString() {
Romain Guyf9284692011-07-13 18:46:21 -0700243 return "Looper{" + Integer.toHexString(System.identityHashCode(this)) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 }
245
Romain Guyf9284692011-07-13 18:46:21 -0700246 /**
247 * @hide
248 */
249 public static interface Profiler {
250 void profile(Message message, long wallStart, long wallTime, long threadTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 }
252}