blob: 5607f7fc79175f040ebcea30880c10d77727adb4 [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>();
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);
Romain Guy648bee12011-07-20 18:47:17 -0700133 wallStart = SystemClock.currentTimeMicro();
134 threadStart = SystemClock.currentThreadTimeMicro();
Romain Guyf9284692011-07-13 18:46:21 -0700135 }
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) {
Romain Guy648bee12011-07-20 18:47:17 -0700140 long wallTime = SystemClock.currentTimeMicro() - wallStart;
141 long threadTime = SystemClock.currentThreadTimeMicro() - threadStart;
Romain Guyf9284692011-07-13 18:46:21 -0700142
143 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
144 if (logging instanceof Profiler) {
Romain Guy648bee12011-07-20 18:47:17 -0700145 ((Profiler) logging).profile(msg, wallStart, wallTime,
146 threadStart, threadTime);
Romain Guyf9284692011-07-13 18:46:21 -0700147 }
148 }
149
Dianne Hackborne5dea752011-02-09 14:19:23 -0800150 // Make sure that during the course of dispatching the
151 // identity of the thread wasn't corrupted.
152 final long newIdent = Binder.clearCallingIdentity();
153 if (ident != newIdent) {
Romain Guyf9284692011-07-13 18:46:21 -0700154 Log.wtf(TAG, "Thread identity changed from 0x"
Dianne Hackborne5dea752011-02-09 14:19:23 -0800155 + Long.toHexString(ident) + " to 0x"
156 + Long.toHexString(newIdent) + " while dispatching to "
Dianne Hackborn1ab43772011-03-15 14:38:02 -0700157 + msg.target.getClass().getName() + " "
158 + msg.callback + " what=" + msg.what);
Dianne Hackborne5dea752011-02-09 14:19:23 -0800159 }
160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 msg.recycle();
162 }
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 */
Romain Guyf9284692011-07-13 18:46:21 -0700170 public static Looper myLooper() {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800171 return sThreadLocal.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 }
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 */
Romain Guyf9284692011-07-13 18:46:21 -0700192 public static MessageQueue myQueue() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 return myLooper().mQueue;
194 }
195
196 private Looper() {
197 mQueue = new MessageQueue();
198 mRun = true;
199 mThread = Thread.currentThread();
200 }
201
202 public void quit() {
203 Message msg = Message.obtain();
204 // NOTE: By enqueueing directly into the message queue, the
205 // message is left with a null target. This is how we know it is
206 // a quit message.
207 mQueue.enqueueMessage(msg, 0);
208 }
209
210 /**
211 * Return the Thread associated with this Looper.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 */
213 public Thread getThread() {
214 return mThread;
215 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800216
Jeff Browna41ca772010-08-11 14:46:32 -0700217 /** @hide */
218 public MessageQueue getQueue() {
219 return mQueue;
220 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 public void dump(Printer pw, String prefix) {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800223 pw = PrefixPrinter.create(pw, prefix);
224 pw.println(this.toString());
225 pw.println("mRun=" + mRun);
226 pw.println("mThread=" + mThread);
227 pw.println("mQueue=" + ((mQueue != null) ? mQueue : "(null"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 if (mQueue != null) {
229 synchronized (mQueue) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700230 long now = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 Message msg = mQueue.mMessages;
232 int n = 0;
233 while (msg != null) {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800234 pw.println(" Message " + n + ": " + msg.toString(now));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 n++;
236 msg = msg.next;
237 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800238 pw.println("(Total messages: " + n + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 }
240 }
241 }
242
243 public String toString() {
Romain Guyf9284692011-07-13 18:46:21 -0700244 return "Looper{" + Integer.toHexString(System.identityHashCode(this)) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 }
246
Romain Guyf9284692011-07-13 18:46:21 -0700247 /**
248 * @hide
249 */
250 public static interface Profiler {
Romain Guy648bee12011-07-20 18:47:17 -0700251 void profile(Message message, long wallStart, long wallTime,
252 long threadStart, long threadTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 }
254}