blob: 3edd6926fe7dc1520efb1f87dd94f88fcb49e34d [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";
55 private static final boolean LOG_V = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056
57 // sThreadLocal.get() will return null unless you've called prepare().
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080058 private static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064 private Printer mLogging = null;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080065 private static Looper mMainLooper = null; // guarded by Looper.class
66
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 /** 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 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080079
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()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 public static final void prepareMainLooper() {
87 prepare();
88 setMainLooper(myLooper());
89 if (Process.supportsProcesses()) {
90 myLooper().mQueue.mQuitAllowed = false;
91 }
92 }
93
94 private synchronized static void setMainLooper(Looper looper) {
95 mMainLooper = looper;
96 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 /** Returns the application's main looper, which lives in the main thread of the application.
99 */
100 public synchronized static final Looper getMainLooper() {
101 return mMainLooper;
102 }
103
104 /**
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800105 * Run the message queue in this thread. Be sure to call
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 * {@link #quit()} to end the loop.
107 */
108 public static final void loop() {
109 Looper me = myLooper();
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800110 if (me == null) {
111 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 MessageQueue queue = me.mQueue;
Dianne Hackborne5dea752011-02-09 14:19:23 -0800114
115 // Make sure the identity of this thread is that of the local process,
116 // and keep track of what that identity token actually is.
117 Binder.clearCallingIdentity();
118 final long ident = Binder.clearCallingIdentity();
119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 while (true) {
121 Message msg = queue.next(); // might block
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 if (msg != null) {
123 if (msg.target == null) {
124 // No target is a magic identifier for the quit message.
125 return;
126 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800127 if (me.mLogging != null) me.mLogging.println(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 ">>>>> Dispatching to " + msg.target + " "
129 + msg.callback + ": " + msg.what
130 );
131 msg.target.dispatchMessage(msg);
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800132 if (me.mLogging != null) me.mLogging.println(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 "<<<<< Finished to " + msg.target + " "
134 + msg.callback);
Dianne Hackborne5dea752011-02-09 14:19:23 -0800135
136 // Make sure that during the course of dispatching the
137 // identity of the thread wasn't corrupted.
138 final long newIdent = Binder.clearCallingIdentity();
139 if (ident != newIdent) {
140 Log.wtf("Looper", "Thread identity changed from 0x"
141 + Long.toHexString(ident) + " to 0x"
142 + Long.toHexString(newIdent) + " while dispatching to "
Dianne Hackborn1ab43772011-03-15 14:38:02 -0700143 + msg.target.getClass().getName() + " "
144 + msg.callback + " what=" + msg.what);
Dianne Hackborne5dea752011-02-09 14:19:23 -0800145 }
146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 msg.recycle();
148 }
149 }
150 }
151
152 /**
153 * Return the Looper object associated with the current thread. Returns
154 * null if the calling thread is not associated with a Looper.
155 */
156 public static final Looper myLooper() {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800157 return sThreadLocal.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 }
159
160 /**
161 * Control logging of messages as they are processed by this Looper. If
162 * enabled, a log message will be written to <var>printer</var>
163 * at the beginning and ending of each message dispatch, identifying the
164 * target Handler and message contents.
165 *
166 * @param printer A Printer object that will receive log messages, or
167 * null to disable message logging.
168 */
169 public void setMessageLogging(Printer printer) {
170 mLogging = printer;
171 }
172
173 /**
174 * Return the {@link MessageQueue} object associated with the current
175 * thread. This must be called from a thread running a Looper, or a
176 * NullPointerException will be thrown.
177 */
178 public static final MessageQueue myQueue() {
179 return myLooper().mQueue;
180 }
181
182 private Looper() {
183 mQueue = new MessageQueue();
184 mRun = true;
185 mThread = Thread.currentThread();
186 }
187
188 public void quit() {
189 Message msg = Message.obtain();
190 // NOTE: By enqueueing directly into the message queue, the
191 // message is left with a null target. This is how we know it is
192 // a quit message.
193 mQueue.enqueueMessage(msg, 0);
194 }
195
196 /**
197 * Return the Thread associated with this Looper.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 */
199 public Thread getThread() {
200 return mThread;
201 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800202
Jeff Browna41ca772010-08-11 14:46:32 -0700203 /** @hide */
204 public MessageQueue getQueue() {
205 return mQueue;
206 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 public void dump(Printer pw, String prefix) {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800209 pw = PrefixPrinter.create(pw, prefix);
210 pw.println(this.toString());
211 pw.println("mRun=" + mRun);
212 pw.println("mThread=" + mThread);
213 pw.println("mQueue=" + ((mQueue != null) ? mQueue : "(null"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 if (mQueue != null) {
215 synchronized (mQueue) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700216 long now = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 Message msg = mQueue.mMessages;
218 int n = 0;
219 while (msg != null) {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800220 pw.println(" Message " + n + ": " + msg.toString(now));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 n++;
222 msg = msg.next;
223 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800224 pw.println("(Total messages: " + n + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 }
226 }
227 }
228
229 public String toString() {
230 return "Looper{"
231 + Integer.toHexString(System.identityHashCode(this))
232 + "}";
233 }
234
235 static class HandlerException extends Exception {
236
237 HandlerException(Message message, Throwable cause) {
238 super(createMessage(cause), cause);
239 }
240
241 static String createMessage(Throwable cause) {
242 String causeMsg = cause.getMessage();
243 if (causeMsg == null) {
244 causeMsg = cause.toString();
245 }
246 return causeMsg;
247 }
248 }
249}