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/):
| Topic | File |
|---|---|
| Entry point, looper, exit | Server.java |
| ActivityThread / context hacks, AudioRecord fallback | Workarounds.java |
| Fake context | FakeContext.java |
| Restore-on-death process | CleanUp.java |
| Main display mirror | video/ScreenCapture.java |
| New virtual display | video/NewDisplayCapture.java |
| Encoder loop | video/SurfaceEncoder.java, video/CaptureControl.java |
| Packet framing | device/Streamer.java |
| Display change detection | display/DisplayMonitor.java, wrappers/DisplayWindowListener.java |
| Hidden API wrappers | wrappers/ (DisplayManager, SurfaceControl, DisplayControl, InputManager, WindowManager, ActivityManager, PowerManager, ClipboardManager, ServiceManager) |
| Input, clipboard, app start | control/Controller.java, device/Device.java |
| Audio | audio/ (AudioDirectCapture, AudioPlaybackCapture, AudioRecordReader, AudioEncoder, AudioConfig) |
| Camera | video/CameraCapture.java |
| Compile-time AIDL stubs | server/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_processaccepts a dex, jar or apk that containsclasses.dex(scrcpydoc/develop.md).pm path org.tether.androidprintspackage:/data/app/~~…/base.apk(one line per split); strippackage:and take thebase.apkline. 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 fromSystem.getProperty("java.class.path")(first entry) so it can relaunch itself for the cleanup child. - Process name.
app_processtakes--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 ofapp_main.cpp); scrcpy does not use it. - Hidden API policy. scrcpy uses plain
Class.forName/getDeclaredMethodeverywhere with no exemption trick, which implies hidden-API enforcement is not applied to a shell-startedapp_process. No bypass library is needed. (Inference from scrcpy; UNVERIFIED by reading ART source.) - Startup order in
Server.main/internalMain[scrcpy]:- Install a default uncaught-exception handler that logs thread + throwable and then chains to the previous handler.
- If uid is 0 (rooted adbd),
Os.setuid(2000): clipboard does not work as root (#6224). - Prepare a quittable main looper:
Looper.prepare()then set the private staticLooper.sMainLoopertoLooper.myLooper()by reflection. (Looper.prepareMainLooper()makes it non-quittable.) - Parse options; apply workarounds (below); open the connection; start
worker threads;
Looper.loop()on the main thread. - When all workers finish or one reports a fatal error, call
Looper.getMainLooper().quitSafely(), stop/join workers, and finally alwaysSystem.exit(status), because framework classes may have started non-daemon threads that would keep the VM alive.
- Workarounds (
Workarounds.java) [scrcpy]. A static initialiser: constructsandroid.app.ActivityThreadthrough its private constructor, stores it in the staticsCurrentActivityThread, and setsmSystemThread = true. Thenapply()does, in this order:fillConfigurationController()(API 31+): buildandroid.app.ConfigurationController(ActivityThreadInternal)with the activity thread and store it inmConfigurationController. Needed on Samsung, whereDisplayManagerGlobal.getDisplayInfoLocked()callsActivityThread.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 firstgetSystemContext()call.fillAppInfo(): createActivityThread$AppBindData, set itsappInfoto anApplicationInfowhosepackageNameiscom.android.shell, and store it inmBoundApplication. (Skipped on ONYX devices, irrelevant to us.)fillAppContext():Instrumentation.newApplication(Application.class, FakeContext)and store the result inmInitialApplication, soActivityThread.currentApplication()is non-null. All three are wrapped in try/catch and failure is only logged.
- FakeContext (
FakeContext.java) [scrcpy]: aContextWrapperaroundActivityThread.getSystemContext()(reflection) that overrides:getPackageName()andgetOpPackageName()→"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 anonymousContentResolversubclass whose hiddenacquireProvider(Context, String)goes throughIActivityManager.getContentProviderExternal(name, userId 0, token, tag)(the mechanismsettings/contentshell commands use) and returns theproviderfield of the returned holder. The other four hidden abstract methods are stubbed. This needs a compile-time stub ofandroid.content.IContentProvider.getSystemService(name): forclipboard, the Samsung-internalsemclipboard, andactivity, overwrite the returned manager’s privatemContextfield with the fake context so later binder calls carry packagecom.android.shellinstead ofandroid. The reason for all of this: the system context’s package isandroid, and system_server rejectsandroidfor 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 forwindow,power, and the activity manager (viaActivityManagerNative.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 callsOs.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 inCleanUp.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:
fillConfigurationControlleris mandatory (Android 14+ One UI). - Samsung Android 11 only: the encoder crashes when
/proc/self/cmdlineexceeds 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-nameonly 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 viaps, and long command lines are a known Samsung hazard. Write it to the helper’s stdin as the first line instead. - Port
Workarounds+FakeContextalmost one to one; keep the same call order; keep every step individually try/caught and report which ones failed inShellHelloas diagnostics. - Release builds use R8 (
isMinifyEnabled = true): add keep rules fororg.tether.shell.**entry points and anything reached only by reflection or byapp_process. - Put framework stubs (
android.content.IContentProvider,android.view.IDisplayWindowListener,android.content.IOnPrimaryClipChangedListener) in acompileOnlymodule 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,compileOnlyis cleaner inside an app APK. UNVERIFIED that AIDL generation works from acompileOnlymodule 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. Keeporg.tether.shellfree ofR.*, Compose, Hilt and JNI. Kotlin stdlib and coroutines are fine (Dispatchers.Mainworks only after the main looper is prepared). - Exit rules: socket EOF or stdin EOF → orderly stop →
exitProcess. Port the cleanup child withsetsid()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 staticandroid.hardware.display.DisplayManager.createVirtualDisplay(String name, int width, int height, int displayIdToMirror, Surface surface)by reflection; this returns aVirtualDisplaythat mirrors an existing display at the requested size. Only if that throws does it fall back toSurfaceControl.createDisplay(name, secure)+ a transaction (setDisplaySurface,setDisplayProjection(token, 0, deviceRect, targetRect),setDisplayLayerStack(token, layerStack)). -
Why DisplayManager on 14+. The
SurfaceControldisplay-token methods were moved out ofandroid.view.SurfaceControlin Android 14 (intocom.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 inDevice.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 newADD_MIRROR_DISPLAYpermission and shell holds it. -
Secure content. Shell cannot create a secure display since Android 12 (comment in
ScreenCapture.createDisplay); shell does not holdCAPTURE_SECURE_VIDEO_OUTPUTon 14/15/16 [AOSP].FLAG_SECUREwindows (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 lacksFLAG_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 hiddenDisplayInfo; read fieldslogicalWidth,logicalHeight(already rotated),rotation,layerStack,flags,logicalDensityDpi, anduniqueId(may be missing on some ROMs, #6461). If the call returns null, scrcpy parsesdumpsys displaywith a regex on themOverrideDisplayInfoline. -
Change detection (
DisplayMonitor) [scrcpy]: on Android 14+ scrcpy does not useDisplayManager.DisplayListener; it registers anIDisplayWindowListenerwithIWindowManager.registerDisplayWindowListenerand reacts toonDisplayConfigurationChanged(displayId, Configuration). Reason:DisplayListenernever fired on some Android 14 builds and broke again in an Android 15 update (#5908, fixed v3.2). On each event it re-readsDisplayInfo, 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 throwsAbstractMethodErroron a binder thread and kills the process (#6331, #6362, fixed v3.3.2 / v3.3.3). scrcpy’s fix is to overrideonTransact, catchAbstractMethodError, callreply.writeNoException()and return true. -
Rotation / resize / fold handling (
SurfaceEncoder.streamCapture,CaptureControl) [scrcpy]: a reset callssignalEndOfInputStream()on the running codec; the drain loop sees EOS, then the outer loop stops andreset()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’sVideoCapabilities.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]:Key Value KEY_MIMEvideo/avc(default),video/hevc,video/av01, VP8/VP9 since v4.1KEY_BIT_RATE8 000 000 default KEY_FRAME_RATE60 (required by configure; real rate is variable) KEY_COLOR_FORMATCOLOR_FormatSurfaceKEY_COLOR_RANGECOLOR_RANGE_LIMITEDKEY_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 withdequeueOutputBuffer(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 (u64big-endian = PTS in µs, with bit 62 = config packet and bit 61 = key frame;u32length) 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 isBufferInfo.presentationTimeUsunchanged.
Per version / Samsung
- 14:
DisplayListenerunreliable → window listener path. - 15: same; a QPR broke
DisplayListeneragain (#5908). - 16:
IDisplayWindowListenergrew methods (guardonTransact);ADD_MIRROR_DISPLAYexists and is held by shell. - Samsung: needs the configuration-controller workaround for
getDisplayInfo. Exynos encoder behaviour on the A55 (alignment,KEY_LATENCYsupport) 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 theSurfaceControlfallback. - 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 theonTransactguard. This is the single most likely thing to crash on One UI 8.5. - Copy scrcpy’s
MediaFormatas 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 withMediaCodec.setParameters(PARAMETER_KEY_REQUEST_SYNC_FRAME)when a viewer (re)attaches instead of a 10 s wait; change bitrate live withPARAMETER_KEY_VIDEO_BITRATE. - Map framing onto our protocol:
StreamOpencarries 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 desktoph264parseneeds 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]: instantiateandroid.hardware.display.DisplayManagerthrough its hidden(Context)constructor with the fake context, then call the publiccreateVirtualDisplay(name, width, height, dpi, surface, flags). -
Flags (
NewDisplayCapture.startNew) [scrcpy]:Flag Value When 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-contentSHOULD_SHOW_SYSTEM_DECORATIONS1 << 9default on; off with --no-vd-system-decorationsTRUSTED1 << 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_WINDOWare all held by shell. -
Minimum version. scrcpy refuses
--new-displaybelow 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. WithminSdk 34we 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 fromFakeContext.getPackageManager().getLaunchIntentForPackage(pkg)(leanback intent as fallback), addFLAG_ACTIVITY_NEW_TASK, buildActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle(), and callIActivityManager.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 callforceStopPackage(pkg, -2)first. The CLI equivalent isam 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 withVirtualDisplay.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_REMOVALthe tasks on it are removed; without it they move to the main display (scrcpydoc/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):0local,1fallback display (default: keyboard appears on the phone’s own screen),2hide. 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
VirtualDisplayper streamed app. Flags: scrcpy’s full Android 14 set minusSHOULD_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.startActivityAsUserwithsetLaunchDisplayId; keepam start --displayas 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
StreamOpenand rotate on the desktop (GStreamervideoflip). 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, soHIDEis a reasonable second choice. - Run a
userActivityticker 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 realandroid.hardware.input.InputManagerfromFakeContext.getSystemService("input")and invoke the hiddeninjectInputEvent(InputEvent, int mode). Modes:0async,1wait for result,2wait for finish. scrcpy uses async for everything except the synthetic COPY/CUT key before a clipboard read (wait for finish). Shell holdsINJECT_EVENTSon 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 reusablePointerProperties(toolType = TOOL_TYPE_FINGER) andPointerCoords(x, y, pressure; size and orientation 0). Build withMotionEvent.obtain(downTime, eventTime, action, pointerCount, props, coords, metaState=0, buttonState, xPrecision=1f, yPrecision=1f, deviceId=0, edgeFlags=0, source, flags=0).downTimeis the time of the first pointer’sACTION_DOWN. With more than one pointer, down/up becomeACTION_POINTER_DOWN/UP | (index << ACTION_POINTER_INDEX_SHIFT). Source isSOURCE_TOUCHSCREENandbuttonStatemust 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_DOWNthenACTION_BUTTON_PRESS; other buttons →ACTION_BUTTON_PRESSonly; release →ACTION_BUTTON_RELEASE, andACTION_UPafter the last one. The action button is set with the hiddenMotionEvent.setActionButton(int). Hover isACTION_HOVER_MOVE. - Scroll: one pointer,
ACTION_SCROLL,SOURCE_MOUSE, withAXIS_HSCROLL/AXIS_VSCROLLset 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 areKEYCODE_BACK,KEYCODE_HOME,KEYCODE_APP_SWITCH. scrcpy’s right-click is “back, or POWER if the screen is off”, decided withisDisplayInteractive(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 injectKEYCODE_PASTE(scrcpydoc/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/uhidand 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 withInputManager.addUniqueIdAssociationByPort(inputPort, displayUniqueId)usingDisplayInfo.uniqueId(v3.3). Below 15 a UHID mouse only works on the main display. - Permission error. Some OEMs gate
INJECT_EVENTSbehind an extra developer toggle (“USB debugging (Security settings)”, Xiaomi family); scrcpy detects theSecurityExceptiontext and prints guidance (#6080). Not known to affect Samsung.
Per version / Samsung
- 14:
OWN_FOCUSgives 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,PointersStateand 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
KeyCharacterMapfirst; on a null result fall back to clipboard +KEYCODE_PASTEfor 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
SecurityExceptionon first injection as a capability failure inShellHelloinstead 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 mode0(off) or2(normal), by reflection onandroid.view.SurfaceControl. - Tokens on Android 14+ (
wrappers/DisplayControl) [scrcpy]:getPhysicalDisplayIds()andgetPhysicalDisplayToken(long)are no longer onSurfaceControl; they live incom.android.server.display.DisplayControl, which is in the system-server jars, not the boot classpath. The trick:com.android.internal.os.ClassLoaderFactory.createClassLoader(String dexPath, String librarySearchPath, String libraryPermittedPath, ClassLoader parent, int targetSdkVersion, boolean isNamespaceShared, String classLoaderName)withdexPath = Os.getenv("SYSTEMSERVERCLASSPATH"), nulls, the system class loader as parent,0,true,null.loadClass("com.android.server.display.DisplayControl").- Invoke the private
Runtime.loadLibrary0(Class, String)with that class and"android_servers"so its native methods bind. - Call the static
getPhysicalDisplayIds(): long[]andgetPhysicalDisplayToken(long): IBinder. scrcpy picks this path when SDK ≥ 34 andSurfaceControlhas nogetPhysicalDisplayIds(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 commandcmd display power-off 0/power-on 0is the same mechanism (Android 15+, scrcpydoc/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_WAKEUPkey-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 theuserActivityticker. - 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:
DisplayControlclass-loader path. 15+ also hasrequestDisplayPower/cmd display power-offas 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
DisplayControlpath first; keepcmd display power-off <id>(exec) as the fallback on 15+ and probe which one works atShellHello. - Always run the cleanup child when
screen_offis requested; never rely on in-processfinallyblocks. - Wireless adb means “not plugged in” is common, so
stay_on_while_plugged_inis not enough: use theuserActivityticker (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 realandroid.content.ClipboardManagerfromFakeContext.getSystemService("clipboard")(whosemContexthas been replaced by the fake context) and uses the publicgetPrimaryClip(),setPrimaryClip(ClipData.newPlainText(null, text))andaddPrimaryClipChangedListener(...). The manager fills in packagecom.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): ClipDatasetPrimaryClip(ClipData clip, String callingPackage, String attributionTag, int userId, int deviceId)addPrimaryClipChangedListener(IOnPrimaryClipChangedListener listener, String callingPackage, String attributionTag, int userId, int deviceId)(and the matchingremove…), listener is a oneway interface with one methoddispatchPrimaryClipChanged().- Also
hasPrimaryClip,getPrimaryClipDescription,clearPrimaryClip,getPrimaryClipSourcewith the same four trailing parameters. - Values scrcpy used: package
com.android.shell, tagnull, user0, device id0(default device).deviceIdis the Android 14 addition.
- OEM signature drift (scrcpy v3.2
wrappers/ClipboardManager.java): sevengetPrimaryClipvariants were probed in order, including OEM ones with an extra trailingboolean userOperate(Honor, #4822), a seven-argument form, and a trailingString. This probing is exactly what the switch to the real manager removed. - Samsung. One UI’s
ClipboardManagerdelegates toSemClipboardManager, which readsSettings.Systemthrough 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 thesemclipboardservice’s context as well (#6523, v3.3.4). Both are covered byFakeContextas described in section 1. - Echo suppression [scrcpy]: an atomic “setting clipboard” flag is raised
around
setPrimaryClipso 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
semclipboardpatch. UNVERIFIED on One UI 8.5.
What to do
- Use the real
ClipboardManagerthroughFakeContext, created on the main looper thread; register the listener there; pushClipboardmessages on change and answerClipboardReadon demand. - Keep a raw
IClipboardpath (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 (scrcpydoc/audio.md).playback: anAudioPolicyloopback mix (below), Android 13+.micand other microphone presets; since v3.2 alsoVOICE_CALL,VOICE_UPLINK,VOICE_DOWNLINK,VOICE_PERFORMANCE.
- Permissions [AOSP Shell manifest 14/15/16]:
RECORD_AUDIO,CAPTURE_AUDIO_OUTPUT,MODIFY_AUDIO_ROUTINGall 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().setContextis what makes the attribution (uid 2000,com.android.shell) correct. - Fallback constructor (
Workarounds.createAudioRecord) [scrcpy], used only when the builder throwsNullPointerException(Vivo): create an emptyAudioRecordthrough the hidden(long)constructor, set private fields (mRecordingState,mInitializationLooper,mAudioAttributesbuilt with the hiddenAudioAttributes.Builder.setInternalCapturePreset(int),mChannelCount,mChannelMask), call the privateaudioParamCheckandaudioBuffSizeCheck, then the privatenative_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 hiddenAttributionSource.asScopedParcelState()→getParcel(). Then setmSampleRate,mSessionId,mState = STATE_INITIALIZED. - Android 11 foreground hack: start
com.android.shell/.HeapDumpActivityso uid 2000 counts as foreground, retry, then force-stop the shell package. Android 11 only; irrelevant withminSdk 34. - Android 16:
AudioRecord.Builder.build()threwUnsupportedOperationException: Cannot create AudioRecordon 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 ofFakeContext(attribution source,getDeviceId,setContext) is the result. UNVERIFIED beyond that. - Playback capture (
AudioPlaybackCapture) [scrcpy, #4380], all hidden classes inandroid.media.audiopolicy: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().AudioMix.Builder(rule).setFormat(format).setRouteFlags(flag).build()withROUTE_FLAG_LOOP_BACK(captured audio is removed from the phone’s speaker) orROUTE_FLAG_LOOP_BACK_RENDER(duplication: still plays on the phone; scrcpy--audio-dup).AudioPolicy.Builder(FakeContext).addMix(mix).build().- Hidden static
AudioManager.registerAudioPolicyStatic(policy), must return 0. policy.createAudioRecordSink(mix)returns theAudioRecord. Needs Android 13 (when shell gainedMODIFY_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 fromAudioRecord.getTimestamp(ts, TIMEBASE_MONOTONIC), falling back to previous PTS + duration, forced strictly increasing. - Encoding (
AudioEncoder):MediaCodecforaudio/opus,KEY_BIT_RATE = 128000,KEY_CHANNEL_COUNT = 2,KEY_SAMPLE_RATE = 48000; asynchronous callback on aHandlerThread, separate input and output threads. If the device has no Opus encoder, configure fails with0xfffffffeand 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, theOpusHeadbytes, thenAOPUSDLY/AOPUSPRLblocks.Streamer.fixOpusConfigPackettrims it to justOpusHead. 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_setuphas the extrahalInputFlags. - 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.encoderon the A55 is expected but UNVERIFIED.
What to do
- Map protocol
AudioStart.source:OUTPUT→REMOTE_SUBMIX(phone goes silent, captures everything);PLAYBACK_DUP→AudioPolicywithROUTE_FLAG_LOOP_BACK_RENDER. Consider a third value forROUTE_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
OUTPUTas “capture everything (mutes phone)”. - Use the builder with
setContext(FakeContext)only. Port the reflectivenative_setupfallback only if the A55 actually needs it. - Strip the Opus config to
OpusHeadand put it inStreamOpen; the desktop can feed it toopusdecas 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]: constructandroid.hardware.camera2.CameraManagerthrough its hidden(Context)constructor with the fake context. Shell holdsandroid.permission.CAMERAon 14/15/16 [AOSP]. - Minimum version: Android 12 (
Server.scrcpyrefuses below; that is when shell could open the camera). - Flow: dedicated
HandlerThread;openCamera(id, callback, handler); choose a size fromStreamConfigurationMap.getOutputSizes(MediaCodec.class)(or high-speed sizes);SessionConfiguration(SESSION_REGULAR | SESSION_HIGH_SPEED, [OutputConfiguration(encoderSurface)], executor, stateCallback);createCaptureRequest(TEMPLATE_RECORD), add the surface, optionally setCONTROL_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.getCameraCharacteristicsnow callsgetRotationOverride→ActivityManager.getAppTasks(), which sent packageandroidfor uid 2000 and was denied (#6523, fixed v3.3.4). The fix is theactivityentry inFakeContext.getSystemService(patching theActivityManager’smContext).
Per version / Samsung
- 14 / 15: works with the fake context.
- 16: needs the
ActivityManagercontext 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 inStreamOpenand rotate/flip on the desktop beforev4l2sink. - Expose camera list (id, facing, sizes, fps ranges) through
ShellHelloor 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
settingscontent provider obtained withgetContentProviderExternal, inwrappers/ContentProvider.java; activity start; force-stop), and plainRuntime.execfor rare things (dumpsys displayparsing inwrappers/DisplayManager, helpers inutil/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:
Goal Command Notes Runtime permissions pm grant org.tether.android <permission>Only for runtime (dangerous) or development permissions. Notification access cmd 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_NOTIFICATIONSis `signatureAll files access appops set org.tether.android MANAGE_EXTERNAL_STORAGE allowPermission is `signature Battery allowlist dumpsys deviceidle whitelist +org.tether.androidUser allowlist. Settings `settings put <global secure -
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 granttakes effect. UNVERIFIED; check against how ADR-0011 already obtains them.
Per version / Samsung
- 14: no sensitive-notification gate.
- 15 / 16:
RECEIVE_SENSITIVE_NOTIFICATIONSapp-op needed for OTP content. Android 16 restricts whichdevice_configflags shell may write (allowlist); none of our grants usedevice_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 intoGrantResult. 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_listenersor the secure setting,dumpsys deviceidle whitelist,dumpsys packagepermission 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.listAppsand friends) [scrcpy]:FakeContext.getPackageManager();getInstalledApplications(GET_META_DATA); keep entries whereappInfo.enabledandgetLaunchIntentForPackage(pkg) ?: getLeanbackLaunchIntentForPackage(pkg)is non-null; label frompm.getApplicationLabel(appInfo); system flag fromApplicationInfo.FLAG_SYSTEM. It is slow (“this may take some time”) and runs on a worker.--list-appsbroke once and was fixed in v3.3.1 (#6165), so the fake context path forPackageManageris exercised upstream. Shell holdsQUERY_ALL_PACKAGES[AOSP]. - Icons: scrcpy does not fetch icons at all. Loading
pm.getApplicationIcon(...)and rasterising anAdaptiveIconDrawableto aBitmapinsideapp_processis plausible but UNVERIFIED. - CLI alternative:
cmd package query-activities --brief -a android.intent.action.MAIN -c android.intent.category.LAUNCHERlists launchable components; no labels or icons.
What to do
- Build
AppListin the normal app, not in the helper. Our app has a realContext, resources and bitmaps: declare a<queries>element forACTION_MAIN+CATEGORY_LAUNCHER(noQUERY_ALL_PACKAGESneeded), usequeryIntentActivitiesorLauncherAppsfor label + icon, hash the PNG foricon_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 withFakeContext.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
PackageManagerapproach for package + label and skip icons.
11. Samsung / One UI problems and workarounds
| Problem | Evidence | Workaround |
|---|---|---|
NPE in ConfigurationController.getConfiguration() when reading display info (Android 14+ One UI) | #4467, v2.3.1 | fillConfigurationController() 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.4 | Fake content resolver + patch mContext of clipboard and semclipboard managers. |
| Settings/display state not restored after disconnect | #6405, #6540, v3.3.4 | Cleanup child in its own session (Os.setsid()). |
| Encoder abort when the process command line is long (Android 11 Samsung) | #7169 open | Short argv; pass options over stdin/socket. |
| New display shows a DeX-like shell, double nav bar, duplicated icons | #6591, #6270, #6433 | Create displays without SHOULD_SHOW_SYSTEM_DECORATIONS. |
| Typing sometimes ignored on a new display, Android 16 / One UI 8.5 | #6909 open | None known. Have paste and UHID text paths. |
setDisplayImePolicy throws (S10+, Android 12) | #5997 open | Catch, fall back to default/hide. Status on 16 UNVERIFIED. |
| New display unusable on Z Fold 4 / Android 16 | #6855 open, unconfirmed | None. Probe and degrade to main-display mirror. |
| Mirroring an existing DeX display is black on Android 15 | #6287 open | Not our use case; do not target DeX displays. |
| Auto Blocker blocks adb commands over USB | Press and vendor help pages (HotHardware, Phonecheck); default-on on newer One UI per netzwelt | User 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 reboot | ADR-0007 (not re-verified here) | Detect and prompt; USB fallback. |
Knox / app_process | No Knox-specific app_process restriction found in scrcpy source or tracker beyond the items above | Nothing to do. Not using root, so Knox warranty bit is untouched. |
| Secure Folder, Samsung Pass, banking apps | General FLAG_SECURE behaviour (section 2); Samsung specifics UNVERIFIED | Black 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.diagnosticsblock: 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-releaseandandroid16-release[AOSPpackages/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 withdumpsys package com.android.shellon 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 16ADD_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:
Release Change Reference 14 Display tokens moved to DisplayControl;DisplayListenerunreliable;native_setupgained a parameter;--lock-video-orientationand crop paths brokev2.3, v2.4, v3.0 notes 14 QPR3 / 15 freezeDisplayRotation/thawDisplayRotationgained aString callerparameterwrappers/WindowManager.java15 New requestDisplayPower, unusable on some devices;DisplayListenerbroke again in a monthly update#5530, #5908 15 OTP content withheld from notification listeners without the sensitive-notifications app-op section 9 16 AudioRecord.Builderfailed for shell during previews (twice)#5698, #6021 16 IDisplayWindowListenergained methods →AbstractMethodError#6331, #6362 16 CameraManagerperforms a package/uid check throughgetAppTasks#6523 16 device_configwrites 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
onTransactguard). - Anything that passes a package name must pass
com.android.shell, neverandroid. When a newSecurityExceptionmentions “package android … uid 2000”, the fix is almost always another manager whosemContextneeds 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)
--nice-nameaccepted byapp_process; stdin token hand-off works over wireless adb.- Workarounds all apply;
getDisplayInfo(0)returns data. - Window-listener events arrive on rotation; no
AbstractMethodError. - Clipboard read / write / listener, locked and unlocked.
- New display without system decorations: app start, touch, keys, text, IME policy result; behaviour when the app is already open on the phone.
DisplayControlscreen-off path and cleanup after transport loss.REMOTE_SUBMIXandAudioPolicycapture; Opus encoder present.- Camera open and sizes; behaviour while locked.
- Each grant command, its read-back, and survival across reboot.
- Whether Auto Blocker affects wireless debugging.
dumpsys package com.android.shellpermission list versus AOSP.