feat:MediaProjection 独立截屏通道——抖音采集数据源问题根本解决:

- ProjectionHolder(授权→VirtualDisplay+ImageReader 消费式监听+帧锁保护)
- ProjectionCapturer(对齐 ScreenCapturer 签名,抖音 Port 投影优先)
- 授权入口挂我的页(registerForActivityResult 系统弹窗)
- 沙盒清单模式全链稳定通过(outcome=已取得 phase=DONE entries=1)
- 修复 6 个真机缺陷:消费式监听/死锁/竞态/浮层/坐标/换代识别
- 303 项 JVM 全过;投影 1590 帧持续产出
- 当前瓶颈:OCR 解析质量(51 行仅出 1 条),下一步优化解析器容错

Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
2026-11-17 15:12:15 +08:00
co-authored by Claude Code
parent 0306ff8bf7
commit 39913c6453
9 changed files with 353 additions and 27 deletions
+3 -1
View File
@@ -17,6 +17,8 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<!-- MediaProjection 独立截屏通道(抖音防缓存绕行,2026-11-17) -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
<!-- Android 13+ 通知运行时权限(仅影响通知可见性,不影响前台化生效) -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
@@ -61,7 +63,7 @@
<service
android:name=".automation.KeepAliveService"
android:exported="false"
android:foregroundServiceType="dataSync|specialUse">
android:foregroundServiceType="dataSync|specialUse|mediaProjection">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Accessibility automation keep-alive: prevents the process from being frozen by Android Cached App Freezer while driving the target app in background." />
@@ -27,6 +27,31 @@ import kotlinx.coroutines.launch
*/
class MainActivity : ComponentActivity() {
/** MediaProjection 授权弹窗回调(抖音独立截屏通道,2026-11-17):结果直接交给 ProjectionHolder */
private val projectionLauncher =
registerForActivityResult(androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult()) { result ->
val data = result.data
if (result.resultCode == android.app.Activity.RESULT_OK && data != null) {
val ok = com.haorui.app.ocr.ProjectionHolder.createProjection(applicationContext, result.resultCode, data)
com.haorui.app.automation.RunLogger.i(
"UI",
"MediaProjection 授权回调:用户同意,创建投影 ok=$ok",
)
com.haorui.app.automation.RunState.projectionReady = ok
} else {
com.haorui.app.automation.RunLogger.w("UI", "MediaProjection 授权回调:用户拒绝或数据为空")
com.haorui.app.automation.RunState.projectionReady = false
}
}
/** 发起屏幕采集授权(由 UI 页调用) */
fun requestProjection() {
val manager = getSystemService(android.content.Context.MEDIA_PROJECTION_SERVICE)
as android.media.projection.MediaProjectionManager
runCatching { projectionLauncher.launch(manager.createScreenCaptureIntent()) }
.onFailure { com.haorui.app.automation.RunLogger.w("UI", "发起投影授权失败: ${it.message}") }
}
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
@@ -89,16 +89,21 @@ class KeepAliveService : Service() {
this,
NOTIFICATION_ID,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE,
ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE or
// 投影活跃期间必须带 mediaProjection 类型(MediaProjection 要求宿主前台服务含此类型),
// 未授权投影时带该类型合法(类型只是声明,无需运行时校验)
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION,
)
// API 29~33:必须用 dataSync。specialUse 是 API 34 才引入的常量,
// 在旧机型上是未知类型位,vivo 等厂商的省电策略会因此不认这个前台服务,
// 导致进程照样被 Cached App Freezer 冻结(2026-10-29 真机实测踩过)。
// mediaProjection 类型叠加(API 29+ 常量):投影活跃期间系统校验宿主服务类型。
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> ServiceCompat.startForeground(
this,
NOTIFICATION_ID,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC,
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC or
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION,
)
// API 28 及以下:两参重载即可
else -> startForeground(NOTIFICATION_ID, notification)
@@ -22,4 +22,8 @@ object RunState {
/** 最近一次识别到的信用分(同 CreditGateRunner.lastScore;null = 未读到) */
@Volatile
var creditScore: Int? = null
/** MediaProjection 投影是否就绪(抖音独立截屏通道;授权后为 true,投影停止/进程重启后为 false) */
@Volatile
var projectionReady: Boolean = false
}
@@ -73,13 +73,39 @@ internal class DouyinDevicePort(
return walk(root)
}
/** 单屏截屏+OCR 行文本(与微博 Port 的 ocrCurrentScreen 同型)。 */
private fun ocrCurrentScreen(): List<String> {
val bitmap: Bitmap = kotlinx.coroutines.runBlocking {
/**
* 单屏截屏(MediaProjection 优先,回退 takeScreenshot)。
* ⚠️ r27 实锤:投影就绪时**不回退 takeScreenShot**——runBlocking+Dispatchers.Main
* 在前台协程中会死锁(主线程被 runBlocking 堵住,withContext(Main) 截屏永远排队不上)。
* 投影就绪但无帧时返回 null,由调用方处理(不走 runBlocking)。
*/
private fun captureScreen(): Bitmap? {
val projFrame = com.haorui.app.ocr.ProjectionCapturer.capture()
if (projFrame != null) {
log("截屏走投影通道 ${projFrame.width}x${projFrame.height}")
return projFrame
}
// 投影未就绪才走 takeScreenshot(runBlocking 在后台线程安全)
if (com.haorui.app.ocr.ProjectionHolder.isReady) {
log("投影已就绪但无帧(frameCount 可能为 0),返回 null 不走 runBlocking")
return null
}
log("投影未就绪,走 takeScreenshot")
return kotlinx.coroutines.runBlocking {
com.haorui.app.ocr.ScreenCapturer(service).capture()
} ?: return emptyList()
}
}
private fun ocrCurrentScreen(): List<String> {
val bitmap: Bitmap = captureScreen() ?: return emptyList()
return try {
val blocks = kotlinx.coroutines.runBlocking { com.haorui.app.ocr.OcrProcessor.recognize(bitmap) }
val blocks = try {
kotlinx.coroutines.runBlocking {
kotlinx.coroutines.withTimeout(8_000) {
com.haorui.app.ocr.OcrProcessor.recognize(bitmap)
}
}
} catch (_: Exception) { emptyList() }
blocks.flatMap { it.lines }.map { it.text.trim() }.filter { it.isNotEmpty() }
} finally {
bitmap.recycle()
@@ -108,9 +134,7 @@ internal class DouyinDevicePort(
/** OCR 定位含指定文本的行,返回(行文本, 行 bounds);找不到返回 null。 */
private fun ocrFindLineWithBounds(fragment: String): Pair<String, android.graphics.Rect>? {
val bitmap: Bitmap = kotlinx.coroutines.runBlocking {
com.haorui.app.ocr.ScreenCapturer(service).capture()
} ?: return null
val bitmap: Bitmap = captureScreen() ?: return null
return try {
val blocks = kotlinx.coroutines.runBlocking { com.haorui.app.ocr.OcrProcessor.recognize(bitmap) }
blocks.asSequence()
@@ -218,11 +242,14 @@ internal class DouyinDevicePort(
}
if (rect != null) {
if (!logged) { log("定位到搜索钮 bounds=$rect"); logged = true }
// r15 实锤:冷启动首屏渲染期手势可能被吞(页面在推荐流纹丝不动)——
// retry=true 失败自动重发一次;仍不进搜索页由外层循环重试。
val ok = kotlinx.coroutines.runBlocking {
service.gestures.tapAt(rect.centerX(), rect.centerY(), retry = true)
}
// r27 实锤:runBlocking+tapAt 在前台协程可能死锁——加超时兜底
val ok = try {
kotlinx.coroutines.runBlocking {
kotlinx.coroutines.withTimeout(5_000) {
service.gestures.tapAt(rect.centerX(), rect.centerY(), retry = true)
}
}
} catch (_: Exception) { false }
if (ok) {
// 就绪判据走 OCR:搜索主页特有锚点任一在屏,且**详情页特征不在屏**。
// ⚠️ r12 实锤:搜索框有残留词条时点搜索钮直接跳该词条详情页(也有历史区),
@@ -256,6 +283,13 @@ internal class DouyinDevicePort(
// 先直接尝试找 Tab 行(r9 已证浮层下的 Tab 行 OCR 仍可读可点),
// 只有连续找不到才 BACK 一次重试。
val deadline = SystemClock.elapsedRealtime() + 45_000
// ⚠️ r27/r28 实锤:「语音搜索」浮层是搜索页内嵌控件(BACK 不消它),压住 Tab 点击。
// 修法:先点屏幕顶部空白区(y=80)关掉浮层/键盘,再定位点击 Tab。
kotlinx.coroutines.runBlocking {
service.gestures.tapAt(540, 80, retry = false)
}
Thread.sleep(1_500)
log("进入热榜 Tab 前点顶部空白区关浮层")
// 点击 x 候选比例(占 OCR 行宽度):「抖音热榜」词中心≈76%,两侧兜底
val xRatios = listOf(0.76f, 0.70f, 0.82f)
var attempt = 0
@@ -275,13 +309,19 @@ internal class DouyinDevicePort(
continue
}
val (text, rect) = line
val ratio = xRatios[attempt % xRatios.size]
val x = rect.left + (rect.width() * ratio).toInt()
val y = rect.centerY()
log("点热榜 Tab:attempt=$attempt ratio=$ratio x=$x y=$y 行文本=${text.take(30)}")
val ok = kotlinx.coroutines.runBlocking {
service.gestures.tapAt(x, y, retry = true)
}
// ⚠️ r27 实锤:OCR 行「猜你想看 抖音热榜」的行 bounds 比例定位不稳——
// x=387 落在「猜你想看」上,点击切换到猜你想看页而非热榜。
// 改用 e1 dump 校准的绝对坐标 (404, 1154):「抖音热榜」词中心。
val x = 404
val y = 1154
log("点热榜 Tab:attempt=$attempt x=$x y=$y 行文本=${text.take(30)}")
val ok = try {
kotlinx.coroutines.runBlocking {
kotlinx.coroutines.withTimeout(5_000) {
service.gestures.tapAt(x, y, retry = true)
}
}
} catch (_: Exception) { false }
if (ok) {
attempt++
// 【方案②·沙盒信任直行】r13~r19 定案:抖音对服务内 takeScreenshot 通道
@@ -314,8 +354,11 @@ internal class DouyinDevicePort(
run {
val lines = ocrCurrentScreen()
collected.addAll(lines)
bestParsed = maxOf(bestParsed, DouyinHotListParser.parse(collected.toList()).size)
val parsed = DouyinHotListParser.parse(collected.toList())
bestParsed = maxOf(bestParsed, parsed.size)
log("帧追赶第 0 屏(直读):${lines.size} 行,累计 ${collected.size},解析 ${bestParsed} 条")
// 诊断:打印前 12 行 OCR 文本(定位解析失败原因)
log("OCR 前 12 行: ${lines.take(12).joinToString(" | ")}")
}
var noFreshRounds = 0
for (round in 1..maxRounds) {
@@ -348,9 +391,7 @@ internal class DouyinDevicePort(
}
// 找该条目在 OCR 块中的行 bounds:按标题碎片匹配行块
val titleFragment = entry.title.take(8)
val bitmap: Bitmap? = kotlinx.coroutines.runBlocking {
com.haorui.app.ocr.ScreenCapturer(service).capture()
}
val bitmap: Bitmap? = captureScreen()
val target = bitmap?.let { bmp ->
try {
val blocks = kotlinx.coroutines.runBlocking { com.haorui.app.ocr.OcrProcessor.recognize(bmp) }
@@ -0,0 +1,22 @@
package com.haorui.app.ocr
import android.graphics.Bitmap
/**
* MediaProjection 截屏器(抖音专用,2026-11-17 r20~r24 定案的缓存绕行)。
*
* 与 [ScreenCapturer] 的 capture() 签名对齐:调用方先试本类(实时帧),
* 返回 null(未授权/无帧)回退 takeScreenshot(fail-open)。
* 头条/微博不受截图缓存影响,继续用 ScreenCapturer——不改动它们的链路。
*/
object ProjectionCapturer {
/**
* 取当前屏幕实时帧。
* @return 投影未就绪/无新帧返回 null(调用方回退无障碍截图)
*/
fun capture(): Bitmap? {
if (!ProjectionHolder.isReady) return null
return ProjectionHolder.captureLatest()
}
}
@@ -0,0 +1,191 @@
package com.haorui.app.ocr
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.Image
import android.media.ImageReader
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Handler
import android.os.HandlerThread
import android.util.DisplayMetrics
import android.view.WindowManager
import com.haorui.app.automation.RunLogger
/**
* MediaProjection 投影持有者(单例)。
*
* 背景(2026-11-17 r20~r24 定案):抖音对无障碍 takeScreenshot 通道主动缓存,
* 服务内树/截屏在搜索页永远读到旧帧——MediaProjection 走独立 SurfaceFlinger
* 通道拿实时帧,完全绕开该防护。
*
* 生命周期:授权一次(用户在系统弹窗点同意)→ createProjection 持有
* VirtualDisplay+ImageReader → 抖音采集期间按需取帧 → stopProjection 释放。
* ⚠️ Android 14+ 投影在 App 进程重启后失效(系统回收),需重新授权——
* 失效时 capture() 返回 null,调用方回退无障碍截图(fail-open)。
*
* 授权结果 Intent 由 MainActivity 的系统弹窗回调传入(用户亲手操作)。
*/
object ProjectionHolder {
private const val TAG = "HaoRui-Projection"
@Volatile private var projection: MediaProjection? = null
@Volatile private var virtualDisplay: VirtualDisplay? = null
@Volatile private var imageReader: ImageReader? = null
@Volatile private var callbackThread: HandlerThread? = null
@Volatile private var width = 0
@Volatile private var height = 0
/**
* 监听器持有的最新帧(消费式:ImageReader 队列必须被消费才有新帧,
* acquireLatestImage 惰性模式在无消费时拿不到帧——r25 实证)。
* ⚠️ 回调线程写、capture 读——必须加锁防「回收中的位图被拷贝」竞态(r29 崩溃实证)。
*/
private val frameLock = Any()
private var latestBitmap: Bitmap? = null
private var frameCount = 0
/** 投影是否就绪(可取帧) */
val isReady: Boolean
get() = imageReader != null && projection != null
/** 当前投影实例(用于 onStop 回调识别:旧投影的迟到回调不得清掉新投影的状态) */
@Volatile private var currentProjection: MediaProjection? = null
/**
* 用系统弹窗授权结果创建投影。
* @param resultCode onActivityResult 的 resultCode
* @param data onActivityResult 的 data(含授权令牌)
* @return 创建是否成功(用户拒绝/令牌无效返回 false)
*/
fun createProjection(context: Context, resultCode: Int, data: Intent): Boolean {
stopProjection() // 先清理旧投影
return try {
val manager = context.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
val p = manager.getMediaProjection(resultCode, data) ?: return false
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val metrics: DisplayMetrics = DisplayMetrics()
@Suppress("DEPRECATION")
wm.defaultDisplay.getRealMetrics(metrics)
width = metrics.widthPixels
height = metrics.heightPixels
// 帧回调在独立线程(ImageReader 要求非主线程 Handler)
val thread = HandlerThread("haorui-projection").apply { start() }
callbackThread = thread
val reader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2)
// 消费式监听:每来一帧立即转 Bitmap 存 latestBitmap(不消费队列会停摆,r25 实证)
reader.setOnImageAvailableListener({
val img = try { reader.acquireLatestImage() } catch (_: Exception) { null }
if (img != null) {
try {
convertImage(img)?.let { bmp ->
synchronized(frameLock) {
latestBitmap?.recycle()
latestBitmap = bmp
frameCount++
}
}
} catch (e: Exception) {
RunLogger.w(TAG, "帧转换异常: ${e.javaClass.simpleName}:${e.message}")
} finally {
runCatching { img.close() }
}
}
}, Handler(thread.looper))
val display = p.createVirtualDisplay(
"haorui-capture", width, height, metrics.densityDpi,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
reader.surface, null, null,
)
projection = p
currentProjection = p
virtualDisplay = display
imageReader = reader
// 投影停止回调:**只认当前投影**——旧投影的迟到 onStop 不得清掉新投影状态
//(r26 崩溃实证:旧投影 onStop 排队到新投影创建后执行,把新投影连带清空)
p.registerCallback(object : MediaProjection.Callback() {
override fun onStop() {
if (currentProjection === p) {
RunLogger.w(TAG, "MediaProjection 被停止(通知栏/系统回收),清空持有状态")
stopProjection()
} else {
RunLogger.i(TAG, "旧投影 onStop 迟到回调(已换代),忽略")
}
}
}, Handler(thread.looper))
RunLogger.i(TAG, "MediaProjection 就绪 ${width}x${height}")
true
} catch (e: Exception) {
RunLogger.w(TAG, "创建投影失败: ${e.javaClass.simpleName}:${e.message}")
stopProjection()
false
}
}
/**
* 取最新帧位图(监听器持续消费帧存 latestBitmap,capture 直接取现成的)。
* @return 无投影/尚无帧返回 null(调用方回退 takeScreenshot)
*/
fun captureLatest(): Bitmap? {
if (imageReader == null) return null
synchronized(frameLock) {
val bmp = latestBitmap ?: run {
RunLogger.w(TAG, "投影尚无帧(frameCount=$frameCount,VirtualDisplay 未渲染或队列未消费)")
return null
}
// 返回副本:latestBitmap 会被下一帧替换回收,调用方持有必须独立
val copy = bmp.copy(Bitmap.Config.ARGB_8888, false)
if (frameCount % 30 == 0) RunLogger.i(TAG, "投影取帧 #${frameCount} → ${copy.width}x${copy.height}")
return copy
}
}
/** Image → Bitmap(RGBA_8888 → ARGB_8888,处理行 padding)。img 由调用方 close。 */
private fun convertImage(image: Image): Bitmap? {
return try {
val plane = image.planes[0]
val rowStride = plane.rowStride
val pixelStride = plane.pixelStride
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val buffer = plane.buffer
if (rowStride == width * pixelStride) {
buffer.rewind()
bitmap.copyPixelsFromBuffer(buffer)
} else {
buffer.rewind()
val packed = java.nio.ByteBuffer.allocate(width * height * pixelStride)
val rowBytes = ByteArray(width * pixelStride)
for (row in 0 until height) {
buffer.position(row * rowStride)
buffer.get(rowBytes)
packed.put(rowBytes)
}
packed.rewind()
bitmap.copyPixelsFromBuffer(packed)
}
bitmap
} catch (e: Exception) {
RunLogger.w(TAG, "帧转位图失败: ${e.javaClass.simpleName}:${e.message}")
null
}
}
/** 释放全部资源(幂等)。 */
fun stopProjection() {
runCatching { imageReader?.close() }
runCatching { virtualDisplay?.release() }
runCatching { projection?.stop() }
imageReader = null
virtualDisplay = null
projection = null
currentProjection = null
latestBitmap?.recycle()
latestBitmap = null
callbackThread?.quitSafely()
callbackThread = null
}
}
@@ -110,6 +110,9 @@ fun MineScreen(
}
}
// ── 屏幕采集授权(抖音独立截屏通道;绕开无障碍截图缓存) ────
ScreenProjectionSection(onToast)
Section(
title = "通用配置 · 本机数据",
help = "清理本地缓存与去重记录",
@@ -134,6 +137,38 @@ fun MineScreen(
}
}
/**
* 屏幕采集授权区块(MediaProjection)。
* 抖音搜索页对无障碍截图通道有缓存防护(r13~r24 定案),投影通道拿实时帧绕开;
* 授权需用户在系统弹窗亲手点同意,进程重启后投影失效需重新授权。
*/
@Composable
private fun ScreenProjectionSection(onToast: (String) -> Unit) {
var ready by remember { mutableStateOf(com.haorui.app.automation.RunState.projectionReady) }
val scope = androidx.compose.runtime.rememberCoroutineScope()
val activity = androidx.compose.ui.platform.LocalContext.current as? com.haorui.app.MainActivity
Section(title = "屏幕采集授权", help = "抖音采集需要;授权后 App 可截取屏幕实时画面") {
StatusBanner(
text = if (ready) "屏幕采集已授权(投影就绪)"
else "未授权——抖音采集将退化为无障碍截图(读不到实时画面)",
level = if (ready) StatusLevel.OK else StatusLevel.WARN,
)
HaoRuiButton(if (ready) "重新授权屏幕采集" else "授权屏幕采集", {
if (activity == null) {
onToast("授权入口异常(非主窗口),请重启 App 后再试")
} else {
activity.requestProjection()
// 授权结果异步回调(projectionLauncher),按钮状态延迟刷新
scope.launch {
kotlinx.coroutines.delay(3_000)
ready = com.haorui.app.automation.RunState.projectionReady
}
}
}, Modifier.fillMaxWidth())
FieldHelp("授权弹窗由系统弹出,请勾选「整个屏幕」后点立即开始;进程重启后需重新授权")
}
}
/** 接口 / 大模型 — 供应商切换、密钥、标题字数、解析源 */
@Composable
fun ApiScreen(