What you’ll study
- What a window is in Android, and the three players that put one on screen: the window, its manager in your app, and the system’s window manager service.
- What happens, in order, when your code calls
WindowManager.addView(): eleven steps across three processes, each a class and method in AOSP. - Which two calls cross into the system process through Binder, and what each one asks for.
- Why the window’s surface is not made when the window is added, but by the first relayout after it.
- What the system checks before it lets a window in, and what you see when the check fails.
- Where to look next: SurfaceFlinger, the Hardware Composer, and tools to watch it happen.
How it connects
This guide stands alone on the Android internals shelf, and it sits under several others. Guide 3 followed a frame from vsync to the screen; this one follows the window that frame is drawn into. Guide 4 followed a touch to your app, and the input channel that addWindow opens is the other end of that path. Guide 8 drew into a surface of its own next to the app’s, and the surface in this guide is where the app’s own drawing lands. Guide 2 covered the drawing itself.
Read it at your level
| Level | Read | You should be able to |
|---|---|---|
| Student | The basics, the window lab | Name the three players and say what each one does |
| Fresher | + The high level | Say what addView() does in order, and which part runs in the system process |
| Junior | + Step by step | Name the class that makes the window’s root view and the call that leaves your process |
| Mid | + The surface, the snippet | Say when the surface is created and why an overlay without the permission throws |
| Senior | + Edge cases, cross questions | Explain what differs between Android versions in this path, and what you would trace |
The basics
A window is a rectangle of screen that one app draws into and the system keeps track of: where it is, what is above it, who gets the touch. Every activity has one. So does anything else an app puts on screen by itself, such as a floating overlay.
Three players do the work:
- The window and its view. Your content: a
Viewhierarchy, and aWindow, which for an activity is aPhoneWindow. WindowManager, in your app. The interface your code calls:addView(),updateViewLayout(),removeView(). It runs in your process and does the app’s half of the work.WindowManagerService, in the system. It runs in the system server, a separate process, and it is the one that decides: it checks the request, keeps the list of windows and their order, opens the input channel and hands out the surface. It is why the system, and not an app, decides where each window sits relative to the others.
Your app asks and the system decides, so asking has to cross from your process into the system’s. That crossing is Binder, Android’s inter-process calls, and a window gets on screen only after two such calls. The path from addView() to the first frame is the rest of this guide.
Try it: the window lab
One addView() call, step by step. Each step is a class and method read from AOSP main, in the lane of the process it runs in. A Binder marker is where the call leaves your app and the next step runs in the system server. Pick a step to see what it does, the source it comes from and a link to the file.
Things to try. The lab starts on step 1.
- Count the steps. There are 11: seven run in your app, three in the system server, one in SurfaceFlinger.
- Find the Binder calls. There are two: step 6,
ViewRootImpl.setView(), which asks the session to add the window, and step 9, the first traversal’srelayoutWindow(), which asks for the window to be laid out and given a surface (throughrelayoutorrelayoutAsync, which the guide doesn’t distinguish). The lab marks each. - The surface comes late. Step through to 8,
WindowManagerService.addWindow(), and then 9 and 10. The window exists after step 8; its surface is made at step 10, after the app’s first traversal asked for it. - The first layout is asked for first. Step 6:
setView()callsrequestLayout()before it asks the system to add the window, and the source comment says why. By the time the system has the window, the app already has a traversal waiting. - Where the permission check is. Step 8 is where the system checks the permission for the window type. A failed check comes back to step 6 as an exception, and the Kotlin snippet below shows it.
The lab is a table with a stepper; it runs nothing, and nothing in this guide ran on a device.
The high level
| Step | What it does | Where it can go wrong |
|---|---|---|
| Make the window | Activity.attach() makes a PhoneWindow and a window manager for it |
Nothing: it is the framework’s |
| Ask | Your code calls addView() on a WindowManager |
A view added twice, or a missing permission |
| Make the root | WindowManagerGlobal makes a ViewRootImpl and records the view |
Nothing the app can do |
| Cross | ViewRootImpl.setView() calls the window session through Binder |
The call can be refused: a bad token, a missing permission |
| Decide | WindowManagerService.addWindow() checks, makes a WindowState and opens input |
The window is refused |
| Lay out | The first traversal calls relayoutWindow() through Binder |
A slow first traversal delays everything after it |
| Give a surface | The service builds the SurfaceControl and hands it back |
The app can’t draw until it has it |
| Show | The app draws, and SurfaceFlinger composes and displays | Guides 3, 8 and 11 |
Step by step
Source excerpts are from AOSP main (frameworks/base) as read on 18 November 2026, trimmed with …; lines marked [note] are the author’s. The files are linked in The map. Method names are used and line numbers are not, because they move between releases.
Steps 1 and 2: the activity makes a window
// Activity.java, in attach()
mWindow = new PhoneWindow(this, window, activityConfigCallback);
…
mWindow.setWindowManager(…);
Window is an abstract class, and PhoneWindow is the implementation an activity gets. Window.setWindowManager() keeps not the system’s window manager but a local one made from it:
// Window.java
mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);
The local manager remembers the window as its parent, and passes it on with every addView(): WindowManagerGlobal adjusts the parameters for a sub-window when it is given a parent.
Step 3: the window manager your code gets
Activity.getSystemService(WINDOW_SERVICE) returns that same window manager, mWindowManager. A Context that isn’t an activity gets one made by the registry:
// SystemServiceRegistry.java
registerService(Context.WINDOW_SERVICE, WindowManager.class,
new CachedServiceFetcher<WindowManager>() {
@Override
public WindowManager createService(ContextImpl ctx) {
return new WindowManagerImpl(ctx);
}});
Either way what you hold is a WindowManagerImpl. WindowManager is the interface, and it extends ViewManager, which is where addView() comes from.
Step 4: addView() forwards
// WindowManagerImpl.java
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyTokens(params);
mGlobal.addView(view, params, mContext.getDisplayNoVerify(), mParentWindow,
mContext.getUserId());
}
applyTokens puts the default token, if there is one and the window has no parent and no token, and the window context token into the layout parameters. Then the request goes to mGlobal, the WindowManagerGlobal that every window manager in the process shares.
Step 5: the process-wide manager makes the root
WindowManagerGlobal.addView() rejects a null view, a null display, and parameters that aren’t WindowManager.LayoutParams. A window with a parent gets its parameters adjusted for a sub-window. It then looks for the view in its list, and throws if the view is already there and not on its way out: “View … has already been added to the window manager.” Then it makes the object that connects a view to the system:
// WindowManagerGlobal.java
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
…
root.setView(view, wparams, panelParentView, userId);
The three lists are the process’s record of every window it has added. ViewRootImpl is the root of the view hierarchy for one window: it runs the traversals that measure, lay out and draw (guide 3), and it is the app’s end of the window’s conversation with the system.
Step 6: setView() leaves the process
// ViewRootImpl.java, in setView()
// Schedule the first layout -before- adding to the window manager, to make sure
// we do the relayout before receiving any other events from the system.
requestLayout();
InputChannel inputChannel = null;
if ((mWindowAttributes.inputFeatures & INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
inputChannel = new InputChannel();
}
…
res = mWindowSession.addToDisplayAsUser(mWindow, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(), userId,
mInsetsController.getRequestedVisibleTypes(), inputChannel, mTempInsets,
mTempControls, attachedFrame, compatScale);
requestLayout() doesn’t lay out then and there: it marks a layout as requested and calls scheduleTraversals() (guide 3’s Choreographer does the rest). mWindowSession is an IWindowSession, and this call is the one that runs in the system server. The input channel and the insets are out parameters, filled in on the other side, which is how the window gets the touch path of guide 4. [note] The article this guide was written beside shows a shorter signature, as it says it simplifies; this is the one in the source read.
Step 7: the system receives it
// Session.java, in the system server
public int addToDisplayAsUser(IWindow window, WindowManager.LayoutParams attrs, …) {
return mService.addWindow(this, window, attrs, viewVisibility, displayId, userId, …);
}
A Session is the system’s object for one app’s connection. It only forwards, to WindowManagerService.addWindow().
Step 8: the service decides
addWindow is long. In order, among the things it does: it asks the policy to check the permission for the window type, finds or makes the display for the window, finds or makes the window’s token, and builds the record the system keeps for it.
// WindowManagerService.java, in addWindow(), in order, trimmed
int res = mPolicy.checkAddPermission(attrs.type, isRoundedCornerOverlay, attrs.packageName, …);
if (res != ADD_OKAY) return res;
…
final DisplayContent displayContent = … getDisplayContentOrCreate(displayId, attrs.token);
…
WindowToken token = displayContent.getWindowToken(…);
…
final WindowState win = new WindowState(this, session, client, token, parentWindow, …);
…
win.openInputChannel(outInputChannel);
…
mWindowMap.put(client.asBinder(), win);
…
win.mToken.addWindow(win);
…
displayContent.getInputMonitor().updateInputWindowsLw(false /*force*/);
The permission check is in the window policy, PhoneWindowManager.checkAddPermission(). For an overlay window it goes through the SYSTEM_ALERT_WINDOW app op: when the op is allowed the window is added, when it is errored an app that targets Android 6 or later is refused with ADD_PERMISSION_DENIED, when it is merely “ignored” the call still returns ADD_OKAY (the window is added), and in the remaining case the code checks the SYSTEM_ALERT_WINDOW permission itself. Window types that aren’t overlays, such as the status bar, need INTERNAL_SYSTEM_WINDOW, a permission that ordinary apps don’t have.
A WindowState is the system’s record of one window: its parameters, its token, its frame, its surface. A WindowToken groups the windows that belong together. After this the window exists in the system’s tree, in its place in the order; it has an input channel; and the call returns a result code to setView. [note] Older descriptions of this path, including the article that this guide’s topic list was drawn from, show a win.attach() call here. I did not find one in addWindow in the source read. They are describing Android 12, and this is later.
If the permission check fails, the code returns ADD_PERMISSION_DENIED, and back in setView (step 6) the result code becomes an exception:
// ViewRootImpl.java
case WindowManagerGlobal.ADD_PERMISSION_DENIED:
throw new WindowManager.BadTokenException("Unable to add window "
+ mWindow + " -- permission denied for window type "
+ mWindowAttributes.type);
Step 9: the first traversal asks for a surface
The window is in the system’s list and has no surface. The first traversal, the one setView asked for before it added the window, calls relayoutWindow(), which calls the session again through Binder:
// ViewRootImpl.java, in performTraversals() and relayoutWindow()
relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
…
relayoutResult = mWindowSession.relayout(mWindow, params, …);
[note] The same method chooses between relayout and relayoutAsync with a flag. I did not trace which one the first relayout uses, and the guide counts both as a Binder call.
Step 10: the service builds the surface
// WindowManagerService.java, in relayoutWindow()
result = createSurfaceControl(outSurfaceControl, result, win, winAnimator);
…
// in createSurfaceControl()
surfaceControl = winAnimator.createSurfaceLocked();
…
winAnimator.getSurfaceControl(outSurfaceControl);
// WindowStateAnimator.java, in createSurfaceLocked()
int flags = SurfaceControl.HIDDEN;
…
mSurfaceControl = mWin.makeSurface()
.setParent(mWin.mSurfaceControl)
.setName(mTitle)
.setFormat(format)
.setFlags(flags)
…
.setBLASTLayer().build();
The new SurfaceControl starts hidden, is a child of the window’s own SurfaceControl, and is copied into outSurfaceControl, which is how the app receives it. The service keeps its own handle to it. SurfaceFlinger’s page in the Android documentation describes the arrangement: WindowManager asks SurfaceFlinger for a layer, which is a surface (with the buffer queue the app draws into) and a SurfaceControl (with the layer’s metadata, such as where it is shown); WindowManager sends the surface to the app and keeps the SurfaceControl “to manipulate the appearance of the app on the screen”.
Step 11: drawing, composing, showing
From here the app draws into its surface: the frames of guide 3, through the renderer of guide 2. SurfaceFlinger “accepts, composes, and sends buffers to the display”, with the Hardware Composer HAL, which the documentation says “determines the most efficient way to composite buffers with the available hardware”, for example by passing layers to the display hardware as overlay planes instead of compositing them on the GPU (see Read next). This guide stops at the surface; the rest is the graphics stack.
A window in code
The article’s example is a floating window, which is also the clearest case of a window your app adds itself. It needs the “display over other apps” permission, and without it the service refuses at step 8 and setView (step 6) throws the BadTokenException shown above:
fun addOverlay(context: Context): View? {
if (!Settings.canDrawOverlays(context)) return null // without it, addView fails: see ADD_PERMISSION_DENIED
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val params = WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT,
)
val label = TextView(context).apply {
text = "Floating label"
setBackgroundColor(Color.BLUE)
setPadding(20, 20, 20, 20)
}
windowManager.addView(label, params) // the path in the lab starts here
return label
}
fun removeOverlay(context: Context, label: View) {
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
windowManager.removeView(label)
}
The source’s own description of TYPE_APPLICATION_OVERLAY: such windows are displayed above all activity windows but below critical system windows like the status bar or the keyboard; the system may change their position, size or visibility at any time; they need SYSTEM_ALERT_WINDOW; and the system raises the importance of a process that has one, to reduce the chance of the low-memory killer taking it. Remove the view with removeView when you are done; the process keeps its record of the window until you do.
Checkpoint
You should be able to say:
- A window is a rectangle of screen that an app draws into and the system tracks, and an activity has one, a
PhoneWindow. - Your code calls
WindowManager, in your process;WindowManagerServiceis in the system server and is the one that decides. addView()goes throughWindowManagerImpltoWindowManagerGlobal, which makes aViewRootImpl;ViewRootImpl.setView()makes the first of two Binder calls.- The service checks the permission for the window type, finds the token, makes a
WindowStateand opens the input channel; a refused permission comes back to your code as aBadTokenException. - The surface is not made by
addView: the first traversal’srelayoutWindow()is the call that makes the service build theSurfaceControl. - SurfaceFlinger composes the surfaces and sends the result to the display.
Why it helps
| Symptom | What is happening | What to do |
|---|---|---|
BadTokenException … permission denied for window type |
checkAddPermission refused the window type |
Check Settings.canDrawOverlays() before an overlay, and request the permission |
View … has already been added to the window manager |
WindowManagerGlobal already has this view in its list |
Remove it first, or keep one reference and don’t add it again |
| An overlay vanishes or moves | The system may change an overlay’s position, size or visibility at any time | Treat it as a hint, not a guarantee |
| The first frame is late | The surface comes after the first traversal’s relayout | Keep the first traversal short, and trace it |
| A view you added is never released | WindowManagerGlobal keeps its view, root and parameters until removeView |
Pair every addView with a removeView |
| Key events go to the window behind an overlay | The javadoc: with FLAG_NOT_FOCUSABLE, key and button events go to whatever focusable window is behind, and the flag also enables FLAG_NOT_TOUCH_MODAL |
Leave the flag off only if the overlay needs keys, and read the rest of the flag’s documentation first |
The map
| Topic | Code | Where |
|---|---|---|
| A window per activity | Activity.attach(), Window.setWindowManager() |
Activity.java, Window.java |
| The manager your code gets | SystemServiceRegistry, WindowManagerImpl |
SystemServiceRegistry.java, WindowManagerImpl.java |
| The process-wide manager | WindowManagerGlobal.addView() |
WindowManagerGlobal.java |
| The root and the Binder calls | ViewRootImpl.setView(), relayoutWindow() |
ViewRootImpl.java |
| The system’s side of the session | Session.addToDisplayAsUser() |
Session.java |
| The permission policy | PhoneWindowManager.checkAddPermission() |
PhoneWindowManager.java |
| The decision | WindowManagerService.addWindow(), relayoutWindow() |
WindowManagerService.java |
| The surface | WindowStateAnimator.createSurfaceLocked() |
WindowStateAnimator.java |
| Window types and flags | WindowManager.LayoutParams |
WindowManager.java |
| SurfaceFlinger and WindowManager | The documentation | SurfaceFlinger and WindowManager |
Edge cases
- Version differences. The path was read from AOSP
mainon 18 November 2026.addToDisplayAsUsertakes more parameters than it did, and the Android 12 code that many descriptions use has a differentaddWindow. Method names are the stable part; check the one you target. - Sub-windows.
WindowManagerGlobal.addView()has a branch for windows whose type is between the first and last sub-window types: it looks for the window they hang from. Dialogs and popups from an activity go there. - Windows with no system window. The same method also looks in a list of “windowless” roots for a parent. This guide followed the ordinary path only.
- Relayout is not only the first one. Later changes go through
relayoutWindow()too, which can callrelayoutAsyncinstead ofrelayout. - Overlays are the system’s to move. The javadoc says so; design as if the overlay may not be where you put it.
- Contexts. An activity’s manager is its window’s own; another
Contextgets one from the registry. Which one you hold decides the parent window and tokens that go into the parameters.
Cross questions
Why does an app need WindowManagerService? Couldn't each app own its window?
Because a window is a shared thing: its place in the stack, which one gets the touch, which one is shown on which display. The system server is the one process that sees all of them, so it is the one that decides. Your process asks, and gets back the pieces it needs to draw.
What is the difference between WindowManager, WindowManagerImpl and WindowManagerGlobal?
WindowManager is the interface your code uses, WindowManagerImpl is the object you actually hold (one per window or Context), and WindowManagerGlobal is the one shared by the whole process, which keeps the lists of views, roots and parameters and makes the ViewRootImpl.
What is ViewRootImpl for?
It is the root of a window's view hierarchy in the app. It runs the traversals, talks to the window session in the system server, and holds the surface once it has one.
When is the surface created?
Not by addView. The window is added by the first Binder call, and the surface is built when the first traversal's relayoutWindow() reaches WindowStateAnimator.createSurfaceLocked() in the system server, then copied back to the app.
Why does setView call requestLayout() before it adds the window?
The source's comment says why: so the relayout is already scheduled before the app starts receiving other events from the system.
What does BadTokenException: permission denied for window type mean?
WindowManagerService.addWindow() asked the policy to check the permission for the window type, got a refusal, and returned ADD_PERMISSION_DENIED; ViewRootImpl.setView() turned that into the exception. For an overlay, it means the app doesn't have the display-over-other-apps permission.
How would I watch this happen?
The service wraps the surface creation in a trace section named createSurfaceControl, so a system trace shows it; Perfetto is a system tracing tool. I haven't traced it on a device for this guide.
Revision: key points
- A window is a rectangle of screen an app draws into and the system tracks; an activity has a
PhoneWindow. WindowManageris the app’s interface;WindowManagerServicein the system server decides.addView()goesWindowManagerImpl→WindowManagerGlobal→ViewRootImpl.setView(), which asks for the first layout and then calls the session by Binder.Session.addToDisplayAsUser()forwards toWindowManagerService.addWindow(), which checks the permission, finds or makes the token, makes aWindowStateand opens the input channel.- A refused check returns
ADD_PERMISSION_DENIED, andsetViewthrows aBadTokenException. - The surface is built by the first
relayoutWindow(), inWindowStateAnimator.createSurfaceLocked(), as a hidden childSurfaceControl, and handed back to the app. - SurfaceFlinger composes the surfaces and sends them to the display.
- Two Binder calls get a window on screen: adding it, and the first relayout.
Cheat sheet
Each concept in a few words.
| Concept | In a few words |
|---|---|
| Window | A rectangle of screen an app draws into and the system tracks. |
| PhoneWindow | The Window an activity gets. |
| WindowManager | The app-side interface to add, update and remove windows. |
| WindowManagerGlobal | The process-wide manager that keeps every window’s view and root. |
| ViewRootImpl | The root of a window’s views: traversals and the system conversation. |
| WindowManagerService | The system server’s owner of every window. |
| Session | The system’s object for one app’s window connection. |
| WindowState | The system’s record of one window. |
| WindowToken | Groups the windows that belong together. |
| SurfaceControl | The handle the system keeps to move and show a surface. |
| Binder | Android’s calls from one process to another. |
| Relayout | The call that sizes the window and gets its surface. |
Read next
- The article that started this guide: Stefano Santilli, Understanding Window Management in Android: A Deep Dive (LinkedIn, April 2025). It follows the same path with a story to carry the three players, and uses the Android 12 code; this guide checked each step against
mainand found the surface comes at the relayout - The documentation: SurfaceFlinger and WindowManager and Hardware Composer
- The API:
WindowManager,WindowManager.LayoutParams,WindowandSurfaceControl - Binder, from the app side: Android Interface Definition Language
- To watch it: Perfetto
- The series: guide 3 for the frame, guide 4 for input, guide 8 for a surface of its own
- Where real software uses this: every overlay, bubble, floating button and picture-in-picture view, and every activity; the lab is a read of the source, not a model of any one device
Search terms that find more: WindowManagerService addWindow, ViewRootImpl setView, WindowManagerGlobal addView, relayoutWindow createSurfaceControl, WindowState WindowToken, SurfaceControl BLAST layer, TYPE_APPLICATION_OVERLAY BadTokenException.
The fine print
The source was read from AOSP main (frameworks/base) on 18 November 2026: Activity, Window, WindowManagerImpl, WindowManagerGlobal, SystemServiceRegistry, ViewRootImpl, Session, WindowManagerService (addWindow, relayoutWindow, createSurfaceControl), WindowStateAnimator and PhoneWindowManager.checkAddPermission. I read the code inside addWindow and relayoutWindow that the steps name, and not the rest of those methods, and I did not read WindowState beyond looking for attach. The article credited under Read next was read in full in a browser. SurfaceFlinger and the Hardware Composer were read in the documentation pages named under Read next, and nowhere else. The Kotlin snippet compiles against Android’s SDK at minSdk 26 and lint had nothing to report on it; it was not run on a device, and nothing in this guide was. The lab is a step list with links, and its tests check that every step names a class, a file and an https source, and pin the counts above. No trace was taken. The page was checked in the built-in browser pane in dark theme; light theme, narrow widths and a phone were not checked.