blob: ccf642c877e1b97a7f50f6e22ba8384458ec7a21 [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
19import android.util.Config;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080020import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.util.Printer;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080022import android.util.PrefixPrinter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023
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.
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080036 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037 * <pre>
38 * class LooperThread extends Thread {
39 * public Handler mHandler;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080040 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041 * public void run() {
42 * Looper.prepare();
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080043 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044 * mHandler = new Handler() {
45 * public void handleMessage(Message msg) {
46 * // process incoming messages here
47 * }
48 * };
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080049 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050 * Looper.loop();
51 * }
52 * }</pre>
53 */
54public class Looper {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080055 private static final String TAG = "Looper";
56 private static final boolean LOG_V = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057
58 // sThreadLocal.get() will return null unless you've called prepare().
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080059 private static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060
61 final MessageQueue mQueue;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080062 final Thread mThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063 volatile boolean mRun;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065 private Printer mLogging = null;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080066 private static Looper mMainLooper = null; // guarded by Looper.class
67
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 /** 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 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080080
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()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 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 }
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 */
101 public synchronized static final Looper getMainLooper() {
102 return mMainLooper;
103 }
104
105 /**
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800106 * Run the message queue in this thread. Be sure to call
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 * {@link #quit()} to end the loop.
108 */
109 public static final void loop() {
110 Looper me = myLooper();
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800111 if (me == null) {
112 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 MessageQueue queue = me.mQueue;
Dianne Hackborne5dea752011-02-09 14:19:23 -0800115
116 // Make sure the identity of this thread is that of the local process,
117 // and keep track of what that identity token actually is.
118 Binder.clearCallingIdentity();
119 final long ident = Binder.clearCallingIdentity();
120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 while (true) {
122 Message msg = queue.next(); // might block
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 if (msg != null) {
124 if (msg.target == null) {
125 // No target is a magic identifier for the quit message.
126 return;
127 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800128 if (me.mLogging != null) me.mLogging.println(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 ">>>>> Dispatching to " + msg.target + " "
130 + msg.callback + ": " + msg.what
131 );
132 msg.target.dispatchMessage(msg);
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800133 if (me.mLogging != null) me.mLogging.println(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 "<<<<< Finished to " + msg.target + " "
135 + msg.callback);
Dianne Hackborne5dea752011-02-09 14:19:23 -0800136
137 // Make sure that during the course of dispatching the
138 // identity of the thread wasn't corrupted.
139 final long newIdent = Binder.clearCallingIdentity();
140 if (ident != newIdent) {
141 Log.wtf("Looper", "Thread identity changed from 0x"
142 + Long.toHexString(ident) + " to 0x"
143 + Long.toHexString(newIdent) + " while dispatching to "
Dianne Hackborn1ab43772011-03-15 14:38:02 -0700144 + msg.target.getClass().getName() + " "
145 + msg.callback + " what=" + msg.what);
Dianne Hackborne5dea752011-02-09 14:19:23 -0800146 }
147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 msg.recycle();
149 }
150 }
151 }
152
153 /**
154 * Return the Looper object associated with the current thread. Returns
155 * null if the calling thread is not associated with a Looper.
156 */
157 public static final Looper myLooper() {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800158 return sThreadLocal.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 }
160
161 /**
162 * Control logging of messages as they are processed by this Looper. If
163 * enabled, a log message will be written to <var>printer</var>
164 * at the beginning and ending of each message dispatch, identifying the
165 * target Handler and message contents.
166 *
167 * @param printer A Printer object that will receive log messages, or
168 * null to disable message logging.
169 */
170 public void setMessageLogging(Printer printer) {
171 mLogging = printer;
172 }
173
174 /**
175 * Return the {@link MessageQueue} object associated with the current
176 * thread. This must be called from a thread running a Looper, or a
177 * NullPointerException will be thrown.
178 */
179 public static final MessageQueue myQueue() {
180 return myLooper().mQueue;
181 }
182
183 private Looper() {
184 mQueue = new MessageQueue();
185 mRun = true;
186 mThread = Thread.currentThread();
187 }
188
189 public void quit() {
190 Message msg = Message.obtain();
191 // NOTE: By enqueueing directly into the message queue, the
192 // message is left with a null target. This is how we know it is
193 // a quit message.
194 mQueue.enqueueMessage(msg, 0);
195 }
196
197 /**
198 * Return the Thread associated with this Looper.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 */
200 public Thread getThread() {
201 return mThread;
202 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800203
Jeff Browna41ca772010-08-11 14:46:32 -0700204 /** @hide */
205 public MessageQueue getQueue() {
206 return mQueue;
207 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 public void dump(Printer pw, String prefix) {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800210 pw = PrefixPrinter.create(pw, prefix);
211 pw.println(this.toString());
212 pw.println("mRun=" + mRun);
213 pw.println("mThread=" + mThread);
214 pw.println("mQueue=" + ((mQueue != null) ? mQueue : "(null"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 if (mQueue != null) {
216 synchronized (mQueue) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700217 long now = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 Message msg = mQueue.mMessages;
219 int n = 0;
220 while (msg != null) {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800221 pw.println(" Message " + n + ": " + msg.toString(now));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 n++;
223 msg = msg.next;
224 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800225 pw.println("(Total messages: " + n + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 }
227 }
228 }
229
230 public String toString() {
231 return "Looper{"
232 + Integer.toHexString(System.identityHashCode(this))
233 + "}";
234 }
235
236 static class HandlerException extends Exception {
237
238 HandlerException(Message message, Throwable cause) {
239 super(createMessage(cause), cause);
240 }
241
242 static String createMessage(Throwable cause) {
243 String causeMsg = cause.getMessage();
244 if (causeMsg == null) {
245 causeMsg = cause.toString();
246 }
247 return causeMsg;
248 }
249 }
250}