Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

M4 research: the adb shell helper (org.tether.shell.Main)

Technical reference for writing the enhanced-tier helper in Kotlin (ADR-0007, roadmap “Milestone 4”). Researched 2026-11-15.

Primary reference: scrcpy v5.0.1 (commit a60891ae, 2026-10-08, Apache-2.0), server/ directory, read from a local clone, plus its release notes and issues. Secondary: AOSP android14-release, android15-release, android16-release branches (Shell manifest, IClipboard.aidl, core permission definitions), fetched from android.googlesource.com.

Conventions used below:

  • [scrcpy] = read directly in scrcpy v5.0.1 source.
  • [AOSP] = read directly in the AOSP branch named.
  • [issue] = taken from a scrcpy issue or release note (linked).
  • UNVERIFIED = from memory, inference, or a secondary source; test on the A55 before relying on it.
  • Nothing here has been run on the Galaxy A55 (Android 16 / One UI 8.5). Every “works” below means “scrcpy does this and ships it”, not “tested by us”.
  • Since minSdk = 34, all pre-Android-14 branches in scrcpy can be dropped; they are mentioned only where they explain why something exists.

Source file index (all under https://github.com/Genymobile/scrcpy/blob/v5.0.1/server/src/main/java/com/genymobile/scrcpy/):

TopicFile
Entry point, looper, exitServer.java
ActivityThread / context hacks, AudioRecord fallbackWorkarounds.java
Fake contextFakeContext.java
Restore-on-death processCleanUp.java
Main display mirrorvideo/ScreenCapture.java
New virtual displayvideo/NewDisplayCapture.java
Encoder loopvideo/SurfaceEncoder.java, video/CaptureControl.java
Packet framingdevice/Streamer.java
Display change detectiondisplay/DisplayMonitor.java, wrappers/DisplayWindowListener.java
Hidden API wrapperswrappers/ (DisplayManager, SurfaceControl, DisplayControl, InputManager, WindowManager, ActivityManager, PowerManager, ClipboardManager, ServiceManager)
Input, clipboard, app startcontrol/Controller.java, device/Device.java
Audioaudio/ (AudioDirectCapture, AudioPlaybackCapture, AudioRecordReader, AudioEncoder, AudioConfig)
Cameravideo/CameraCapture.java
Compile-time AIDL stubsserver/src/main/aidl

Licence note: scrcpy is Apache-2.0, which is one-way compatible with our GPL-3.0. Translating its logic to Kotlin is allowed; keep an attribution line in NOTICE/the file header for anything ported closely.


1. Launching with app_process

How it works

  • Classpath. app_process accepts a dex, jar or apk that contains classes.dex (scrcpy doc/develop.md). pm path org.tether.android prints package:/data/app/~~…/base.apk (one line per split); strip package: and take the base.apk line. The path changes on every app update, so resolve it at every launch. The $(…) must be expanded on the phone, so quote the whole command for the remote shell.
  • Command shape used by scrcpy (app/src/server.c, execute_server): adb -s <serial> shell CLASSPATH=<path> app_process / <MainClass> <args…>. scrcpy reads its own path back from System.getProperty("java.class.path") (first entry) so it can relaunch itself for the cleanup child.
  • Process name. app_process takes --nice-name=<name> between the directory argument and the class name (app_process / --nice-name=tether-shell org.tether.shell.Main). UNVERIFIED on the A55 (from memory of app_main.cpp); scrcpy does not use it.
  • Hidden API policy. scrcpy uses plain Class.forName / getDeclaredMethod everywhere with no exemption trick, which implies hidden-API enforcement is not applied to a shell-started app_process. No bypass library is needed. (Inference from scrcpy; UNVERIFIED by reading ART source.)
  • Startup order in Server.main / internalMain [scrcpy]:
    1. Install a default uncaught-exception handler that logs thread + throwable and then chains to the previous handler.
    2. If uid is 0 (rooted adbd), Os.setuid(2000): clipboard does not work as root (#6224).
    3. Prepare a quittable main looper: Looper.prepare() then set the private static Looper.sMainLooper to Looper.myLooper() by reflection. (Looper.prepareMainLooper() makes it non-quittable.)
    4. Parse options; apply workarounds (below); open the connection; start worker threads; Looper.loop() on the main thread.
    5. When all workers finish or one reports a fatal error, call Looper.getMainLooper().quitSafely(), stop/join workers, and finally always System.exit(status), because framework classes may have started non-daemon threads that would keep the VM alive.
  • Workarounds (Workarounds.java) [scrcpy]. A static initialiser: constructs android.app.ActivityThread through its private constructor, stores it in the static sCurrentActivityThread, and sets mSystemThread = true. Then apply() does, in this order:
    1. fillConfigurationController() (API 31+): build android.app.ConfigurationController(ActivityThreadInternal) with the activity thread and store it in mConfigurationController. Needed on Samsung, where DisplayManagerGlobal.getDisplayInfoLocked() calls ActivityThread.currentActivityThread().getConfiguration() and hits a null controller (#4467, fixed in v2.3.1). This is the “configuration controller” item in our roadmap. It must run before the first getSystemContext() call.
    2. fillAppInfo(): create ActivityThread$AppBindData, set its appInfo to an ApplicationInfo whose packageName is com.android.shell, and store it in mBoundApplication. (Skipped on ONYX devices, irrelevant to us.)
    3. fillAppContext(): Instrumentation.newApplication(Application.class, FakeContext) and store the result in mInitialApplication, so ActivityThread.currentApplication() is non-null. All three are wrapped in try/catch and failure is only logged.
  • FakeContext (FakeContext.java) [scrcpy]: a ContextWrapper around ActivityThread.getSystemContext() (reflection) that overrides:
    • getPackageName() and getOpPackageName() → "com.android.shell".
    • getAttributionSource() → AttributionSource.Builder(Process.SHELL_UID).setPackageName("com.android.shell").build().
    • getDeviceId() → 0 (Android 14 API; default device).
    • getApplicationContext() → itself; createPackageContext(...) → itself.
    • getContentResolver() → an anonymous ContentResolver subclass whose hidden acquireProvider(Context, String) goes through IActivityManager.getContentProviderExternal(name, userId 0, token, tag) (the mechanism settings/content shell commands use) and returns the provider field of the returned holder. The other four hidden abstract methods are stubbed. This needs a compile-time stub of android.content.IContentProvider.
    • getSystemService(name): for clipboard, the Samsung-internal semclipboard, and activity, overwrite the returned manager’s private mContext field with the fake context so later binder calls carry package com.android.shell instead of android. The reason for all of this: the system context’s package is android, and system_server rejects android for uid 2000 (“package android does not belong to uid 2000” / “does not match caller’s uid 2000”: #4639, #6224, #6523).
  • Binder services without a manager: android.os.ServiceManager.getService(name) then <Interface>$Stub.asInterface(binder), both by reflection (wrappers/ServiceManager.java). Used for window, power, and the activity manager (via ActivityManagerNative.getDefault()).
  • Exit when adb dies. scrcpy has no explicit watchdog: each socket read or write fails when the tunnel closes, the worker reports termination, and the main looper quits. adbd also kills the shell subprocess when the transport drops. Because that kill can arrive before any restore code runs, scrcpy forks a second app_process (CleanUp.main) at start, which calls Os.setsid() to leave the server’s session, then blocks reading its stdin pipe from the parent. EOF means the parent died; it then restores settings and display power and exits. The parent can update “restore display power” by writing one byte to that pipe.
  • Samsung restore bug: settings were not restored on some Samsung devices (#6405, #6540, fixed in v3.3.4). The setsid() comment in CleanUp.main (“avoid being terminated along with the server process on some devices”) is very likely that fix; UNVERIFIED that it is the same commit.

Per version / Samsung

  • 14 / 15 / 16: same launch path; no version-specific branch in Server.java.
  • Samsung: fillConfigurationController is mandatory (Android 14+ One UI).
  • Samsung Android 11 only: the encoder crashes when /proc/self/cmdline exceeds about 256 bytes (#7169, open). Not our target version, but a reason to keep argv short.

What to do

  • Launch as adb shell 'CLASSPATH=$(pm path org.tether.android | sed -n "s/^package://;/base\.apk$/p") exec app_process / org.tether.shell.Main' and add --nice-name only after confirming it on the A55.
  • Do not pass the one-time token on argv (ADR-0007 currently shows --token): argv is visible to any other adb shell via ps, and long command lines are a known Samsung hazard. Write it to the helper’s stdin as the first line instead.
  • Port Workarounds + FakeContext almost one to one; keep the same call order; keep every step individually try/caught and report which ones failed in ShellHello as diagnostics.
  • Release builds use R8 (isMinifyEnabled = true): add keep rules for org.tether.shell.** entry points and anything reached only by reflection or by app_process.
  • Put framework stubs (android.content.IContentProvider, android.view.IDisplayWindowListener, android.content.IOnPrimaryClipChangedListener) in a compileOnly module so they are not packaged; the boot classpath provides the real classes at runtime. (scrcpy compiles them into its jar and relies on parent-first class loading; either works, compileOnly is cleaner inside an app APK. UNVERIFIED that AIDL generation works from a compileOnly module in our Gradle setup; fallback is to ship them.)
  • The helper has no Application, no resources from our APK, no AndroidX initialisers and no native libraries. Keep org.tether.shell free of R.*, Compose, Hilt and JNI. Kotlin stdlib and coroutines are fine (Dispatchers.Main works only after the main looper is prepared).
  • Exit rules: socket EOF or stdin EOF → orderly stop → exitProcess. Port the cleanup child with setsid() for anything that must be undone (display power, show_touches, screen_off_timeout, IME policy).

2. Screen capture of the main display

How it works

  • Which API. ScreenCapture.start() [scrcpy] first calls the hidden static android.hardware.display.DisplayManager.createVirtualDisplay(String name, int width, int height, int displayIdToMirror, Surface surface) by reflection; this returns a VirtualDisplay that mirrors an existing display at the requested size. Only if that throws does it fall back to SurfaceControl.createDisplay(name, secure) + a transaction (setDisplaySurface, setDisplayProjection(token, 0, deviceRect, targetRect), setDisplayLayerStack(token, layerStack)).

  • Why DisplayManager on 14+. The SurfaceControl display-token methods were moved out of android.view.SurfaceControl in Android 14 (into com.android.server.display.DisplayControl, see section 5), so the old path does not exist there. That it is the removal that forced the switch is UNVERIFIED (consistent with scrcpy’s Android 14 fixes and the comment in Device.setDisplayPower). The fallback is effectively dead code for us.

  • Permissions [AOSP Shell manifest, 14/15/16]: shell holds CAPTURE_VIDEO_OUTPUT, READ_FRAME_BUFFER, ACCESS_SURFACE_FLINGER. Android 16 adds a new ADD_MIRROR_DISPLAY permission and shell holds it.

  • Secure content. Shell cannot create a secure display since Android 12 (comment in ScreenCapture.createDisplay); shell does not hold CAPTURE_SECURE_VIDEO_OUTPUT on 14/15/16 [AOSP]. FLAG_SECURE windows (banking apps, some password fields, DRM video) are black in the stream. There is no non-root workaround (#3049). scrcpy also warns when the display lacks FLAG_SUPPORTS_PROTECTED_BUFFERS. Whether Android 15’s “sensitive content protection” (OTP notifications hidden during screen share) applies to a shell mirror display is UNVERIFIED.

  • Display size / rotation. DisplayManagerGlobal.getInstance().getDisplayInfo(displayId) returns a hidden DisplayInfo; read fields logicalWidth, logicalHeight (already rotated), rotation, layerStack, flags, logicalDensityDpi, and uniqueId (may be missing on some ROMs, #6461). If the call returns null, scrcpy parses dumpsys display with a regex on the mOverrideDisplayInfo line.

  • Change detection (DisplayMonitor) [scrcpy]: on Android 14+ scrcpy does not use DisplayManager.DisplayListener; it registers an IDisplayWindowListener with IWindowManager.registerDisplayWindowListener and reacts to onDisplayConfigurationChanged(displayId, Configuration). Reason: DisplayListener never fired on some Android 14 builds and broke again in an Android 15 update (#5908, fixed v3.2). On each event it re-reads DisplayInfo, compares (size, rotation) with the last known value, and only then triggers a reset.

  • Android 16 listener pitfall. Android 16 added methods to IDisplayWindowListener (e.g. onDisplayAddSystemDecorations). A subclass compiled against the old three-method interface throws AbstractMethodError on a binder thread and kills the process (#6331, #6362, fixed v3.3.2 / v3.3.3). scrcpy’s fix is to override onTransact, catch AbstractMethodError, call reply.writeNoException() and return true.

  • Rotation / resize / fold handling (SurfaceEncoder.streamCapture, CaptureControl) [scrcpy]: a reset calls signalEndOfInputStream() on the running codec; the drain loop sees EOS, then the outer loop stops and reset()s the codec, recomputes the size, reconfigures, creates a new input surface, releases and recreates the mirror display, and restarts. A fold or unfold is just another size change on display 0 (UNVERIFIED on a foldable).

  • Sizing. Scale the logical size to fit max_size, then align to the encoder’s VideoCapabilities.getWidthAlignment()/getHeightAlignment() (v4.0+). Encoder capability limits are applied only after the first failure (v4.1), then scrcpy steps down through 2560, 1920, 1600, 1280, 1024, 800. After a first frame was sent, it retries up to 3 times with a 50 ms sleep.

  • Encoder settings (SurfaceEncoder.createFormat) [scrcpy]:

    KeyValue
    KEY_MIMEvideo/avc (default), video/hevc, video/av01, VP8/VP9 since v4.1
    KEY_BIT_RATE8 000 000 default
    KEY_FRAME_RATE60 (required by configure; real rate is variable)
    KEY_COLOR_FORMATCOLOR_FormatSurface
    KEY_COLOR_RANGECOLOR_RANGE_LIMITED
    KEY_I_FRAME_INTERVAL10 (seconds)
    KEY_REPEAT_PREVIOUS_FRAME_AFTER100 000 µs (emits a frame for static content, and makes the first frame appear)
    KEY_PRIORITY0 (real time)
    KEY_LATENCY1 (added in v4.0, #6670)
    "max-fps-to-encoder" (float)only when an fps cap is requested

    scrcpy sets no profile, level or bitrate mode; the encoder default applies. Extra keys can be injected per device via --video-codec-options.

  • Encoder thread must call Looper.prepare() (some OEM codecs deadlock otherwise, #4143). Output is drained synchronously with dequeueOutputBuffer(info, -1).

  • Framing (Streamer.java) [scrcpy]: stream starts with a 4-byte codec id; each encode session starts with a 12-byte session packet (top bit set, low bit = “client-initiated resize”, then width, height); each buffer is a 12-byte header (u64 big-endian = PTS in µs, with bit 62 = config packet and bit 61 = key frame; u32 length) followed by the payload. The config buffer (BUFFER_FLAG_CODEC_CONFIG: SPS/PPS, Annex B) is sent as its own packet with no PTS; the client prepends it to the next frame. PTS is BufferInfo.presentationTimeUs unchanged.

Per version / Samsung

  • 14: DisplayListener unreliable → window listener path.
  • 15: same; a QPR broke DisplayListener again (#5908).
  • 16: IDisplayWindowListener grew methods (guard onTransact); ADD_MIRROR_DISPLAY exists and is held by shell.
  • Samsung: needs the configuration-controller workaround for getDisplayInfo. Exynos encoder behaviour on the A55 (alignment, KEY_LATENCY support) is UNVERIFIED; scrcpy’s downsize-on-error loop exists for exactly this.

What to do

  • Use only the DisplayManager.createVirtualDisplay(name, w, h, displayIdToMirror, surface) path. Treat failure as “capability absent”, do not port the SurfaceControl fallback.
  • Ask the mirror display for the final video size directly (no GL stage); keep input coordinates in device space (section 4).
  • Port DisplayMonitor’s window-listener path including the onTransact guard. This is the single most likely thing to crash on One UI 8.5.
  • Copy scrcpy’s MediaFormat as the default and expose codec options through the protocol so the daemon can push per-device overrides without an app release. Our own additions, all UNVERIFIED: request an on-demand key frame with MediaCodec.setParameters(PARAMETER_KEY_REQUEST_SYNC_FRAME) when a viewer (re)attaches instead of a 10 s wait; change bitrate live with PARAMETER_KEY_VIDEO_BITRATE.
  • Map framing onto our protocol: StreamOpen carries codec + width/height (scrcpy’s session packet) and is re-sent on every reset; config buffers are a flagged frame; access units carry PTS and a key-frame flag. The desktop h264parse needs the config before the first key frame after every reset.

3. New virtual display for per-app streaming

How it works

  • API (wrappers/DisplayManager.createNewVirtualDisplay) [scrcpy]: instantiate android.hardware.display.DisplayManager through its hidden (Context) constructor with the fake context, then call the public createVirtualDisplay(name, width, height, dpi, surface, flags).

  • Flags (NewDisplayCapture.startNew) [scrcpy]:

    FlagValueWhen
    PUBLIC1 << 0always
    PRESENTATION1 << 1always (v3.3.3, #6344)
    OWN_CONTENT_ONLY1 << 3always
    SUPPORTS_TOUCH1 << 6always
    ROTATES_WITH_CONTENT1 << 7always
    DESTROY_CONTENT_ON_REMOVAL1 << 8default on; off with --no-vd-destroy-content
    SHOULD_SHOW_SYSTEM_DECORATIONS1 << 9default on; off with --no-vd-system-decorations
    TRUSTED1 << 10Android 13+
    OWN_DISPLAY_GROUP1 << 11Android 13+
    ALWAYS_UNLOCKED1 << 12Android 13+
    TOUCH_FEEDBACK_DISABLED1 << 13Android 13+
    OWN_FOCUS1 << 14Android 14+
    DEVICE_DISPLAY_GROUP1 << 15Android 14+
  • Permissions [AOSP Shell manifest 14/15/16]: ADD_TRUSTED_DISPLAY, ADD_ALWAYS_UNLOCKED_DISPLAY, CAPTURE_VIDEO_OUTPUT, INTERNAL_SYSTEM_WINDOW are all held by shell.

  • Minimum version. scrcpy refuses --new-display below Android 10 and injects input on secondary displays from Android 10. The trusted / own-focus flag set that makes a display behave like an independent screen needs 13 and 14. With minSdk 34 we always get the full set.

  • Default size/dpi. Without an explicit size scrcpy uses the main display’s natural size and scales dpi by the ratio of the longer sides; flex mode defaults to 1280x960 at 160 dpi.

  • Starting an app (Device.startApp, wrappers/ActivityManager) [scrcpy]: get the launch intent from FakeContext.getPackageManager().getLaunchIntentForPackage(pkg) (leanback intent as fallback), add FLAG_ACTIVITY_NEW_TASK, build ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle(), and call IActivityManager.startActivityAsUser(caller=null, callingPackage="com.android.shell", intent, resolvedType=null, resultTo=null, resultWho=null, requestCode=0, startFlags=0, profilerInfo=null, options, userId=-2) by reflection (11 parameters). A + prefix makes scrcpy call forceStopPackage(pkg, -2) first. The CLI equivalent is am start --display <id> -n <component>.

  • Already-running app. What happens when the app already has a task on the phone’s own display (moved, or a second task) is UNVERIFIED; scrcpy’s force-stop option exists because of this.

  • Resize (flex display, v4.0) [scrcpy]: VirtualDisplay.resize(w, h, dpi) after a debounce; the resulting configuration event resets the encoder and the existing display is re-pointed with VirtualDisplay.setSurface(newSurface) (the display is not recreated, so apps stay). A small tracker remembers recently requested sizes (3 s) to tell client-initiated resizes from device-initiated ones.

  • Rotation. The display rotates with content, but the produced frames stay in the display’s physical orientation; scrcpy rotates them in an OpenGL stage (OpenGLRunner + AffineOpenGLFilter) and keeps a separate transform for input coordinates.

  • Destroying the display. With DESTROY_CONTENT_ON_REMOVAL the tasks on it are removed; without it they move to the main display (scrcpy doc/virtual-display.md, #5615).

  • System decorations. With the flag, some devices show a launcher and navigation bar on the new display. Without it the display is empty until an app starts, and no frame is produced until something renders.

  • IME. IWindowManager.setDisplayImePolicy(displayId, policy): 0 local, 1 fallback display (default: keyboard appears on the phone’s own screen), 2 hide. scrcpy restores a changed policy in the cleanup process.

  • Keeping it awake. IPowerManager.userActivity(displayId, uptimeMillis, 0, 0) every 4 s (--keep-active, v4.0); IPowerManager.isDisplayInteractive(displayId) on 14+ tells whether a given display is on.

Per version / Samsung

  • 14: full flag set available.
  • 15: UHID devices can be bound to a virtual display by unique id (section 4).
  • 16: virtual displays crashed scrcpy on Pixel after the September 2025 security update when desktop-experience features were enabled (#6234, fixed v3.3.2 by the listener guard). One UI 8.5 is a later base, so assume the same applies.
  • Samsung, all from open scrcpy issues (not reproduced by us):
    • With system decorations, One UI shows a DeX-like desktop on the new display, with a duplicated navigation bar (#6591, S23 Ultra, Android 16) and a new “My Files” icon each run (#6270, S24 Ultra, Android 15). It is not flagged as DeX mode by the phone (#6433, One UI 7), and several displays at once work there.
    • setDisplayImePolicy(local) throws on a Galaxy S10+ / Android 12 (#5997). Status on One UI 8.5 UNVERIFIED.
    • Typing into apps on a new display intermittently does nothing on a Fold with Android 16 / One UI 8.5, including with UHID (#6909, open, no diagnosis). Same OS as our test phone.
    • Z Fold 4 / Android 16: new display reported as not usable (#6855, open, unconfirmed).
    • Press reports say One UI 8 can run real DeX on such a display with scrcpy 4.1+ (PhoneArena); details UNVERIFIED.

What to do

  • One VirtualDisplay per streamed app. Flags: scrcpy’s full Android 14 set minus SHOULD_SHOW_SYSTEM_DECORATIONS, so no launcher, no DeX-like shell and none of the Samsung decoration bugs. Consequence: the desktop window must supply Back (and optionally Home → close window), and the stream must tolerate “no frame yet” until the app draws.
  • Default to DESTROY_CONTENT_ON_REMOVAL. Moving a task to the main display when a desktop window closes would wake an app on a phone that may be locked or screen-off. Offer “keep on phone” later.
  • Start apps through IActivityManager.startActivityAsUser with setLaunchDisplayId; keep am start --display as a fallback path behind the same protocol message. Test the already-running case on the A55 first and decide whether force-stop is needed.
  • Window resize: debounce on the desktop too, call VirtualDisplay.resize, reuse the encoder-reset path from section 2.
  • Rotation: instead of porting the GL pipeline, send the display rotation in StreamOpen and rotate on the desktop (GStreamer videoflip). Our own simplification, UNVERIFIED.
  • IME: try setDisplayImePolicy(id, LOCAL), catch failure, report it in the mirror’s capabilities. With a PC keyboard the soft keyboard is not needed, so HIDE is a reasonable second choice.
  • Run a userActivity ticker per live virtual display.
  • Budget time for #6909-style typing failures on One UI 8.5; have clipboard paste and UHID as alternative text paths (section 4).

4. Input injection

How it works

  • Injection call (wrappers/InputManager) [scrcpy]: get the real android.hardware.input.InputManager from FakeContext.getSystemService("input") and invoke the hidden injectInputEvent(InputEvent, int mode). Modes: 0 async, 1 wait for result, 2 wait for finish. scrcpy uses async for everything except the synthetic COPY/CUT key before a clipboard read (wait for finish). Shell holds INJECT_EVENTS on 14/15/16 [AOSP].
  • Target display: hidden InputEvent.setDisplayId(int), called only when the id is not 0.
  • Which display id and which coordinates [scrcpy, #5370, #5614]:
    • Mirroring the main display: inject to display 0 with coordinates scaled to the device size. Injecting into the mirror display made some UI elements unclickable (fixed v3.1).
    • Mirroring another existing display: positional events go to the mirror display id with coordinates in the mirror’s size; key events go to the source display id.
    • New virtual display: everything goes to the virtual display id.
    • Events whose “screen size” field does not match the current video size are dropped (they were generated against a stale frame).
  • Touch (Controller.injectTouch, PointersState) [scrcpy]: keep up to 10 pointers, each mapped from the client’s pointer id to a small local id, with reusable PointerProperties (toolType = TOOL_TYPE_FINGER) and PointerCoords (x, y, pressure; size and orientation 0). Build with MotionEvent.obtain(downTime, eventTime, action, pointerCount, props, coords, metaState=0, buttonState, xPrecision=1f, yPrecision=1f, deviceId=0, edgeFlags=0, source, flags=0). downTime is the time of the first pointer’s ACTION_DOWN. With more than one pointer, down/up become ACTION_POINTER_DOWN/UP | (index << ACTION_POINTER_INDEX_SHIFT). Source is SOURCE_TOUCHSCREEN and buttonState must be 0 for fingers.
  • Mouse. When the pointer is the mouse and the event is a hover or has a non-primary button: TOOL_TYPE_MOUSE, SOURCE_MOUSE. Button sequence required by apps such as Chrome (#3635): first button down → ACTION_DOWN then ACTION_BUTTON_PRESS; other buttons → ACTION_BUTTON_PRESS only; release → ACTION_BUTTON_RELEASE, and ACTION_UP after the last one. The action button is set with the hidden MotionEvent.setActionButton(int). Hover is ACTION_HOVER_MOVE.
  • Scroll: one pointer, ACTION_SCROLL, SOURCE_MOUSE, with AXIS_HSCROLL / AXIS_VSCROLL set on the coords.
  • Keys (Device.injectKeyEvent): KeyEvent(downTime=now, eventTime=now, action, keyCode, repeat, metaState, deviceId=KeyCharacterMap.VIRTUAL_KEYBOARD, scancode=0, flags=0, source=SOURCE_KEYBOARD). The client sends the Android meta state (shift/ctrl/alt/meta bits) with each key. Back, Home and Recents are KEYCODE_BACK, KEYCODE_HOME, KEYCODE_APP_SWITCH. scrcpy’s right-click is “back, or POWER if the screen is off”, decided with isDisplayInteractive(displayId) on 14+.
  • Text (Controller.injectText) [scrcpy]: per char, KeyCharacterMap.load(VIRTUAL_KEYBOARD).getEvents(chars); accented letters are first decomposed into dead-key + letter (KeyComposition). Returns null for anything the virtual key map lacks (most non-Latin text, emoji), and the char is skipped. The alternative is clipboard paste: set the device clipboard, then inject KEYCODE_PASTE (scrcpy doc/control.md). That overwrites the phone clipboard, and a few apps ignore programmatic paste (scrcpy’s --legacy-paste).
  • UHID (control/UhidManager) [scrcpy]: shell can open /dev/uhid and create a HID keyboard/mouse (UHID_CREATE2, UHID_INPUT2), which Android treats as a physical device (hardware keyboard layout, IME hidden, real mouse pointer). On Android 15+ the device can be tied to a virtual display with InputManager.addUniqueIdAssociationByPort(inputPort, displayUniqueId) using DisplayInfo.uniqueId (v3.3). Below 15 a UHID mouse only works on the main display.
  • Permission error. Some OEMs gate INJECT_EVENTS behind an extra developer toggle (“USB debugging (Security settings)”, Xiaomi family); scrcpy detects the SecurityException text and prints guidance (#6080). Not known to affect Samsung.

Per version / Samsung

  • 14: OWN_FOCUS gives each virtual display its own focus, so keys aimed at it do not disturb the phone’s foreground app.
  • 15: UHID-to-display association available.
  • 16: no injection API change found in scrcpy’s history.
  • Samsung: see #6909 in section 3 (typing sometimes ignored on One UI 8.5).

What to do

  • Port Device.injectEvent, PointersState and the mouse button sequence as they are. Use async mode by default.
  • InputEvent{... display_id} in our protocol should carry the mirror id; the helper resolves it to (target display id, coordinate transform) with the rules above, and drops positional events for a stale stream size.
  • Text: try KeyCharacterMap first; on a null result fall back to clipboard + KEYCODE_PASTE for the whole string, and restore the previous clip afterwards (our addition, UNVERIFIED that restore is race-free). Suppress our own clipboard-changed echo while doing so (section 6).
  • Treat UHID keyboard as a later option for the “types nothing” failure mode and for non-US layouts.
  • Report SecurityException on first injection as a capability failure in ShellHello instead of failing silently.

5. Screen off while mirroring

How it works

  • Call (Device.setDisplayPower) [scrcpy]: for every physical display, SurfaceControl.setDisplayPowerMode(IBinder token, int mode) with mode 0 (off) or 2 (normal), by reflection on android.view.SurfaceControl.
  • Tokens on Android 14+ (wrappers/DisplayControl) [scrcpy]: getPhysicalDisplayIds() and getPhysicalDisplayToken(long) are no longer on SurfaceControl; they live in com.android.server.display.DisplayControl, which is in the system-server jars, not the boot classpath. The trick:
    1. com.android.internal.os.ClassLoaderFactory.createClassLoader(String dexPath, String librarySearchPath, String libraryPermittedPath, ClassLoader parent, int targetSdkVersion, boolean isNamespaceShared, String classLoaderName) with dexPath = Os.getenv("SYSTEMSERVERCLASSPATH"), nulls, the system class loader as parent, 0, true, null.
    2. loadClass("com.android.server.display.DisplayControl").
    3. Invoke the private Runtime.loadLibrary0(Class, String) with that class and "android_servers" so its native methods bind.
    4. Call the static getPhysicalDisplayIds(): long[] and getPhysicalDisplayToken(long): IBinder. scrcpy picks this path when SDK ≥ 34 and SurfaceControl has no getPhysicalDisplayIds (some OEM builds kept it).
  • Android 15 alternative. DisplayManagerGlobal.requestDisplayPower(int displayId, boolean on) exists and scrcpy 3.0 used it, but it made the device stop accepting input on some phones, so it was rolled back to the old method (#5530, v3.0.1); it is behind a constant set to false. The shell command cmd display power-off 0 / power-on 0 is the same mechanism (Android 15+, scrcpy doc/device.md).
  • It is not sleep. The panel is off but the device stays interactive. Any wake (POWER key, physical or injected) turns the panel back on, so scrcpy re-applies “off” 200 ms after it injects KEYCODE_POWER / KEYCODE_WAKEUP key-up. The physical power button still turns it on.
  • Timeout and lock. The normal screen timeout still runs; when it fires the device really sleeps and locks, and the mirror shows the lock screen after a wake. scrcpy pairs screen-off with --stay-awake (settings put global stay_on_while_plugged_in 7, effective only while charging), --screen-off-timeout (settings put system screen_off_timeout), or the userActivity ticker.
  • Restore. The cleanup child (section 1) turns power back to normal if the helper dies while the display is forced off, but only if the display is still “on” according to isDisplayInteractive. For a new-virtual-display session the power call targets display 0 (#5522).
  • OEM notes [scrcpy]: Honor on 14 needs the single built-in token path (#4823); “turn screen off on some devices” was fixed in v3.1 (#4544, #5274).

Per version / Samsung

  • 14, 15, 16: DisplayControl class-loader path. 15+ also has requestDisplayPower / cmd display power-off as a second option.
  • Whether rotation, a fold, or Always On Display re-lights the panel on One UI is UNVERIFIED. No Samsung-specific breakage found in scrcpy’s tracker for 14+.

What to do

  • Implement the DisplayControl path first; keep cmd display power-off <id> (exec) as the fallback on 15+ and probe which one works at ShellHello.
  • Always run the cleanup child when screen_off is requested; never rely on in-process finally blocks.
  • Wireless adb means “not plugged in” is common, so stay_on_while_plugged_in is not enough: use the userActivity ticker (display 0) while a mirror is open, and tell the user that the lock timeout is being held off.
  • After any injected POWER/WAKEUP, re-apply off after ~200 ms.

6. Clipboard as shell

How it works

  • Current scrcpy (v5.0.1) no longer reflects on IClipboard. It takes the real android.content.ClipboardManager from FakeContext.getSystemService("clipboard") (whose mContext has been replaced by the fake context) and uses the public getPrimaryClip(), setPrimaryClip(ClipData.newPlainText(null, text)) and addPrimaryClipChangedListener(...). The manager fills in package com.android.shell, attribution tag, user id and device id itself.
  • Create it on the main (looper) thread, even if unused at first (comment in Controller’s constructor); listener callbacks are delivered through that looper.
  • Why shell may read in the background [AOSP Shell manifest 14/15/16]: shell holds READ_CLIPBOARD_IN_BACKGROUND. Whether the “pasted from clipboard” toast appears for shell reads is UNVERIFIED.
  • Binder signatures, if we ever need the raw interface. Identical on Android 14, 15 and 16 [AOSP core/java/android/content/IClipboard.aidl]:
    • getPrimaryClip(String pkg, String attributionTag, int userId, int deviceId): ClipData
    • setPrimaryClip(ClipData clip, String callingPackage, String attributionTag, int userId, int deviceId)
    • addPrimaryClipChangedListener(IOnPrimaryClipChangedListener listener, String callingPackage, String attributionTag, int userId, int deviceId) (and the matching remove…), listener is a oneway interface with one method dispatchPrimaryClipChanged().
    • Also hasPrimaryClip, getPrimaryClipDescription, clearPrimaryClip, getPrimaryClipSource with the same four trailing parameters.
    • Values scrcpy used: package com.android.shell, tag null, user 0, device id 0 (default device). deviceId is the Android 14 addition.
  • OEM signature drift (scrcpy v3.2 wrappers/ClipboardManager.java): seven getPrimaryClip variants were probed in order, including OEM ones with an extra trailing boolean userOperate (Honor, #4822), a seven-argument form, and a trailing String. This probing is exactly what the switch to the real manager removed.
  • Samsung. One UI’s ClipboardManager delegates to SemClipboardManager, which reads Settings.System through the context’s content resolver; with the plain system context that fails with “calling package android does not match caller’s uid 2000” (#6224, v3.3.2). After a later update a similar denial required patching the semclipboard service’s context as well (#6523, v3.3.4). Both are covered by FakeContext as described in section 1.
  • Echo suppression [scrcpy]: an atomic “setting clipboard” flag is raised around setPrimaryClip so the listener ignores our own write; and the set is skipped when the clipboard already holds the same text (otherwise keyboard clipboard histories get flooded).
  • Text only. scrcpy never transfers images or URIs.

Per version / Samsung

  • 14 / 15 / 16: no signature difference in AOSP.
  • Samsung: depends on the fake content resolver and the semclipboard patch. UNVERIFIED on One UI 8.5.

What to do

  • Use the real ClipboardManager through FakeContext, created on the main looper thread; register the listener there; push Clipboard messages on change and answer ClipboardRead on demand.
  • Keep a raw IClipboard path (AOSP four-trailing-parameter signature only) as a diagnostic fallback, not as the main path.
  • Port both echo-suppression measures.
  • First test on the A55: read, write, listener, with the phone locked and unlocked.

7. Audio capture of device playback

How it works

  • Sources (audio/AudioSource.java) [scrcpy]:
    • output = MediaRecorder.AudioSource.REMOTE_SUBMIX: the whole mix, and playback on the phone is silenced while capturing (scrcpy doc/audio.md).
    • playback: an AudioPolicy loopback mix (below), Android 13+.
    • mic and other microphone presets; since v3.2 also VOICE_CALL, VOICE_UPLINK, VOICE_DOWNLINK, VOICE_PERFORMANCE.
  • Permissions [AOSP Shell manifest 14/15/16]: RECORD_AUDIO, CAPTURE_AUDIO_OUTPUT, MODIFY_AUDIO_ROUTING all held by shell.
  • Format (AudioConfig): 48 000 Hz, stereo, PCM 16-bit.
  • Direct capture (AudioDirectCapture) [scrcpy]: AudioRecord.Builder().setContext(FakeContext) (API 31+), .setAudioSource(source), .setAudioFormat(...), .setBufferSizeInBytes(8 * minBufferSize), .build(), startRecording(). setContext is what makes the attribution (uid 2000, com.android.shell) correct.
  • Fallback constructor (Workarounds.createAudioRecord) [scrcpy], used only when the builder throws NullPointerException (Vivo): create an empty AudioRecord through the hidden (long) constructor, set private fields (mRecordingState, mInitializationLooper, mAudioAttributes built with the hidden AudioAttributes.Builder.setInternalCapturePreset(int), mChannelCount, mChannelMask), call the private audioParamCheck and audioBuffSizeCheck, then the private native_setup. On Android 14+ that native method has 12 parameters: (Object weakThis, Object attributes, int[] sampleRate, int channelMask, int channelIndexMask, int audioFormat, int buffSizeInBytes, int[] sessionId, Parcel attributionSource, long nativeRecordInJavaObj, int maxSharedAudioHistoryMs, int halInputFlags). The attribution parcel comes from the hidden AttributionSource.asScopedParcelState() → getParcel(). Then set mSampleRate, mSessionId, mState = STATE_INITIALIZED.
  • Android 11 foreground hack: start com.android.shell/.HeapDumpActivity so uid 2000 counts as foreground, retry, then force-stop the shell package. Android 11 only; irrelevant with minSdk 34.
  • Android 16: AudioRecord.Builder.build() threw UnsupportedOperationException: Cannot create AudioRecord on Android 16 previews and again on Beta 4 (#5698 fixed v3.2, #6021 fixed v3.3). The root cause and the exact fix were not read; the v5.0.1 shape of FakeContext (attribution source, getDeviceId, setContext) is the result. UNVERIFIED beyond that.
  • Playback capture (AudioPlaybackCapture) [scrcpy, #4380], all hidden classes in android.media.audiopolicy:
    1. AudioMixingRule.Builder(); setTargetMixRole(MIX_ROLE_PLAYERS); addMixRule(RULE_MATCH_ATTRIBUTE_USAGE, AudioAttributes) once per usage (media, game, alarm, notification, ringtone, assistant, accessibility, navigation, sonification, voice communication and signalling, unknown; the full list is new in v5.0, #6975); voiceCommunicationCaptureAllowed(true); build().
    2. AudioMix.Builder(rule).setFormat(format).setRouteFlags(flag).build() with ROUTE_FLAG_LOOP_BACK (captured audio is removed from the phone’s speaker) or ROUTE_FLAG_LOOP_BACK_RENDER (duplication: still plays on the phone; scrcpy --audio-dup).
    3. AudioPolicy.Builder(FakeContext).addMix(mix).build().
    4. Hidden static AudioManager.registerAudioPolicyStatic(policy), must return 0.
    5. policy.createAudioRecordSink(mix) returns the AudioRecord. Needs Android 13 (when shell gained MODIFY_AUDIO_ROUTING). Not affected by phone volume or connected headsets. Apps that opt out of playback capture are not captured.
  • Reading (AudioRecordReader): read at most 1024 frames per call into a direct buffer; PTS from AudioRecord.getTimestamp(ts, TIMEBASE_MONOTONIC), falling back to previous PTS + duration, forced strictly increasing.
  • Encoding (AudioEncoder): MediaCodec for audio/opus, KEY_BIT_RATE = 128000, KEY_CHANNEL_COUNT = 2, KEY_SAMPLE_RATE = 48000; asynchronous callback on a HandlerThread, separate input and output threads. If the device has no Opus encoder, configure fails with 0xfffffffe and scrcpy suggests AAC.
  • Framing: same 12-byte header as video. Android’s Opus codec-config buffer is not a bare OpusHead: it is "AOPUSHDR", a native-endian 64-bit length, the OpusHead bytes, then AOPUSDLY / AOPUSPRL blocks. Streamer.fixOpusConfigPacket trims it to just OpusHead. Frames after that are plain Opus packets.
  • Audio failure is non-fatal in scrcpy: it sends a “stream disabled” code and continues with video.

Per version / Samsung

  • 14: both sources available; native_setup has the extra halInputFlags.
  • 15: no change found.
  • 16: builder regression twice during previews, fixed upstream (see above).
  • Samsung: no Samsung-specific audio issue found in scrcpy’s tracker. Presence of c2.android.opus.encoder on the A55 is expected but UNVERIFIED.

What to do

  • Map protocol AudioStart.source: OUTPUT → REMOTE_SUBMIX (phone goes silent, captures everything); PLAYBACK_DUP → AudioPolicy with ROUTE_FLAG_LOOP_BACK_RENDER. Consider a third value for ROUTE_FLAG_LOOP_BACK (silent phone, per-usage capture, ignores volume).
  • Default the “Phone audio” toggle to the playback/policy path with a UI note that some apps opt out; offer OUTPUT as “capture everything (mutes phone)”.
  • Use the builder with setContext(FakeContext) only. Port the reflective native_setup fallback only if the A55 actually needs it.
  • Strip the Opus config to OpusHead and put it in StreamOpen; the desktop can feed it to opusdec as stream header.
  • Make audio failure a GrantResult-style soft error, never fatal to the mirror.
  • Worth a separate spike for M3’s call audio: scrcpy lists VOICE_CALL / uplink / downlink sources for shell. Whether Samsung’s audio HAL honours them is UNVERIFIED.

8. Camera capture from shell

How it works

  • Access (wrappers/ServiceManager.getCameraManager, CameraCapture) [scrcpy]: construct android.hardware.camera2.CameraManager through its hidden (Context) constructor with the fake context. Shell holds android.permission.CAMERA on 14/15/16 [AOSP].
  • Minimum version: Android 12 (Server.scrcpy refuses below; that is when shell could open the camera).
  • Flow: dedicated HandlerThread; openCamera(id, callback, handler); choose a size from StreamConfigurationMap.getOutputSizes(MediaCodec.class) (or high-speed sizes); SessionConfiguration(SESSION_REGULAR | SESSION_HIGH_SPEED, [OutputConfiguration(encoderSurface)], executor, stateCallback); createCaptureRequest(TEMPLATE_RECORD), add the surface, optionally set CONTROL_AE_TARGET_FPS_RANGE = Range(fps, fps), FLASH_MODE_TORCH, CONTROL_ZOOM_RATIO; setRepeatingRequest.
  • Constraints [scrcpy]:
    • The camera only renders to a surface whose size equals a supported capture size. Any other output size needs the OpenGL stage; v4.1 adapts the target size to avoid configuration errors (#6919).
    • SurfaceTexture’s transform matrix is wrong for camera input; scrcpy substitutes a vertical-flip matrix when it uses GL.
    • Declared sizes and frame rates are not reliable on all devices (scrcpy doc/camera.md).
    • The camera can be taken away (another app opens it); scrcpy marks the capture closed and ends the stream.
  • Android 16 breakage: CameraManager.getCameraCharacteristics now calls getRotationOverride → ActivityManager.getAppTasks(), which sent package android for uid 2000 and was denied (#6523, fixed v3.3.4). The fix is the activity entry in FakeContext.getSystemService (patching the ActivityManager’s mContext).

Per version / Samsung

  • 14 / 15: works with the fake context.
  • 16: needs the ActivityManager context patch.
  • Samsung: scrcpy v2.3 “fix camera issues on many devices” (#4392); nothing newer and Samsung-specific found. Behaviour while the phone is locked or the camera privacy toggle is on is UNVERIFIED.

What to do

  • Offer only sizes reported by getOutputSizes(MediaCodec.class) and encode at exactly that size, so no GL stage is needed. Send sensor orientation and facing in StreamOpen and rotate/flip on the desktop before v4l2sink.
  • Expose camera list (id, facing, sizes, fps ranges) through ShellHello or a dedicated message.
  • Keep the normal-tier foreground camera stream (ADR-0007) as the fallback when the shell camera fails.
  • Handle camera disconnect as a clean stream end with a reason.

9. Privileged commands for grants

How it works

  • scrcpy mixes both styles [scrcpy]: binder for hot paths (settings through the settings content provider obtained with getContentProviderExternal, in wrappers/ContentProvider.java; activity start; force-stop), and plain Runtime.exec for rare things (dumpsys display parsing in wrappers/DisplayManager, helpers in util/Command.java).

  • Shell holds the needed permissions on 14/15/16 [AOSP Shell manifest]: GRANT_RUNTIME_PERMISSIONS, MANAGE_APP_OPS_MODES, MANAGE_NOTIFICATION_LISTENERS, WRITE_SECURE_SETTINGS, CHANGE_DEVICE_IDLE_TEMP_WHITELIST, DEVICE_POWER.

  • Per grant:

    GoalCommandNotes
    Runtime permissionspm grant org.tether.android <permission>Only for runtime (dangerous) or development permissions.
    Notification accesscmd notification allow_listener org.tether.android/<listener class>Skips the Android 13+ “restricted settings” UI gate for sideloaded apps.
    OTP / sensitive notifications (15+)appops set org.tether.android RECEIVE_SENSITIVE_NOTIFICATIONS allowRECEIVE_SENSITIVE_NOTIFICATIONS is `signature
    All files accessappops set org.tether.android MANAGE_EXTERNAL_STORAGE allowPermission is `signature
    Battery allowlistdumpsys deviceidle whitelist +org.tether.androidUser allowlist.
    Settings`settings put <globalsecure
  • Persistence across reboot (UNVERIFIED as a set; standard platform behaviour, confirm each on the A55): runtime permission grants, app-op modes, the enabled notification listener list, the device-idle user allowlist and settings values are all stored on disk and survive reboot. They are lost on uninstall, and app-ops/permissions can be reset by the user (“Reset app preferences”, manual revoke). Not persistent: the helper itself, display power state, deviceidle tempwhitelist, and wireless debugging on Samsung (ADR-0007).

  • Hard-restricted runtime permissions (SMS, call log) may need installer allowlisting before pm grant takes effect. UNVERIFIED; check against how ADR-0011 already obtains them.

Per version / Samsung

  • 14: no sensitive-notification gate.
  • 15 / 16: RECEIVE_SENSITIVE_NOTIFICATIONS app-op needed for OTP content. Android 16 restricts which device_config flags shell may write (allowlist); none of our grants use device_config.
  • Samsung: no extra developer toggle is needed for pm grant (unlike the Xiaomi family). One UI’s own “sleeping apps” list is separate from the device-idle allowlist and has no known shell command; UNVERIFIED.

What to do

  • Exec the commands from the helper with ProcessBuilder, array arguments (never a shell string), capture exit code + stderr into GrantResult. They are rare, the CLIs are stable across 14–16, and binder signatures for the same operations are not.
  • After each grant, verify by reading back (appops get, cmd notification list_listeners or the secure setting, dumpsys deviceidle whitelist, dumpsys package permission state) and report the verified state, not the exit code.
  • Whitelist the exact set of grant items in the helper; do not expose a generic “run command” message over the socket.
  • Re-check grants on every helper start and repair silently; treat them as persistent but revocable.

10. App list with labels and icons

How it works

  • scrcpy (Device.listApps and friends) [scrcpy]: FakeContext.getPackageManager(); getInstalledApplications(GET_META_DATA); keep entries where appInfo.enabled and getLaunchIntentForPackage(pkg) ?: getLeanbackLaunchIntentForPackage(pkg) is non-null; label from pm.getApplicationLabel(appInfo); system flag from ApplicationInfo.FLAG_SYSTEM. It is slow (“this may take some time”) and runs on a worker. --list-apps broke once and was fixed in v3.3.1 (#6165), so the fake context path for PackageManager is exercised upstream. Shell holds QUERY_ALL_PACKAGES [AOSP].
  • Icons: scrcpy does not fetch icons at all. Loading pm.getApplicationIcon(...) and rasterising an AdaptiveIconDrawable to a Bitmap inside app_process is plausible but UNVERIFIED.
  • CLI alternative: cmd package query-activities --brief -a android.intent.action.MAIN -c android.intent.category.LAUNCHER lists launchable components; no labels or icons.

What to do

  • Build AppList in the normal app, not in the helper. Our app has a real Context, resources and bitmaps: declare a <queries> element for ACTION_MAIN + CATEGORY_LAUNCHER (no QUERY_ALL_PACKAGES needed), use queryIntentActivities or LauncherApps for label + icon, hash the PNG for icon_hash, cache by package + lastUpdateTime. This also works in the normal tier (for “Open on phone”) and keeps the helper small.
  • The helper only needs StartApp{package, display_id}: resolve the launch intent with FakeContext.getPackageManager().getLaunchIntentForPackage (the scrcpy path) or accept an explicit component from the app’s list.
  • If a shell-side list is ever needed (app not running), use scrcpy’s PackageManager approach for package + label and skip icons.

11. Samsung / One UI problems and workarounds

ProblemEvidenceWorkaround
NPE in ConfigurationController.getConfiguration() when reading display info (Android 14+ One UI)#4467, v2.3.1fillConfigurationController() before first system-context use (section 1).
Clipboard: “calling package android does not match caller’s uid 2000” via SemClipboardManager#6224 v3.3.2, #6523 v3.3.4Fake content resolver + patch mContext of clipboard and semclipboard managers.
Settings/display state not restored after disconnect#6405, #6540, v3.3.4Cleanup child in its own session (Os.setsid()).
Encoder abort when the process command line is long (Android 11 Samsung)#7169 openShort argv; pass options over stdin/socket.
New display shows a DeX-like shell, double nav bar, duplicated icons#6591, #6270, #6433Create displays without SHOULD_SHOW_SYSTEM_DECORATIONS.
Typing sometimes ignored on a new display, Android 16 / One UI 8.5#6909 openNone known. Have paste and UHID text paths.
setDisplayImePolicy throws (S10+, Android 12)#5997 openCatch, fall back to default/hide. Status on 16 UNVERIFIED.
New display unusable on Z Fold 4 / Android 16#6855 open, unconfirmedNone. Probe and degrade to main-display mirror.
Mirroring an existing DeX display is black on Android 15#6287 openNot our use case; do not target DeX displays.
Auto Blocker blocks adb commands over USBPress and vendor help pages (HotHardware, Phonecheck); default-on on newer One UI per netzweltUser must turn it off (or its USB-commands sub-option). Whether it also blocks wireless debugging was not answered by any source: UNVERIFIED, test on the A55. One UI 9 beta “Maximum restrictions” reportedly blocks USB entirely (Android Authority).
Wireless debugging off after rebootADR-0007 (not re-verified here)Detect and prompt; USB fallback.
Knox / app_processNo Knox-specific app_process restriction found in scrcpy source or tracker beyond the items aboveNothing to do. Not using root, so Knox warranty bit is untouched.
Secure Folder, Samsung Pass, banking appsGeneral FLAG_SECURE behaviour (section 2); Samsung specifics UNVERIFIEDBlack frames; show a “protected content” hint on the desktop.

What to do

  • Treat the first five rows as mandatory ports; they are cheap and already proven upstream.
  • Add a ShellHello.diagnostics block: brand, model, SDK, One UI version (ro.build.version.oneui), which workarounds applied, which probes failed.
  • Run a scripted A55 acceptance pass before building UI: display info, mirror, rotation event, clipboard read/write/listener, new display without decorations, app start, key + text into that display, IME policy, screen off/on + cleanup after adb kill-server, both audio sources, camera open.
  • Watch scrcpy’s tracker for #6909; it is the same OS build family as the test phone.

12. New shell restrictions in Android 15 / 16

Findings

  • No permission was removed from the shell package between android14-release, android15-release and android16-release [AOSP packages/Shell/AndroidManifest.xml, diffed]. Every permission this design relies on is present in all three: INJECT_EVENTS, ADD_TRUSTED_DISPLAY, ADD_ALWAYS_UNLOCKED_DISPLAY, CAPTURE_VIDEO_OUTPUT, CAPTURE_AUDIO_OUTPUT, MODIFY_AUDIO_ROUTING, RECORD_AUDIO, CAMERA, READ_CLIPBOARD_IN_BACKGROUND, GRANT_RUNTIME_PERMISSIONS, MANAGE_APP_OPS_MODES, MANAGE_NOTIFICATION_LISTENERS, WRITE_SECURE_SETTINGS, DEVICE_POWER, QUERY_ALL_PACKAGES, START_ACTIVITIES_FROM_BACKGROUND. This is AOSP; Samsung’s shipped manifest may differ (UNVERIFIED; check with dumpsys package com.android.shell on the A55).

  • Never held: CAPTURE_SECURE_VIDEO_OUTPUT (so secure content stays black).

  • Added for shell: Android 15 MANAGE_DISPLAYS, RECEIVE_SENSITIVE_NOTIFICATIONS (for CTS; shell holding it does not let shell grant it to us). Android 16 ADD_MIRROR_DISPLAY (new gate for mirror displays; shell passes it), MANAGE_ADVANCED_PROTECTION_MODE / QUERY_ADVANCED_PROTECTION_MODE.

  • Behaviour changes that broke scrcpy without any permission change:

    ReleaseChangeReference
    14Display tokens moved to DisplayControl; DisplayListener unreliable; native_setup gained a parameter; --lock-video-orientation and crop paths brokev2.3, v2.4, v3.0 notes
    14 QPR3 / 15freezeDisplayRotation / thawDisplayRotation gained a String caller parameterwrappers/WindowManager.java
    15New requestDisplayPower, unusable on some devices; DisplayListener broke again in a monthly update#5530, #5908
    15OTP content withheld from notification listeners without the sensitive-notifications app-opsection 9
    16AudioRecord.Builder failed for shell during previews (twice)#5698, #6021
    16IDisplayWindowListener gained methods → AbstractMethodError#6331, #6362
    16CameraManager performs a package/uid check through getAppTasks#6523
    16device_config writes from shell limited to an allowlistAOSP mirror commits (omnirom gerrit); secondary source
  • Android 16 Advanced Protection Mode: its effect on adb / wireless debugging was not established. UNVERIFIED.

  • Pattern: most breakages arrived in monthly or QPR updates, not at major releases, and were package-attribution checks or interface growth rather than permission removals.

What to do

  • Design for breakage between app releases: every feature is a probed capability in ShellHello; one failing probe never takes down the helper; failures carry the exception class and message so the desktop can show a precise “not supported on this build” and we can triage from logs.
  • Any binder callback class we implement must tolerate unknown transactions (the onTransact guard).
  • Anything that passes a package name must pass com.android.shell, never android. When a new SecurityException mentions “package android … uid 2000”, the fix is almost always another manager whose mContext needs the fake context.
  • Track scrcpy releases as an early-warning feed; its fixes for Pixel betas typically precede the same base reaching One UI.

Open items to verify on the Galaxy A55 (Android 16 / One UI 8.5)

  1. --nice-name accepted by app_process; stdin token hand-off works over wireless adb.
  2. Workarounds all apply; getDisplayInfo(0) returns data.
  3. Window-listener events arrive on rotation; no AbstractMethodError.
  4. Clipboard read / write / listener, locked and unlocked.
  5. New display without system decorations: app start, touch, keys, text, IME policy result; behaviour when the app is already open on the phone.
  6. DisplayControl screen-off path and cleanup after transport loss.
  7. REMOTE_SUBMIX and AudioPolicy capture; Opus encoder present.
  8. Camera open and sizes; behaviour while locked.
  9. Each grant command, its read-back, and survival across reboot.
  10. Whether Auto Blocker affects wireless debugging.
  11. dumpsys package com.android.shell permission list versus AOSP.