Android from the foundation · Puzzle 17 · 18 of 23
Frames, jank and ANRs
Drawing the screen is just another message in the main thread's queue. So one slow message doesn't only delay a tap: it stops the screen from being drawn.
The problem
In puzzle 16, the main thread ran messages one at a time. Now suppose one message takes a long time, like reading a big file, or a Thread.sleep(6000) in a button's click code, which pauses the thread for 6 seconds. What does the user see?
See it
The screen is redrawn 60 times a second; each redraw is a frame, due about every 16 milliseconds (ms). Each frame is a message in the main thread's queue.
Step 1 of 4One message takes too long. The frames behind it can't be drawn in time, and the app stutters: jank.
Step 2 of 4The user taps. system_server sends the touch down a direct line into your app, and it waits in the queue too. Predict: what if it waits much longer?
Step 3 of 4system_server waits for your app to answer "done" on that line, which only happens once the main thread has handled the touch. After 5 seconds with no answer, it shows "App isn't responding": an ANR (Application Not Responding).
Step 4 of 4
The building block
The screen is redrawn about 60 times a second. Each redraw is a frame, and each one must be ready within about 16 milliseconds (1000 ms ÷ 60). Drawing a frame is a message in the main thread's queue too.
If a message takes longer than that, the frames behind it come late, and the app visibly stutters: jank.
Touches don't travel by Binder. Each screen your app shows is drawn in a window, its rectangle of the display, and for each window system_server opens a direct line into your app, an input channel. It sends each touch down that line, where it lands in the main thread's queue, and waits for your app to answer "done" on that same line, which it does once the main thread has handled the touch. If a touch waits in the queue for 5 seconds with no answer, system_server shows the "App isn't responding" dialog: an ANR (Application Not Responding). That's why slow work (files, network, big calculations) belongs on another thread, never on the main thread.
The analogy
The clerk also has to repaint the shop window 60 times a second. One long phone call, and the window freezes; keep a customer waiting long enough, and the town hall puts up a sign: "not responding".
Check yourself
Sources
- Android Developers: Slow rendering (jank)
- AOSP: InputChannel.java ("An input channel specifies the file descriptors used to send input events to a window in another process") and InputEventReceiver.java (
finishInputEvent(event, handled)) - Android Developers: ANRs
What you now know
A frame is due about every 16 ms. A message that takes longer makes frames late: jank. A touch that waits 5 seconds gets the "App isn't responding" dialog: an ANR.
Answer every question above correctly to unlock the next puzzle.
Something wrong or unclear on this page? Tell me: a puzzle that didn't click is a bug in the puzzle.