Feature: Add screen preview to the Android client

get_screenshot and the server's online-list and hover thumbnails were
gated to Windows and X11 Linux. The Android client now answers
COMMAND_SCREEN_PREVIEW_REQ on the main connection with
TOKEN_SCREEN_PREVIEW_RSP plus a JPEG, and advertises
CLIENT_CAP_SCREEN_PREVIEW at login only when it can really capture.

Capture goes through AccessibilityService.takeScreenshot (API 30+),
enabled by canTakeScreenshot in the service config. MediaProjection is
deliberately not reused: its VirtualDisplay already feeds the H.264
encoder and Android 14+ refuses a second one from the same projection,
while accessibility capture runs alongside the live stream. The JPEG is
scaled to maxWidth and encoded in Kotlin; native only copies the bytes
and drops a request while one is in flight. Only mode=screen is
supported, and capabilities are re-evaluated on every login so turning
the service off withdraws the capability.

Also fix two review findings: a screenshot callback that lands after
the 3 s timeout now recycles its bitmap instead of leaking it, and the
server's failure hint lists the possible Android causes instead of
asserting disabled accessibility.

Verified on the emulator against a local debug server: get_screenshot
returns 640x1422 and 720x1600 JPEGs, the 120-wide list thumbnail works,
and both MCP tool-table checkers pass with apk added for get_screenshot,
get_activity_history and get_client_log.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-11 20:58:40 +01:00
1 parent 66acde0301
commit f29150d20e
6 files changed
+346 -16

No files matched your search

@@ -0,0 +1,138 @@
package com.yama.client
import android.accessibilityservice.AccessibilityService
import android.graphics.Bitmap
import android.os.Build
import android.util.Log
import android.view.Display
import java.io.ByteArrayOutputStream
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executor
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
/**
* 屏幕预览(MCP get_screenshot)的 Android 实现:借无障碍服务的
* [AccessibilityService.takeScreenshot](API 30+)抓一帧,等比缩到 maxWidth 以内再编码 JPEG。
*
* 刻意不走 MediaProjection:投屏的 VirtualDisplay 已经被 H.264 编码器占着,Android 14+
* 同一个投影再建第二个 VirtualDisplay 会失败;无障碍截屏与实时投屏互不干扰,用户拒绝投屏
* 授权时也照样能用。代价是 Android 11 以下没有这条路(不声明能力位,服务端直接拒绝)。
*/
object ScreenShot {
private const val TAG = "YAMA"
private const val CAPTURE_TIMEOUT_MS = 3000L
private const val MAX_WIDTH = 1920
/** 抓屏结果:JPEG 数据 + 实际编码后的宽高(服务端据此回报尺寸/换算比例) */
class Shot(val data: ByteArray, val width: Int, val height: Int)
/**
* 当前能否抓屏:API 30+ 且无障碍服务在跑。takeScreenshot 的能力来自服务配置
* (accessibility_service_config.xml 的 canTakeScreenshot),服务没起来就调不了。
*/
@JvmStatic
fun canCapture(): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return false
return ControlService.instance != null
}
/**
* 同步抓一帧并编码 JPEG。从 native 工作线程调用(调用方负责 attach JVM),
* 内部用 CountDownLatch 等系统回调。拿不到画面/超时/编码失败一律返回 null,
* native 侧据此回 SCREEN_PREVIEW_CAPTURE_FAILED。
*/
@JvmStatic
fun capture(maxWidth: Int, quality: Int): Shot? {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return null
val svc = ControlService.instance ?: return null
val latch = CountDownLatch(1)
val holder = arrayOfNulls<Bitmap>(1)
// 超时返回后回调仍可能到达(系统限流时回调会拖到几秒后)。等待方已经放弃,
// 那张整屏 ARGB_8888(1080x2400 约 10 MB)得有人回收。holder 与 abandoned
// 必须在同一把锁下读写:否则回调可能在 countDown 之后、等待方置标志之前
// 看到 false,把位图留在 holder 里,而那边已经超时返回,位图就永久泄漏。
val gate = Any()
val abandoned = AtomicBoolean(false)
// 回调直接在当前线程跑,省掉再起一个线程;Binder 线程回调也安全
val direct = Executor { it.run() }
try {
svc.takeScreenshot(Display.DEFAULT_DISPLAY, direct,
object : AccessibilityService.TakeScreenshotCallback {
override fun onSuccess(result: AccessibilityService.ScreenshotResult) {
val hw = result.hardwareBuffer
var bmp: Bitmap? = null
try {
// 硬件位图引用着 hw,必须先复制成软件位图再关
val hb = Bitmap.wrapHardwareBuffer(hw, result.colorSpace)
bmp = hb?.copy(Bitmap.Config.ARGB_8888, false)
} catch (e: Throwable) {
Log.e(TAG, "takeScreenshot convert failed: $e")
} finally {
hw.close()
}
synchronized(gate) {
holder[0] = bmp
latch.countDown()
// 等待方已超时返回:这张位图归回调自己回收
if (abandoned.get()) {
holder[0]?.recycle()
holder[0] = null
}
}
}
override fun onFailure(errorCode: Int) {
// ERROR_TAKE_SCREENSHOT_INTERVAL_TIME_SHORT 等:系统限流/未授权
Log.e(TAG, "takeScreenshot failed: errorCode=$errorCode")
latch.countDown()
}
})
} catch (e: Throwable) {
Log.e(TAG, "takeScreenshot threw: $e")
return null
}
if (!latch.await(CAPTURE_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
// 与回调抢同一把锁:回调若已把位图放进 holder 并检查过标志(那时还是 false),
// 这里负责回收;回调若还没进锁,它随后会看到标志并自己回收。
synchronized(gate) {
abandoned.set(true)
val late = holder[0]
holder[0] = null
late?.recycle()
}
Log.e(TAG, "takeScreenshot timeout")
return null
}
val src = holder[0] ?: return null
return try {
encodeJpeg(src, maxWidth, quality)
} finally {
src.recycle()
}
}
/** 等比缩放到 maxWidth 以内(maxWidth<=0 表示不缩放),再压成 JPEG */
private fun encodeJpeg(src: Bitmap, maxWidth: Int, quality: Int): Shot? {
val limit = if (maxWidth in 1..MAX_WIDTH) maxWidth else 0
val scaled = if (limit > 0 && src.width > limit) {
val h = (src.height.toLong() * limit / src.width).toInt().coerceAtLeast(1)
Bitmap.createScaledBitmap(src, limit, h, true)
} else src
try {
val out = ByteArrayOutputStream()
if (!scaled.compress(Bitmap.CompressFormat.JPEG, quality.coerceIn(10, 100), out)) return null
val data = out.toByteArray()
if (data.isEmpty()) return null
Log.i(TAG, "screenshot ${src.width}x${src.height} → ${scaled.width}x${scaled.height}, ${data.size} bytes")
return Shot(data, scaled.width, scaled.height)
} catch (e: Throwable) {
Log.e(TAG, "JPEG encode failed: $e")
return null
} finally {
if (scaled !== src) scaled.recycle()
}
}
}