blob: d299672ea1d5e15b3d7375d888595c4e0a774435 [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;
Jeff Sharkey74cd3de2016-04-06 17:40:54 -060075 private long mTraceTag;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 /** Initialize the current thread as a looper.
78 * This gives you a chance to create handlers that then reference
79 * this looper, before actually starting the loop. Be sure to call
80 * {@link #loop()} after calling this method, and end it by calling
81 * {@link #quit()}.
82 */
Romain Guyf9284692011-07-13 18:46:21 -070083 public static void prepare() {
Jeff Brown0f85ce32012-02-16 14:41:10 -080084 prepare(true);
85 }
86
87 private static void prepare(boolean quitAllowed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 if (sThreadLocal.get() != null) {
89 throw new RuntimeException("Only one Looper may be created per thread");
90 }
Jeff Brown0f85ce32012-02-16 14:41:10 -080091 sThreadLocal.set(new Looper(quitAllowed));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080093
94 /**
95 * Initialize the current thread as a looper, marking it as an
96 * application's main looper. The main looper for your application
97 * is created by the Android environment, so you should never need
98 * to call this function yourself. See also: {@link #prepare()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 */
Romain Guyf9284692011-07-13 18:46:21 -0700100 public static void prepareMainLooper() {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800101 prepare(false);
102 synchronized (Looper.class) {
103 if (sMainLooper != null) {
104 throw new IllegalStateException("The main Looper has already been prepared.");
105 }
106 sMainLooper = myLooper();
107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800109
Jeff Brown803c2af2015-03-05 10:52:53 -0800110 /**
111 * 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 -0800112 */
Jeff Brown0f85ce32012-02-16 14:41:10 -0800113 public static Looper getMainLooper() {
114 synchronized (Looper.class) {
115 return sMainLooper;
116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 }
118
119 /**
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800120 * Run the message queue in this thread. Be sure to call
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 * {@link #quit()} to end the loop.
122 */
Romain Guyf9284692011-07-13 18:46:21 -0700123 public static void loop() {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800124 final Looper me = myLooper();
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800125 if (me == null) {
126 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
127 }
Jeff Brown0f85ce32012-02-16 14:41:10 -0800128 final MessageQueue queue = me.mQueue;
129
Dianne Hackborne5dea752011-02-09 14:19:23 -0800130 // Make sure the identity of this thread is that of the local process,
131 // and keep track of what that identity token actually is.
132 Binder.clearCallingIdentity();
133 final long ident = Binder.clearCallingIdentity();
Jeff Brown0f85ce32012-02-16 14:41:10 -0800134
135 for (;;) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 Message msg = queue.next(); // might block
Jeff Brown0f85ce32012-02-16 14:41:10 -0800137 if (msg == null) {
138 // No message indicates that the message queue is quitting.
139 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 }
Jeff Brown0f85ce32012-02-16 14:41:10 -0800141
Jeff Brown0f85ce32012-02-16 14:41:10 -0800142 // This must be in a local variable, in case a UI event sets the logger
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600143 final Printer logging = me.mLogging;
Jeff Brown0f85ce32012-02-16 14:41:10 -0800144 if (logging != null) {
145 logging.println(">>>>> Dispatching to " + msg.target + " " +
146 msg.callback + ": " + msg.what);
Jeff Brown0f85ce32012-02-16 14:41:10 -0800147 }
148
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600149 final long traceTag = me.mTraceTag;
Jorim Jaggi407c0be2016-08-01 13:31:55 +0200150 if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600151 Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
152 }
153 try {
154 msg.target.dispatchMessage(msg);
155 } finally {
156 if (traceTag != 0) {
157 Trace.traceEnd(traceTag);
158 }
159 }
Jeff Brown0f85ce32012-02-16 14:41:10 -0800160
161 if (logging != null) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800162 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
Jeff Brown0f85ce32012-02-16 14:41:10 -0800163 }
164
165 // Make sure that during the course of dispatching the
166 // identity of the thread wasn't corrupted.
167 final long newIdent = Binder.clearCallingIdentity();
168 if (ident != newIdent) {
169 Log.wtf(TAG, "Thread identity changed from 0x"
170 + Long.toHexString(ident) + " to 0x"
171 + Long.toHexString(newIdent) + " while dispatching to "
172 + msg.target.getClass().getName() + " "
173 + msg.callback + " what=" + msg.what);
174 }
175
Jeff Brown9867ed72014-02-28 14:00:57 -0800176 msg.recycleUnchecked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 }
178 }
179
180 /**
181 * Return the Looper object associated with the current thread. Returns
182 * null if the calling thread is not associated with a Looper.
183 */
Jeff Brown803c2af2015-03-05 10:52:53 -0800184 public static @Nullable Looper myLooper() {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800185 return sThreadLocal.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 }
187
188 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 * Return the {@link MessageQueue} object associated with the current
190 * thread. This must be called from a thread running a Looper, or a
191 * NullPointerException will be thrown.
192 */
Jeff Brown803c2af2015-03-05 10:52:53 -0800193 public static @NonNull MessageQueue myQueue() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 return myLooper().mQueue;
195 }
196
Jeff Brown0f85ce32012-02-16 14:41:10 -0800197 private Looper(boolean quitAllowed) {
198 mQueue = new MessageQueue(quitAllowed);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 mThread = Thread.currentThread();
200 }
201
Jeff Brown0f85ce32012-02-16 14:41:10 -0800202 /**
Jeff Brownf9e989d2013-04-04 23:04:03 -0700203 * Returns true if the current thread is this looper's thread.
Jeff Brownf9e989d2013-04-04 23:04:03 -0700204 */
205 public boolean isCurrentThread() {
206 return Thread.currentThread() == mThread;
207 }
208
209 /**
Jeff Brown803c2af2015-03-05 10:52:53 -0800210 * Control logging of messages as they are processed by this Looper. If
211 * enabled, a log message will be written to <var>printer</var>
212 * at the beginning and ending of each message dispatch, identifying the
213 * target Handler and message contents.
214 *
215 * @param printer A Printer object that will receive log messages, or
216 * null to disable message logging.
217 */
218 public void setMessageLogging(@Nullable Printer printer) {
219 mLogging = printer;
220 }
221
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600222 /** {@hide} */
223 public void setTraceTag(long traceTag) {
224 mTraceTag = traceTag;
225 }
226
Jeff Brown803c2af2015-03-05 10:52:53 -0800227 /**
Jeff Brown0f85ce32012-02-16 14:41:10 -0800228 * Quits the looper.
Jeff Brown024136f2013-04-11 19:21:32 -0700229 * <p>
Jeff Brown8b60e452013-04-18 15:17:48 -0700230 * Causes the {@link #loop} method to terminate without processing any
231 * more messages in the message queue.
Jeff Brown024136f2013-04-11 19:21:32 -0700232 * </p><p>
Jeff Brown8b60e452013-04-18 15:17:48 -0700233 * Any attempt to post messages to the queue after the looper is asked to quit will fail.
234 * For example, the {@link Handler#sendMessage(Message)} method will return false.
235 * </p><p class="note">
236 * Using this method may be unsafe because some messages may not be delivered
237 * before the looper terminates. Consider using {@link #quitSafely} instead to ensure
238 * that all pending work is completed in an orderly manner.
Jeff Brown024136f2013-04-11 19:21:32 -0700239 * </p>
Jeff Brown8b60e452013-04-18 15:17:48 -0700240 *
241 * @see #quitSafely
Jeff Brown0f85ce32012-02-16 14:41:10 -0800242 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 public void quit() {
Jeff Brown8b60e452013-04-18 15:17:48 -0700244 mQueue.quit(false);
245 }
246
247 /**
248 * Quits the looper safely.
249 * <p>
250 * Causes the {@link #loop} method to terminate as soon as all remaining messages
251 * in the message queue that are already due to be delivered have been handled.
252 * However pending delayed messages with due times in the future will not be
253 * delivered before the loop terminates.
254 * </p><p>
255 * Any attempt to post messages to the queue after the looper is asked to quit will fail.
256 * For example, the {@link Handler#sendMessage(Message)} method will return false.
257 * </p>
258 */
259 public void quitSafely() {
260 mQueue.quit(true);
Jeff Brown0f85ce32012-02-16 14:41:10 -0800261 }
262
263 /**
Jeff Brown803c2af2015-03-05 10:52:53 -0800264 * Gets the Thread associated with this Looper.
265 *
266 * @return The looper's thread.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 */
Jeff Brown803c2af2015-03-05 10:52:53 -0800268 public @NonNull Thread getThread() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 return mThread;
270 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800271
Jeff Brown803c2af2015-03-05 10:52:53 -0800272 /**
273 * Gets this looper's message queue.
274 *
275 * @return The looper's message queue.
276 */
277 public @NonNull MessageQueue getQueue() {
Jeff Browna41ca772010-08-11 14:46:32 -0700278 return mQueue;
279 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800280
Jeff Brown803c2af2015-03-05 10:52:53 -0800281 /**
282 * Dumps the state of the looper for debugging purposes.
283 *
284 * @param pw A printer to receive the contents of the dump.
285 * @param prefix A prefix to prepend to each line which is printed.
286 */
287 public void dump(@NonNull Printer pw, @NonNull String prefix) {
Jeff Brown5182c782013-10-15 20:31:52 -0700288 pw.println(prefix + toString());
289 mQueue.dump(pw, prefix + " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 }
291
Jeff Browndc3eb4b2015-03-05 18:21:06 -0800292 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 public String toString() {
Jeff Brown5182c782013-10-15 20:31:52 -0700294 return "Looper (" + mThread.getName() + ", tid " + mThread.getId()
295 + ") {" + Integer.toHexString(System.identityHashCode(this)) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297}