blob: 44dbcfb09582748d783ccb290221d95eea0eb615 [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;
Netta P958d0a52017-02-07 11:20:55 -080021import android.os.LooperProto;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080022import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.util.Printer;
Makoto Onuki99571512017-03-28 14:12:34 -070024import android.util.Slog;
Netta P958d0a52017-02-07 11:20:55 -080025import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
27/**
28 * Class used to run a message loop for a thread. Threads by default do
29 * not have a message loop associated with them; to create one, call
30 * {@link #prepare} in the thread that is to run the loop, and then
31 * {@link #loop} to have it process messages until the loop is stopped.
Jeff Brown803c2af2015-03-05 10:52:53 -080032 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033 * <p>Most interaction with a message loop is through the
34 * {@link Handler} class.
Jeff Brown803c2af2015-03-05 10:52:53 -080035 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036 * <p>This is a typical example of the implementation of a Looper thread,
37 * using the separation of {@link #prepare} and {@link #loop} to create an
38 * initial Handler to communicate with the Looper.
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080039 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040 * <pre>
41 * class LooperThread extends Thread {
42 * public Handler mHandler;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080043 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044 * public void run() {
45 * Looper.prepare();
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080046 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047 * mHandler = new Handler() {
48 * public void handleMessage(Message msg) {
49 * // process incoming messages here
50 * }
51 * };
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080052 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053 * Looper.loop();
54 * }
55 * }</pre>
56 */
Jeff Brown67fc67c2013-04-01 13:00:33 -070057public final class Looper {
Jeff Brown6c7b41a2015-02-26 14:43:53 -080058 /*
59 * API Implementation Note:
60 *
61 * This class contains the code required to set up and manage an event loop
62 * based on MessageQueue. APIs that affect the state of the queue should be
63 * defined on MessageQueue or Handler rather than on Looper itself. For example,
64 * idle handlers and sync barriers are defined on the queue whereas preparing the
Jeff Brown803c2af2015-03-05 10:52:53 -080065 * thread, looping, and quitting are defined on the looper.
Jeff Brown6c7b41a2015-02-26 14:43:53 -080066 */
67
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080068 private static final String TAG = "Looper";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
70 // sThreadLocal.get() will return null unless you've called prepare().
Xavier Ducrohet7f9f99ea2011-08-11 10:16:17 -070071 static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
Jeff Brown0f85ce32012-02-16 14:41:10 -080072 private static Looper sMainLooper; // guarded by Looper.class
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073
74 final MessageQueue mQueue;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080075 final Thread mThread;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080076
Jeff Brown0f85ce32012-02-16 14:41:10 -080077 private Printer mLogging;
Jeff Sharkey74cd3de2016-04-06 17:40:54 -060078 private long mTraceTag;
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080079
Makoto Onuki99571512017-03-28 14:12:34 -070080 /* If set, the looper will show a warning log if a message dispatch takes longer than time. */
81 private long mSlowDispatchThresholdMs;
82
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 /** Initialize the current thread as a looper.
84 * This gives you a chance to create handlers that then reference
85 * this looper, before actually starting the loop. Be sure to call
86 * {@link #loop()} after calling this method, and end it by calling
87 * {@link #quit()}.
88 */
Romain Guyf9284692011-07-13 18:46:21 -070089 public static void prepare() {
Jeff Brown0f85ce32012-02-16 14:41:10 -080090 prepare(true);
91 }
92
93 private static void prepare(boolean quitAllowed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 if (sThreadLocal.get() != null) {
95 throw new RuntimeException("Only one Looper may be created per thread");
96 }
Jeff Brown0f85ce32012-02-16 14:41:10 -080097 sThreadLocal.set(new Looper(quitAllowed));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -080099
100 /**
101 * Initialize the current thread as a looper, marking it as an
102 * application's main looper. The main looper for your application
103 * is created by the Android environment, so you should never need
104 * to call this function yourself. See also: {@link #prepare()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 */
Romain Guyf9284692011-07-13 18:46:21 -0700106 public static void prepareMainLooper() {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800107 prepare(false);
108 synchronized (Looper.class) {
109 if (sMainLooper != null) {
110 throw new IllegalStateException("The main Looper has already been prepared.");
111 }
112 sMainLooper = myLooper();
113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800115
Jeff Brown803c2af2015-03-05 10:52:53 -0800116 /**
117 * 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 -0800118 */
Jeff Brown0f85ce32012-02-16 14:41:10 -0800119 public static Looper getMainLooper() {
120 synchronized (Looper.class) {
121 return sMainLooper;
122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 }
124
125 /**
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800126 * Run the message queue in this thread. Be sure to call
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 * {@link #quit()} to end the loop.
128 */
Romain Guyf9284692011-07-13 18:46:21 -0700129 public static void loop() {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800130 final Looper me = myLooper();
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800131 if (me == null) {
132 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
133 }
Jeff Brown0f85ce32012-02-16 14:41:10 -0800134 final MessageQueue queue = me.mQueue;
135
Dianne Hackborne5dea752011-02-09 14:19:23 -0800136 // Make sure the identity of this thread is that of the local process,
137 // and keep track of what that identity token actually is.
138 Binder.clearCallingIdentity();
139 final long ident = Binder.clearCallingIdentity();
Jeff Brown0f85ce32012-02-16 14:41:10 -0800140
141 for (;;) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 Message msg = queue.next(); // might block
Jeff Brown0f85ce32012-02-16 14:41:10 -0800143 if (msg == null) {
144 // No message indicates that the message queue is quitting.
145 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146 }
Jeff Brown0f85ce32012-02-16 14:41:10 -0800147
Jeff Brown0f85ce32012-02-16 14:41:10 -0800148 // This must be in a local variable, in case a UI event sets the logger
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600149 final Printer logging = me.mLogging;
Jeff Brown0f85ce32012-02-16 14:41:10 -0800150 if (logging != null) {
151 logging.println(">>>>> Dispatching to " + msg.target + " " +
152 msg.callback + ": " + msg.what);
Jeff Brown0f85ce32012-02-16 14:41:10 -0800153 }
154
Makoto Onuki99571512017-03-28 14:12:34 -0700155 final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
156
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600157 final long traceTag = me.mTraceTag;
Jorim Jaggi407c0be2016-08-01 13:31:55 +0200158 if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600159 Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
160 }
Makoto Onuki99571512017-03-28 14:12:34 -0700161 final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
162 final long end;
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600163 try {
164 msg.target.dispatchMessage(msg);
Makoto Onuki99571512017-03-28 14:12:34 -0700165 end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600166 } finally {
167 if (traceTag != 0) {
168 Trace.traceEnd(traceTag);
169 }
170 }
Makoto Onuki99571512017-03-28 14:12:34 -0700171 if (slowDispatchThresholdMs > 0) {
172 final long time = end - start;
173 if (time > slowDispatchThresholdMs) {
174 Slog.w(TAG, "Dispatch took " + time + "ms on "
175 + Thread.currentThread().getName() + ", h=" +
176 msg.target + " cb=" + msg.callback + " msg=" + msg.what);
177 }
178 }
Jeff Brown0f85ce32012-02-16 14:41:10 -0800179
180 if (logging != null) {
Jeff Brown0f85ce32012-02-16 14:41:10 -0800181 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
Jeff Brown0f85ce32012-02-16 14:41:10 -0800182 }
183
184 // Make sure that during the course of dispatching the
185 // identity of the thread wasn't corrupted.
186 final long newIdent = Binder.clearCallingIdentity();
187 if (ident != newIdent) {
188 Log.wtf(TAG, "Thread identity changed from 0x"
189 + Long.toHexString(ident) + " to 0x"
190 + Long.toHexString(newIdent) + " while dispatching to "
191 + msg.target.getClass().getName() + " "
192 + msg.callback + " what=" + msg.what);
193 }
194
Jeff Brown9867ed72014-02-28 14:00:57 -0800195 msg.recycleUnchecked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 }
197 }
198
199 /**
200 * Return the Looper object associated with the current thread. Returns
201 * null if the calling thread is not associated with a Looper.
202 */
Jeff Brown803c2af2015-03-05 10:52:53 -0800203 public static @Nullable Looper myLooper() {
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800204 return sThreadLocal.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 }
206
207 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 * Return the {@link MessageQueue} object associated with the current
209 * thread. This must be called from a thread running a Looper, or a
210 * NullPointerException will be thrown.
211 */
Jeff Brown803c2af2015-03-05 10:52:53 -0800212 public static @NonNull MessageQueue myQueue() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 return myLooper().mQueue;
214 }
215
Jeff Brown0f85ce32012-02-16 14:41:10 -0800216 private Looper(boolean quitAllowed) {
217 mQueue = new MessageQueue(quitAllowed);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 mThread = Thread.currentThread();
219 }
220
Jeff Brown0f85ce32012-02-16 14:41:10 -0800221 /**
Jeff Brownf9e989d2013-04-04 23:04:03 -0700222 * Returns true if the current thread is this looper's thread.
Jeff Brownf9e989d2013-04-04 23:04:03 -0700223 */
224 public boolean isCurrentThread() {
225 return Thread.currentThread() == mThread;
226 }
227
228 /**
Jeff Brown803c2af2015-03-05 10:52:53 -0800229 * Control logging of messages as they are processed by this Looper. If
230 * enabled, a log message will be written to <var>printer</var>
231 * at the beginning and ending of each message dispatch, identifying the
232 * target Handler and message contents.
233 *
234 * @param printer A Printer object that will receive log messages, or
235 * null to disable message logging.
236 */
237 public void setMessageLogging(@Nullable Printer printer) {
238 mLogging = printer;
239 }
240
Jeff Sharkey74cd3de2016-04-06 17:40:54 -0600241 /** {@hide} */
242 public void setTraceTag(long traceTag) {
243 mTraceTag = traceTag;
244 }
245
Makoto Onuki99571512017-03-28 14:12:34 -0700246 /** {@hide} */
247 public void setSlowDispatchThresholdMs(long slowDispatchThresholdMs) {
248 mSlowDispatchThresholdMs = slowDispatchThresholdMs;
249 }
250
Jeff Brown803c2af2015-03-05 10:52:53 -0800251 /**
Jeff Brown0f85ce32012-02-16 14:41:10 -0800252 * Quits the looper.
Jeff Brown024136f2013-04-11 19:21:32 -0700253 * <p>
Jeff Brown8b60e452013-04-18 15:17:48 -0700254 * Causes the {@link #loop} method to terminate without processing any
255 * more messages in the message queue.
Jeff Brown024136f2013-04-11 19:21:32 -0700256 * </p><p>
Jeff Brown8b60e452013-04-18 15:17:48 -0700257 * Any attempt to post messages to the queue after the looper is asked to quit will fail.
258 * For example, the {@link Handler#sendMessage(Message)} method will return false.
259 * </p><p class="note">
260 * Using this method may be unsafe because some messages may not be delivered
261 * before the looper terminates. Consider using {@link #quitSafely} instead to ensure
262 * that all pending work is completed in an orderly manner.
Jeff Brown024136f2013-04-11 19:21:32 -0700263 * </p>
Jeff Brown8b60e452013-04-18 15:17:48 -0700264 *
265 * @see #quitSafely
Jeff Brown0f85ce32012-02-16 14:41:10 -0800266 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 public void quit() {
Jeff Brown8b60e452013-04-18 15:17:48 -0700268 mQueue.quit(false);
269 }
270
271 /**
272 * Quits the looper safely.
273 * <p>
274 * Causes the {@link #loop} method to terminate as soon as all remaining messages
275 * in the message queue that are already due to be delivered have been handled.
276 * However pending delayed messages with due times in the future will not be
277 * delivered before the loop terminates.
278 * </p><p>
279 * Any attempt to post messages to the queue after the looper is asked to quit will fail.
280 * For example, the {@link Handler#sendMessage(Message)} method will return false.
281 * </p>
282 */
283 public void quitSafely() {
284 mQueue.quit(true);
Jeff Brown0f85ce32012-02-16 14:41:10 -0800285 }
286
287 /**
Jeff Brown803c2af2015-03-05 10:52:53 -0800288 * Gets the Thread associated with this Looper.
289 *
290 * @return The looper's thread.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 */
Jeff Brown803c2af2015-03-05 10:52:53 -0800292 public @NonNull Thread getThread() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 return mThread;
294 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800295
Jeff Brown803c2af2015-03-05 10:52:53 -0800296 /**
297 * Gets this looper's message queue.
298 *
299 * @return The looper's message queue.
300 */
301 public @NonNull MessageQueue getQueue() {
Jeff Browna41ca772010-08-11 14:46:32 -0700302 return mQueue;
303 }
Brad Fitzpatrick1b298252010-11-23 17:16:47 -0800304
Jeff Brown803c2af2015-03-05 10:52:53 -0800305 /**
306 * Dumps the state of the looper for debugging purposes.
307 *
308 * @param pw A printer to receive the contents of the dump.
309 * @param prefix A prefix to prepend to each line which is printed.
310 */
311 public void dump(@NonNull Printer pw, @NonNull String prefix) {
Jeff Brown5182c782013-10-15 20:31:52 -0700312 pw.println(prefix + toString());
313 mQueue.dump(pw, prefix + " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 }
315
Netta P958d0a52017-02-07 11:20:55 -0800316 /** @hide */
317 public void writeToProto(ProtoOutputStream proto, long fieldId) {
318 final long looperToken = proto.start(fieldId);
319 proto.write(LooperProto.THREAD_NAME, mThread.getName());
320 proto.write(LooperProto.THREAD_ID, mThread.getId());
321 proto.write(LooperProto.IDENTITY_HASH_CODE, System.identityHashCode(this));
322 mQueue.writeToProto(proto, LooperProto.QUEUE);
323 proto.end(looperToken);
324 }
325
Jeff Browndc3eb4b2015-03-05 18:21:06 -0800326 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 public String toString() {
Jeff Brown5182c782013-10-15 20:31:52 -0700328 return "Looper (" + mThread.getName() + ", tid " + mThread.getId()
329 + ") {" + Integer.toHexString(System.identityHashCode(this)) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331}