blob: 9b3880b259b7b7854caa91232bc018cc0b84b5ae [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
Jeff Brown803c2af2015-03-05 10:52:53 -080019import android.annotation.NonNull;
20import android.annotation.Nullable;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080021import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.util.Printer;
23
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.
Jeff Brown803c2af2015-03-05 10:52:53 -080029 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030 * <p>Most interaction with a message loop is through the
31 * {@link Handler} class.
Jeff Brown803c2af2015-03-05 10:52:53 -080032 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033 * <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 */
Jeff Brown67fc67c2013-04-01 13:00:33 -070054public final class Looper {
Jeff Brown6c7b41a2015-02-26 14:43:53 -080055 /*
56 * API Implementation Note:
57 *
58 * This class contains the code required to set up and manage an event loop
59 * based on MessageQueue. APIs that affect the state of the queue should be
60 * defined on MessageQueue or Handler rather than on Looper itself. For example,
61 * idle handlers and sync barriers are defined on the queue whereas preparing the
Jeff Brown803c2af2015-03-05 10:52:53 -080062 * thread, looping, and quitting are defined on the looper.
Jeff Brown6c7b41a2015-02-26 14:43:53 -080063 */
64
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080065 private static final String TAG = "Looper";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066
67 // sThreadLocal.get() will return null unless you've called prepare().
Xavier Ducrohet7f9f99ea2011-08-11 10:16:17 -070068 static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
Jeff Brown0f85ce32012-02-16 14:41:10 -080069 private static Looper sMainLooper; // guarded by Looper.class
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070
71 final MessageQueue mQueue;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080072 final Thread mThread;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080073
Jeff Brown0f85ce32012-02-16 14:41:10 -080074 private Printer mLogging;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 /** Initialize the current thread as a looper.
77 * This gives you a chance to create handlers that then reference
78 * this looper, before actually starting the loop. Be sure to call
79 * {@link #loop()} after calling this method, and end it by calling
80 * {@link #quit()}.
81 */
Romain Guyf9284692011-07-13 18:46:21 -070082 public static void prepare() {
Jeff Brown0f85ce32012-02-16 14:41:10 -080083 prepare(true);
84 }
85
86 private static void prepare(boolean quitAllowed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 if (sThreadLocal.get() != null) {
88 throw new RuntimeException("Only one Looper may be created per thread");
89 }
Jeff Brown0f85ce32012-02-16 14:41:10 -080090 sThreadLocal.set(new Looper(quitAllowed));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080092
93 /**
94 * Initialize the current thread as a looper, marking it as an
95 * application's main looper. The main looper for your application
96 * is created by the Android environment, so you should never need
97 * to call this function yourself. See also: {@link #prepare()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 */
Romain Guyf9284692011-07-13 18:46:21 -070099 public static void prepareMainLooper() {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800100 prepare(false);
101 synchronized (Looper.class) {
102 if (sMainLooper != null) {
103 throw new IllegalStateException("The main Looper has already been prepared.");
104 }
105 sMainLooper = myLooper();
106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800108
Jeff Brown803c2af2015-03-05 10:52:53 -0800109 /**
110 * Returns the application's main looper, which lives in the main thread of the application.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 */
Jeff Brown0f85ce32012-02-16 14:41:10 -0800112 public static Looper getMainLooper() {
113 synchronized (Looper.class) {
114 return sMainLooper;
115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 }
117
118 /**
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800119 * Run the message queue in this thread. Be sure to call
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 * {@link #quit()} to end the loop.
121 */
Romain Guyf9284692011-07-13 18:46:21 -0700122 public static void loop() {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800123 final Looper me = myLooper();
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800124 if (me == null) {
125 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
126 }
Jeff Brown0f85ce32012-02-16 14:41:10 -0800127 final MessageQueue queue = me.mQueue;
128
Dianne Hackborne5dea752011-02-09 14:19:23 -0800129 // Make sure the identity of this thread is that of the local process,
130 // and keep track of what that identity token actually is.
131 Binder.clearCallingIdentity();
132 final long ident = Binder.clearCallingIdentity();
Jeff Brown0f85ce32012-02-16 14:41:10 -0800133
134 for (;;) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 Message msg = queue.next(); // might block
Jeff Brown0f85ce32012-02-16 14:41:10 -0800136 if (msg == null) {
137 // No message indicates that the message queue is quitting.
138 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 }
Jeff Brown0f85ce32012-02-16 14:41:10 -0800140
Jeff Brown0f85ce32012-02-16 14:41:10 -0800141 // This must be in a local variable, in case a UI event sets the logger
142 Printer logging = me.mLogging;
143 if (logging != null) {
144 logging.println(">>>>> Dispatching to " + msg.target + " " +
145 msg.callback + ": " + msg.what);
Jeff Brown0f85ce32012-02-16 14:41:10 -0800146 }
147
148 msg.target.dispatchMessage(msg);
149
150 if (logging != null) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800151 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
Jeff Brown0f85ce32012-02-16 14:41:10 -0800152 }
153
154 // Make sure that during the course of dispatching the
155 // identity of the thread wasn't corrupted.
156 final long newIdent = Binder.clearCallingIdentity();
157 if (ident != newIdent) {
158 Log.wtf(TAG, "Thread identity changed from 0x"
159 + Long.toHexString(ident) + " to 0x"
160 + Long.toHexString(newIdent) + " while dispatching to "
161 + msg.target.getClass().getName() + " "
162 + msg.callback + " what=" + msg.what);
163 }
164
Jeff Brown9867ed72014-02-28 14:00:57 -0800165 msg.recycleUnchecked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 }
167 }
168
169 /**
170 * Return the Looper object associated with the current thread. Returns
171 * null if the calling thread is not associated with a Looper.
172 */
Jeff Brown803c2af2015-03-05 10:52:53 -0800173 public static @Nullable Looper myLooper() {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800174 return sThreadLocal.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 }
176
177 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 * Return the {@link MessageQueue} object associated with the current
179 * thread. This must be called from a thread running a Looper, or a
180 * NullPointerException will be thrown.
181 */
Jeff Brown803c2af2015-03-05 10:52:53 -0800182 public static @NonNull MessageQueue myQueue() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 return myLooper().mQueue;
184 }
185
Jeff Brown0f85ce32012-02-16 14:41:10 -0800186 private Looper(boolean quitAllowed) {
187 mQueue = new MessageQueue(quitAllowed);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 mThread = Thread.currentThread();
189 }
190
Jeff Brown0f85ce32012-02-16 14:41:10 -0800191 /**
Jeff Brownf9e989d2013-04-04 23:04:03 -0700192 * Returns true if the current thread is this looper's thread.
Jeff Brownf9e989d2013-04-04 23:04:03 -0700193 */
194 public boolean isCurrentThread() {
195 return Thread.currentThread() == mThread;
196 }
197
198 /**
Jeff Brown803c2af2015-03-05 10:52:53 -0800199 * Control logging of messages as they are processed by this Looper. If
200 * enabled, a log message will be written to <var>printer</var>
201 * at the beginning and ending of each message dispatch, identifying the
202 * target Handler and message contents.
203 *
204 * @param printer A Printer object that will receive log messages, or
205 * null to disable message logging.
206 */
207 public void setMessageLogging(@Nullable Printer printer) {
208 mLogging = printer;
209 }
210
211 /**
Jeff Brown0f85ce32012-02-16 14:41:10 -0800212 * Quits the looper.
Jeff Brown024136f2013-04-11 19:21:32 -0700213 * <p>
Jeff Brown8b60e452013-04-18 15:17:48 -0700214 * Causes the {@link #loop} method to terminate without processing any
215 * more messages in the message queue.
Jeff Brown024136f2013-04-11 19:21:32 -0700216 * </p><p>
Jeff Brown8b60e452013-04-18 15:17:48 -0700217 * Any attempt to post messages to the queue after the looper is asked to quit will fail.
218 * For example, the {@link Handler#sendMessage(Message)} method will return false.
219 * </p><p class="note">
220 * Using this method may be unsafe because some messages may not be delivered
221 * before the looper terminates. Consider using {@link #quitSafely} instead to ensure
222 * that all pending work is completed in an orderly manner.
Jeff Brown024136f2013-04-11 19:21:32 -0700223 * </p>
Jeff Brown8b60e452013-04-18 15:17:48 -0700224 *
225 * @see #quitSafely
Jeff Brown0f85ce32012-02-16 14:41:10 -0800226 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 public void quit() {
Jeff Brown8b60e452013-04-18 15:17:48 -0700228 mQueue.quit(false);
229 }
230
231 /**
232 * Quits the looper safely.
233 * <p>
234 * Causes the {@link #loop} method to terminate as soon as all remaining messages
235 * in the message queue that are already due to be delivered have been handled.
236 * However pending delayed messages with due times in the future will not be
237 * delivered before the loop terminates.
238 * </p><p>
239 * Any attempt to post messages to the queue after the looper is asked to quit will fail.
240 * For example, the {@link Handler#sendMessage(Message)} method will return false.
241 * </p>
242 */
243 public void quitSafely() {
244 mQueue.quit(true);
Jeff Brown0f85ce32012-02-16 14:41:10 -0800245 }
246
247 /**
Jeff Brown803c2af2015-03-05 10:52:53 -0800248 * Gets the Thread associated with this Looper.
249 *
250 * @return The looper's thread.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 */
Jeff Brown803c2af2015-03-05 10:52:53 -0800252 public @NonNull Thread getThread() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 return mThread;
254 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800255
Jeff Brown803c2af2015-03-05 10:52:53 -0800256 /**
257 * Gets this looper's message queue.
258 *
259 * @return The looper's message queue.
260 */
261 public @NonNull MessageQueue getQueue() {
Jeff Browna41ca772010-08-11 14:46:32 -0700262 return mQueue;
263 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800264
Jeff Brown803c2af2015-03-05 10:52:53 -0800265 /**
266 * Dumps the state of the looper for debugging purposes.
267 *
268 * @param pw A printer to receive the contents of the dump.
269 * @param prefix A prefix to prepend to each line which is printed.
270 */
271 public void dump(@NonNull Printer pw, @NonNull String prefix) {
Jeff Brown5182c782013-10-15 20:31:52 -0700272 pw.println(prefix + toString());
273 mQueue.dump(pw, prefix + " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 }
275
276 public String toString() {
Jeff Brown5182c782013-10-15 20:31:52 -0700277 return "Looper (" + mThread.getName() + ", tid " + mThread.getId()
278 + ") {" + Integer.toHexString(System.identityHashCode(this)) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280}