feat(receiver): 系统签名免授权采集与 INJECT_EVENTS 输入注入
- 新增 util/Privileged.kt:判定系统应用 + 平台签名 + 共享 system uid,并缓存三种运行时能力 - 新增 input/InputExecutor 抽象,SystemInputExecutor 走 InputManager.injectInputEvent(反射), AccessibilityInputExecutor 走 dispatchGesture + performGlobalAction - InputInjector 改为运行时二选一的调度层,支持 down/move/up/cancel 完整拖拽序列与按键自动抬起 - 坐标契约:控制帧传画面像素,被控端按真实屏幕分辨率换算后注入 - ScreenCapturer 支持 projection 为空时用 DisplayManager 直建 VirtualDisplay(CAPTURE_VIDEO_OUTPUT) - MediaProjectionService 增加 privileged/directCapture 判定,直采模式用普通前台服务 - MainActivity/MirrorRequestActivity 免授权:按钮置灰、跳过授权弹窗与存储/通知权限申请 - AndroidManifest 声明 CAPTURE_VIDEO_OUTPUT / INJECT_EVENTS(ProtectedPermissions) - 直采模式无音频(AudioPlaybackCapture 依赖 MediaProjection)
This commit is contained in:
1 parent
d4cd497a44
commit
03a5853da7
11 files changed
+709
-91
No files matched your search
@@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
@@ -9,6 +10,15 @@
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
|
||||
<!-- 系统签名(aosp / zhanxun)专用:免 MediaProjection 直采 + 免无障碍注入输入。
|
||||
普通签名安装包拿不到这两条签名权限,声明本身无副作用。 -->
|
||||
<uses-permission
|
||||
android:name="android.permission.CAPTURE_VIDEO_OUTPUT"
|
||||
tools:ignore="ProtectedPermissions" />
|
||||
<uses-permission
|
||||
android:name="android.permission.INJECT_EVENTS"
|
||||
tools:ignore="ProtectedPermissions" />
|
||||
|
||||
<!-- 文件服务:浏览/读写 Android 目录所需的存储权限 -->
|
||||
<uses-permission
|
||||
android:name="android.permission.READ_EXTERNAL_STORAGE"
|
||||
|
||||
@@ -18,6 +18,7 @@ import android.widget.Toast
|
||||
import com.ttstd.lancast.receiver.discovery.HostBeacon
|
||||
import com.ttstd.lancast.receiver.file.StorageAccess
|
||||
import com.ttstd.lancast.receiver.session.PairingCode
|
||||
import com.ttstd.lancast.receiver.util.Privileged
|
||||
import java.net.NetworkInterface
|
||||
|
||||
class MainActivity : Activity() {
|
||||
@@ -46,6 +47,9 @@ class MainActivity : Activity() {
|
||||
private var hostOverride: String = ""
|
||||
private var authRequested = false
|
||||
|
||||
/** 系统签名应用:一切授权申请都跳过(屏幕录制直采、输入走 INJECT_EVENTS)。 */
|
||||
private val privileged by lazy { Privileged.isPrivileged(this) }
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
hostOverride = intent?.getStringExtra(EXTRA_HOST)?.trim().orEmpty()
|
||||
@@ -82,7 +86,8 @@ class MainActivity : Activity() {
|
||||
}
|
||||
|
||||
val authorize = Button(this).apply {
|
||||
text = "授权屏幕录制(仅待命,不投屏)"
|
||||
text = if (privileged) "系统签名:免授权投屏" else "授权屏幕录制(仅待命,不投屏)"
|
||||
isEnabled = !privileged
|
||||
setOnClickListener { startCaptureConsent() }
|
||||
}
|
||||
val startButton = Button(this).apply {
|
||||
@@ -130,7 +135,7 @@ class MainActivity : Activity() {
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
handler.post(refreshStatus)
|
||||
if (Prefs.autoGrant(this) && !MediaProjectionService.hasProjection && !authRequested) {
|
||||
if (!privileged && Prefs.autoGrant(this) && !MediaProjectionService.canCapture && !authRequested) {
|
||||
autoAuthorize()
|
||||
}
|
||||
}
|
||||
@@ -150,13 +155,18 @@ class MainActivity : Activity() {
|
||||
|
||||
/** 进入应用/开机后的自动授权:只申请屏幕录制凭证,不创建 VirtualDisplay。 */
|
||||
private fun autoAuthorize() {
|
||||
if (authRequested || MediaProjectionService.hasProjection) return
|
||||
// 系统签名应用用 DisplayManager 直采,根本不存在屏幕录制凭证,不用申请。
|
||||
if (privileged || authRequested || MediaProjectionService.canCapture) return
|
||||
authRequested = true
|
||||
startCaptureConsent()
|
||||
}
|
||||
|
||||
private fun startCaptureConsent() {
|
||||
if (MediaProjectionService.hasProjection) {
|
||||
if (privileged) {
|
||||
Toast.makeText(this, "系统签名应用免授权投屏", Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
if (MediaProjectionService.canCapture) {
|
||||
Toast.makeText(this, "已持有屏幕录制授权", Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
@@ -165,6 +175,16 @@ class MainActivity : Activity() {
|
||||
}
|
||||
|
||||
private fun requestStorageAccess() {
|
||||
if (privileged) {
|
||||
// 平台签名应用的 MANAGE_EXTERNAL_STORAGE 在安装时按签名授予,不需要手动申请。
|
||||
if (StorageAccess.canBrowseAll(this)) {
|
||||
Toast.makeText(this, "系统签名:已具备完整文件访问权限", Toast.LENGTH_SHORT).show()
|
||||
} else {
|
||||
Toast.makeText(this, "系统签名但未获存储权限,请检查系统签名/安装位置", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
refreshStatus
|
||||
return
|
||||
}
|
||||
if (StorageAccess.canBrowseAll(this)) {
|
||||
Toast.makeText(this, "已具备完整文件访问权限", Toast.LENGTH_SHORT).show()
|
||||
refreshStatus
|
||||
@@ -181,6 +201,8 @@ class MainActivity : Activity() {
|
||||
}
|
||||
|
||||
private fun requestNotificationPermission() {
|
||||
// 系统签名应用不弹任何运行时权限申请。
|
||||
if (privileged) return
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
|
||||
if (checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) return
|
||||
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST_NOTIFICATIONS)
|
||||
@@ -246,7 +268,14 @@ class MainActivity : Activity() {
|
||||
append("状态:待命(未投屏)")
|
||||
val host = MediaProjectionService.discoveredHost
|
||||
append(if (host.isNotEmpty()) " · 主控端 $host" else " · 等待主控端连接")
|
||||
append(if (MediaProjectionService.hasProjection) " · 已获屏幕授权" else " · 未授权屏幕录制")
|
||||
append(
|
||||
when {
|
||||
// 系统签名:不需要也没有屏幕录制凭证。
|
||||
MediaProjectionService.directCapture -> " · 系统签名免授权"
|
||||
MediaProjectionService.hasProjection -> " · 已获屏幕授权"
|
||||
else -> " · 未授权屏幕录制"
|
||||
},
|
||||
)
|
||||
}
|
||||
else -> "状态:未运行"
|
||||
}
|
||||
|
||||
+41
-9
@@ -21,6 +21,7 @@ import android.widget.Toast
|
||||
import com.ttstd.lancast.receiver.discovery.HostBeacon
|
||||
import com.ttstd.lancast.receiver.file.FileHttpServer
|
||||
import com.ttstd.lancast.receiver.protocol.MirrorAction
|
||||
import com.ttstd.lancast.receiver.util.Privileged
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
@@ -81,9 +82,22 @@ class MediaProjectionService : Service() {
|
||||
var projectionReady = false
|
||||
private set
|
||||
|
||||
/** 系统应用 + 平台签名:跳过所有授权申请。 */
|
||||
@Volatile
|
||||
var privileged = false
|
||||
private set
|
||||
|
||||
/** 系统签名且拿到 CAPTURE_VIDEO_OUTPUT:可用 DisplayManager 直采,免 MediaProjection。 */
|
||||
@Volatile
|
||||
var directCapture = false
|
||||
private set
|
||||
|
||||
/** 已持有可用的屏幕录制凭证(不代表正在投屏)。 */
|
||||
val hasProjection: Boolean get() = projectionReady
|
||||
|
||||
/** 当前是否具备开流条件:系统签名免授权,或已拿到屏幕录制凭证。 */
|
||||
val canCapture: Boolean get() = directCapture || projectionReady
|
||||
|
||||
val isStreaming: Boolean get() = state == State.STREAMING
|
||||
|
||||
/** 通过 UDP 信标自动发现的主控端地址(空串表示还没发现)。 */
|
||||
@@ -162,6 +176,12 @@ class MediaProjectionService : Service() {
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
// 系统签名应用免授权:判定结果缓存,后续所有权限分支都看这两个开关。
|
||||
privileged = Privileged.isPrivileged(this)
|
||||
directCapture = Privileged.canCaptureWithoutProjection(this)
|
||||
if (privileged) {
|
||||
Log.i(TAG, "系统签名应用:跳过授权申请,directCapture=$directCapture")
|
||||
}
|
||||
createNotificationChannels()
|
||||
}
|
||||
|
||||
@@ -274,8 +294,8 @@ class MediaProjectionService : Service() {
|
||||
session?.notifyMirror(MirrorAction.GRANTED)
|
||||
return
|
||||
}
|
||||
// 免确认模式下也要先有屏幕录制凭证,否则仍需要用户走一次授权。
|
||||
if (!Prefs.mirrorConfirm(this) && projectionReady) {
|
||||
// 免确认模式下也要先具备开流条件(系统签名直采或已授权的凭证)。
|
||||
if (!Prefs.mirrorConfirm(this) && canCapture) {
|
||||
beginMirroring()
|
||||
return
|
||||
}
|
||||
@@ -312,7 +332,7 @@ class MediaProjectionService : Service() {
|
||||
Log.i(TAG, "投屏请求被拒绝: $reason")
|
||||
}
|
||||
|
||||
/** 校验权限并开始投屏(用户已确认)。 */
|
||||
/** 校验权限并开始投屏(用户已确认,或系统签名免确认)。 */
|
||||
private fun beginMirroring() {
|
||||
ensureSession()
|
||||
// Android 14+ 要求 createVirtualDisplay 时存在 mediaProjection 类型的前台服务,
|
||||
@@ -320,7 +340,7 @@ class MediaProjectionService : Service() {
|
||||
ensureForeground()
|
||||
val current = session ?: return
|
||||
val active = projection
|
||||
if (active == null || !projectionReady) {
|
||||
if (active == null && !directCapture) {
|
||||
current.notifyMirror(MirrorAction.ERROR, "设备尚未授予屏幕录制权限")
|
||||
Toast.makeText(this, "尚未授权屏幕录制,请先完成授权", Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
@@ -332,7 +352,7 @@ class MediaProjectionService : Service() {
|
||||
if (started) {
|
||||
state = State.STREAMING
|
||||
current.notifyMirror(MirrorAction.GRANTED)
|
||||
Log.i(TAG, "已开始投屏")
|
||||
Log.i(TAG, "已开始投屏(${if (active == null) "系统签名直采" else "MediaProjection"})")
|
||||
} else {
|
||||
state = State.STANDBY
|
||||
current.notifyMirror(MirrorAction.ERROR, "屏幕采集启动失败")
|
||||
@@ -446,8 +466,11 @@ class MediaProjectionService : Service() {
|
||||
|
||||
private fun ensureForeground() {
|
||||
val notification = buildServiceNotification()
|
||||
// 系统签名直采没有 MediaProjection 凭证,按 mediaProjection 类型起前台服务可能被拒,
|
||||
// 先走普通前台服务;失败再退回带类型的方式。
|
||||
val needsProjectionType = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && !directCapture
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
if (needsProjectionType) {
|
||||
startForeground(
|
||||
NOTIFICATION_ID,
|
||||
notification,
|
||||
@@ -457,9 +480,18 @@ class MediaProjectionService : Service() {
|
||||
startForeground(NOTIFICATION_ID, notification)
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
Log.e(TAG, "startForeground(mediaProjection) 失败,降级为普通前台服务", error)
|
||||
runCatching { startForeground(NOTIFICATION_ID, notification) }
|
||||
.onFailure { Log.e(TAG, "startForeground 降级同样失败", it) }
|
||||
Log.e(TAG, "startForeground 失败,换一种类型重试", error)
|
||||
runCatching {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
startForeground(
|
||||
NOTIFICATION_ID,
|
||||
notification,
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION,
|
||||
)
|
||||
} else {
|
||||
startForeground(NOTIFICATION_ID, notification)
|
||||
}
|
||||
}.onFailure { Log.e(TAG, "startForeground 降级同样失败", it) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -69,7 +69,8 @@ class MirrorRequestActivity : Activity() {
|
||||
}
|
||||
|
||||
private fun onAllow() {
|
||||
if (MediaProjectionService.hasProjection) {
|
||||
// 系统签名直采没有也无需屏幕录制凭证,canCapture 已经涵盖这种情况。
|
||||
if (MediaProjectionService.canCapture) {
|
||||
MediaProjectionService.startMirroring(this)
|
||||
finishWith(true, null)
|
||||
return
|
||||
|
||||
@@ -129,10 +129,14 @@ class ReceiverSession(
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始投屏。必须在 [start] 之后、且持有有效的 MediaProjection 时调用。
|
||||
* 开始投屏。必须在 [start] 之后调用。
|
||||
*
|
||||
* [projection] 为 null 表示系统签名应用走 `DisplayManager` 直采(免授权);
|
||||
* 普通应用必须传有效的 MediaProjection 凭证。
|
||||
*
|
||||
* @return 是否成功建立采集链路。
|
||||
*/
|
||||
fun beginMirroring(projection: MediaProjection): Boolean {
|
||||
fun beginMirroring(projection: MediaProjection?): Boolean {
|
||||
if (!running) return false
|
||||
synchronized(captureLock) {
|
||||
if (mirroring) return true
|
||||
@@ -168,26 +172,33 @@ class ReceiverSession(
|
||||
val connected: Boolean get() = transport?.keyEstablished == true
|
||||
|
||||
private fun startCapture() {
|
||||
val current = projection ?: throw IllegalStateException("未持有屏幕录制授权")
|
||||
val size = currentScreenSize()
|
||||
captureWidth = size[0]
|
||||
captureHeight = size[1]
|
||||
captureDensity = currentDensity()
|
||||
// 主控端按画面坐标点击,注入要用真实屏幕坐标,这里把两者的比例登记给注入器。
|
||||
val screen = realScreenSize()
|
||||
injector.updateGeometry(captureWidth, captureHeight, screen[0], screen[1])
|
||||
|
||||
encoder.start(captureWidth, captureHeight, 30, bitrateMbps * 1_000_000, preferH265)
|
||||
val surface = encoder.inputSurface
|
||||
?: throw IllegalStateException("视频编码器未返回输入 Surface")
|
||||
capturer = ScreenCapturer(current, surface, captureDensity).also {
|
||||
// projection 为 null 时由 DisplayManager 直采(系统签名 + CAPTURE_VIDEO_OUTPUT)。
|
||||
capturer = ScreenCapturer(projection, displayManager, surface, captureDensity).also {
|
||||
it.start(captureWidth, captureHeight)
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
audio = AudioCapturer(current) { pcm ->
|
||||
val active = transport ?: return@AudioCapturer
|
||||
// 音频采集(AudioPlaybackCapture)强依赖 MediaProjection;免授权直采时只投画面。
|
||||
val active = projection
|
||||
if (active != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
audio = AudioCapturer(active) { pcm ->
|
||||
val transport = transport ?: return@AudioCapturer
|
||||
opusEncoder.encode(pcm).forEach { packet ->
|
||||
active.sendAudio(packet, SystemClock.elapsedRealtimeNanos() / 1000)
|
||||
transport.sendAudio(packet, SystemClock.elapsedRealtimeNanos() / 1000)
|
||||
}
|
||||
}.also { it.start() }
|
||||
} else if (active == null) {
|
||||
Log.i(TAG, "免授权直采模式:跳过音频采集(AudioPlaybackCapture 依赖 MediaProjection)")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,6 +298,8 @@ class ReceiverSession(
|
||||
running = false
|
||||
displayManager?.unregisterDisplayListener(displayListener)
|
||||
endMirroring()
|
||||
// 补发按键抬起 / 结束未完成手势,避免退出后屏幕上残留按下的手指。
|
||||
injector.release()
|
||||
clipboard.stop()
|
||||
announcer?.stop()
|
||||
nsdAdvertiser?.stop()
|
||||
@@ -310,6 +323,22 @@ class ReceiverSession(
|
||||
return fit(metrics.widthPixels, metrics.heightPixels)
|
||||
}
|
||||
|
||||
/** 真实屏幕尺寸(不裁剪、不取偶),只用于输入注入的坐标换算。 */
|
||||
private fun realScreenSize(): IntArray {
|
||||
val metrics = DisplayMetrics()
|
||||
val display = displayManager?.getDisplay(Display.DEFAULT_DISPLAY)
|
||||
if (display != null) {
|
||||
@Suppress("DEPRECATION")
|
||||
display.getRealMetrics(metrics)
|
||||
} else {
|
||||
metrics.setTo(context.resources.displayMetrics)
|
||||
}
|
||||
return intArrayOf(
|
||||
metrics.widthPixels.coerceAtLeast(1),
|
||||
metrics.heightPixels.coerceAtLeast(1),
|
||||
)
|
||||
}
|
||||
|
||||
private fun currentDensity(): Int {
|
||||
val display = displayManager?.getDisplay(Display.DEFAULT_DISPLAY)
|
||||
?: return context.resources.displayMetrics.densityDpi
|
||||
|
||||
+42
-11
@@ -5,24 +5,55 @@ import android.hardware.display.VirtualDisplay
|
||||
import android.media.projection.MediaProjection
|
||||
import android.view.Surface
|
||||
|
||||
/**
|
||||
* 屏幕采集:把默认屏幕镜像到一个 Surface(编码器的输入面)。
|
||||
*
|
||||
* 两条路径:
|
||||
* - 普通应用:持 MediaProjection 凭证,由它创建 VirtualDisplay(需要系统授权弹窗)。
|
||||
* - 系统签名应用:没有凭证也能用 `DisplayManager.createVirtualDisplay` +
|
||||
* `VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR` 直接镜像默认屏幕(依赖 CAPTURE_VIDEO_OUTPUT),
|
||||
* 因此不需要任何授权弹窗。
|
||||
*/
|
||||
class ScreenCapturer(
|
||||
private val projection: MediaProjection,
|
||||
private val projection: MediaProjection?,
|
||||
private val displayManager: DisplayManager?,
|
||||
private val surface: Surface,
|
||||
private val density: Int,
|
||||
) {
|
||||
private var virtualDisplay: VirtualDisplay? = null
|
||||
|
||||
fun start(width: Int, height: Int) {
|
||||
virtualDisplay = projection.createVirtualDisplay(
|
||||
"lancast-capture",
|
||||
width,
|
||||
height,
|
||||
density,
|
||||
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
|
||||
surface,
|
||||
null,
|
||||
null,
|
||||
)
|
||||
val active = projection
|
||||
virtualDisplay = if (active != null) {
|
||||
active.createVirtualDisplay(
|
||||
"lancast-capture",
|
||||
width,
|
||||
height,
|
||||
density,
|
||||
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
|
||||
surface,
|
||||
null,
|
||||
null,
|
||||
)
|
||||
} else {
|
||||
val manager = displayManager
|
||||
?: throw IllegalStateException("既没有屏幕录制授权,也没有 DisplayManager")
|
||||
// DisplayManager 的重载是 (name, w, h, dpi, surface, flags, ...),surface 在 flags 之前。
|
||||
manager.createVirtualDisplay(
|
||||
"lancast-capture",
|
||||
width,
|
||||
height,
|
||||
density,
|
||||
surface,
|
||||
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
|
||||
null,
|
||||
null,
|
||||
)
|
||||
}
|
||||
if (virtualDisplay == null) {
|
||||
// 没有 CAPTURE_VIDEO_OUTPUT 时系统会直接返回 null(部分 ROM 抛 SecurityException)。
|
||||
throw IllegalStateException("创建镜像 VirtualDisplay 失败(缺少 CAPTURE_VIDEO_OUTPUT?)")
|
||||
}
|
||||
}
|
||||
|
||||
fun resize(width: Int, height: Int) {
|
||||
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package com.ttstd.lancast.receiver.input
|
||||
|
||||
import android.accessibilityservice.AccessibilityService
|
||||
import android.accessibilityservice.GestureDescription
|
||||
import android.graphics.Path
|
||||
import android.os.Build
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import android.view.KeyEvent
|
||||
|
||||
/**
|
||||
* 普通应用的输入注入:走已启用的无障碍服务。
|
||||
*
|
||||
* 无障碍无法注入“逐帧”的触摸序列,所以按下/移动期间只记录路径,抬起时一次性
|
||||
* `dispatchGesture`;这同时天然支持单击、长按(路径不动但时长很长)与拖拽。
|
||||
* 按键只能模拟返回/主页/多任务等全局动作,普通字符键无能为力(返回 false)。
|
||||
*/
|
||||
class AccessibilityInputExecutor : InputExecutor {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AccessibilityInput"
|
||||
private const val MIN_TAP_MS = 40L
|
||||
}
|
||||
|
||||
override val name: String = "accessibility"
|
||||
|
||||
private var path: Path? = null
|
||||
private var downTime = 0L
|
||||
|
||||
private fun service(): LancastAccessibilityService? = LancastAccessibilityService.instance
|
||||
|
||||
override fun down(x: Int, y: Int) {
|
||||
path = Path().apply { moveTo(x.toFloat(), y.toFloat()) }
|
||||
downTime = SystemClock.uptimeMillis()
|
||||
}
|
||||
|
||||
override fun move(x: Int, y: Int) {
|
||||
path?.lineTo(x.toFloat(), y.toFloat())
|
||||
}
|
||||
|
||||
override fun up(x: Int, y: Int) {
|
||||
val current = path ?: return
|
||||
current.lineTo(x.toFloat(), y.toFloat())
|
||||
path = null
|
||||
val duration = (SystemClock.uptimeMillis() - downTime).coerceAtLeast(MIN_TAP_MS)
|
||||
dispatch(current, duration)
|
||||
downTime = 0L
|
||||
}
|
||||
|
||||
override fun cancel(x: Int, y: Int) {
|
||||
// 已发出的手势无法撤回,丢掉未提交的路径即可。
|
||||
path = null
|
||||
downTime = 0L
|
||||
}
|
||||
|
||||
override fun key(keyCode: Int, action: Int): Boolean {
|
||||
// 无障碍只有“执行一次”的语义:按下时执行全局动作,抬手忽略。
|
||||
if (action == 1) return true
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P && keyCode == KeyEvent.KEYCODE_POWER) {
|
||||
return false
|
||||
}
|
||||
val globalAction = when (keyCode) {
|
||||
KeyEvent.KEYCODE_HOME -> AccessibilityService.GLOBAL_ACTION_HOME
|
||||
KeyEvent.KEYCODE_BACK -> AccessibilityService.GLOBAL_ACTION_BACK
|
||||
KeyEvent.KEYCODE_APP_SWITCH -> AccessibilityService.GLOBAL_ACTION_RECENTS
|
||||
KeyEvent.KEYCODE_NOTIFICATION -> AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS
|
||||
KeyEvent.KEYCODE_POWER -> AccessibilityService.GLOBAL_ACTION_LOCK_SCREEN
|
||||
else -> return false
|
||||
}
|
||||
return service()?.performGlobalAction(globalAction) ?: false
|
||||
}
|
||||
|
||||
override fun scroll(x: Int, y: Int, deltaX: Int, deltaY: Int): Boolean {
|
||||
if (deltaX == 0 && deltaY == 0) return true
|
||||
// 滚轮映射成一次纵向滑动:内容上滚 = 手指向上滑。
|
||||
val path = Path().apply {
|
||||
moveTo(x.toFloat(), y.toFloat())
|
||||
lineTo((x + deltaX * 40).toFloat(), (y - deltaY * 120).toFloat())
|
||||
}
|
||||
return dispatch(path, 220L)
|
||||
}
|
||||
|
||||
override fun release() {
|
||||
path = null
|
||||
downTime = 0L
|
||||
}
|
||||
|
||||
private fun dispatch(path: Path, durationMs: Long): Boolean {
|
||||
val current = service()
|
||||
if (current == null) {
|
||||
Log.w(TAG, "无障碍服务未启用,无法模拟手势")
|
||||
return false
|
||||
}
|
||||
val gesture = GestureDescription.Builder()
|
||||
.addStroke(GestureDescription.StrokeDescription(path, 0, durationMs))
|
||||
.build()
|
||||
val dispatched = runCatching { current.dispatchGesture(gesture, null, null) }
|
||||
.getOrDefault(false)
|
||||
if (!dispatched) {
|
||||
Log.w(TAG, "dispatchGesture 被拒绝(服务未连接或屏幕已锁)")
|
||||
}
|
||||
return dispatched
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.ttstd.lancast.receiver.input
|
||||
|
||||
/**
|
||||
* 模拟输入的执行器抽象。
|
||||
*
|
||||
* 两类实现:
|
||||
* - [SystemInputExecutor]:系统签名应用,反射 `InputManager.injectInputEvent` 注入真实输入事件,
|
||||
* 支持完整按下/移动/抬起/取消与按键,不依赖无障碍;
|
||||
* - [AccessibilityInputExecutor]:普通应用,用 `AccessibilityService.dispatchGesture` 模拟手势,
|
||||
* 用 `performGlobalAction` 模拟返回/主页/多任务。
|
||||
*
|
||||
* 坐标一律是**真实屏幕像素**,由 [InputInjector] 统一换算,执行器不再关心缩放。
|
||||
*/
|
||||
interface InputExecutor {
|
||||
/** 日志里用的名字,便于排查当前走的是哪条链路。 */
|
||||
val name: String
|
||||
|
||||
/** 触摸按下。 */
|
||||
fun down(x: Int, y: Int)
|
||||
|
||||
/** 触摸移动(拖拽)。 */
|
||||
fun move(x: Int, y: Int)
|
||||
|
||||
/** 触摸抬起,抬手时才算一次完整点击/拖动。 */
|
||||
fun up(x: Int, y: Int)
|
||||
|
||||
/** 手势取消(窗口失焦、鼠标被抢等)。 */
|
||||
fun cancel(x: Int, y: Int)
|
||||
|
||||
/** 一次性点击。 */
|
||||
fun tap(x: Int, y: Int) {
|
||||
down(x, y)
|
||||
up(x, y)
|
||||
}
|
||||
|
||||
/**
|
||||
* 按键。
|
||||
* @param action 0=按下 1=抬起
|
||||
* @return 是否成功注入(无能力时返回 false,调用方据此降级/记日志)。
|
||||
*/
|
||||
fun key(keyCode: Int, action: Int): Boolean
|
||||
|
||||
/**
|
||||
* 滚轮。没有滚轮指针位置,坐标用屏幕中心兜底。
|
||||
* @return 是否成功注入。
|
||||
*/
|
||||
fun scroll(x: Int, y: Int, deltaX: Int, deltaY: Int): Boolean = false
|
||||
|
||||
/** 释放执行器持有的资源(如缓存的事件、未结束的手势)。 */
|
||||
fun release() = Unit
|
||||
}
|
||||
+158
-56
@@ -1,77 +1,179 @@
|
||||
package com.ttstd.lancast.receiver.input
|
||||
|
||||
import android.accessibilityservice.AccessibilityService
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import com.ttstd.lancast.receiver.protocol.ControlEvent
|
||||
import com.ttstd.lancast.receiver.protocol.ControlFrame
|
||||
import com.ttstd.lancast.receiver.util.Privileged
|
||||
|
||||
/**
|
||||
* 控制事件入口:把协议里的触摸/鼠标/按键/滚轮翻译成真实的屏幕输入。
|
||||
*
|
||||
* 具体怎么注入由 [InputExecutor] 决定:
|
||||
* - 系统签名应用 → [SystemInputExecutor](InputManager.injectInputEvent,无需无障碍);
|
||||
* - 普通应用 → [AccessibilityInputExecutor](AccessibilityService.dispatchGesture)。
|
||||
*
|
||||
* 坐标换算也在这里统一处理:主控端发来的是**画面像素**(编码分辨率),而注入需要
|
||||
* **真实屏幕像素**。长边被限制到 1920 时两者不同,必须按比例映射,否则点击会偏移。
|
||||
*/
|
||||
class InputInjector(private val context: Context) {
|
||||
private var touchStart: Pair<Int, Int>? = null
|
||||
|
||||
companion object {
|
||||
private const val TAG = "InputInjector"
|
||||
|
||||
/** 发送端只发「按下」的一次性按键时,自动补一个抬起,避免按键卡在按下状态。 */
|
||||
private const val KEY_AUTO_UP_MS = 120L
|
||||
}
|
||||
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val executor: InputExecutor? = selectExecutor(context)
|
||||
private val pendingKeyUp = HashMap<Int, Runnable>()
|
||||
|
||||
/** 编码画面尺寸(主控端坐标空间)。 */
|
||||
@Volatile
|
||||
private var frameWidth = 0
|
||||
|
||||
@Volatile
|
||||
private var frameHeight = 0
|
||||
|
||||
/** 真实屏幕尺寸(注入坐标空间)。 */
|
||||
@Volatile
|
||||
private var screenWidth = 0
|
||||
|
||||
@Volatile
|
||||
private var screenHeight = 0
|
||||
|
||||
/** 当前使用的注入方式,便于日志排查。 */
|
||||
val executorName: String get() = executor?.name ?: "none"
|
||||
|
||||
/**
|
||||
* 更新坐标换算参数。[frameWidth]/[frameHeight] 是编码分辨率,
|
||||
* [screenWidth]/[screenHeight] 是本机真实屏幕分辨率。
|
||||
*/
|
||||
fun updateGeometry(frameWidth: Int, frameHeight: Int, screenWidth: Int, screenHeight: Int) {
|
||||
if (this.frameWidth == frameWidth && this.frameHeight == frameHeight &&
|
||||
this.screenWidth == screenWidth && this.screenHeight == screenHeight
|
||||
) {
|
||||
return
|
||||
}
|
||||
this.frameWidth = frameWidth
|
||||
this.frameHeight = frameHeight
|
||||
this.screenWidth = screenWidth
|
||||
this.screenHeight = screenHeight
|
||||
Log.i(TAG, "坐标换算:画面 ${frameWidth}x$frameHeight -> 屏幕 ${screenWidth}x$screenHeight($executorName)")
|
||||
}
|
||||
|
||||
fun inject(frame: ControlFrame) {
|
||||
val target = executor
|
||||
if (target == null) {
|
||||
Log.w(TAG, "没有可用的输入注入方式,丢弃事件")
|
||||
return
|
||||
}
|
||||
when (val event = frame.event) {
|
||||
is ControlEvent.Touch -> injectTouch(event)
|
||||
is ControlEvent.Mouse -> injectMouse(event)
|
||||
is ControlEvent.Key -> injectKey(event)
|
||||
is ControlEvent.Wheel -> injectWheel(event)
|
||||
is ControlEvent.Clipboard -> injectText(event.text)
|
||||
is ControlEvent.Touch -> injectTouch(target, event)
|
||||
is ControlEvent.Mouse -> injectMouse(target, event)
|
||||
is ControlEvent.Key -> injectKey(target, event)
|
||||
is ControlEvent.Wheel -> injectWheel(target, event)
|
||||
// 远程文本注入需要输入法级权限,两条链路都不支持;主控端剪贴板同步仍可用。
|
||||
is ControlEvent.Clipboard -> Log.i(TAG, "忽略远程文本注入(${event.text.length} 字符)")
|
||||
is ControlEvent.Ping, is ControlEvent.Pong -> Unit
|
||||
// 投屏请求由 Service 处理,不参与输入注入。
|
||||
is ControlEvent.Mirror -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
private fun injectTouch(event: ControlEvent.Touch) {
|
||||
/** 会话结束时调用:补发按键抬起、结束未完成手势。 */
|
||||
fun release() {
|
||||
for ((keyCode, up) in pendingKeyUp.toMap()) {
|
||||
handler.removeCallbacks(up)
|
||||
executor?.key(keyCode, 1)
|
||||
}
|
||||
pendingKeyUp.clear()
|
||||
executor?.release()
|
||||
}
|
||||
|
||||
private fun injectTouch(target: InputExecutor, event: ControlEvent.Touch) {
|
||||
val x = screenX(event.x)
|
||||
val y = screenY(event.y)
|
||||
when (event.action) {
|
||||
0 -> {
|
||||
touchStart = event.x to event.y
|
||||
accessibility()?.tap(event.x, event.y) ?: shell("input", "tap", "${event.x}", "${event.y}")
|
||||
}
|
||||
2 -> {
|
||||
val start = touchStart
|
||||
if (start != null) {
|
||||
accessibility()?.swipe(start.first, start.second, event.x, event.y)
|
||||
?: shell("input", "swipe", "${start.first}", "${start.second}", "${event.x}", "${event.y}")
|
||||
}
|
||||
0 -> target.down(x, y)
|
||||
1 -> target.up(x, y)
|
||||
2 -> target.move(x, y)
|
||||
3 -> target.cancel(x, y)
|
||||
else -> Log.w(TAG, "未知触摸动作 ${event.action}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun injectMouse(target: InputExecutor, event: ControlEvent.Mouse) {
|
||||
// 协议暂未区分鼠标按键;按下即视为一次点击。
|
||||
if (event.action != 0) return
|
||||
target.tap(screenX(event.x), screenY(event.y))
|
||||
}
|
||||
|
||||
private fun injectKey(target: InputExecutor, event: ControlEvent.Key) {
|
||||
val keyCode = event.keycode
|
||||
if (keyCode <= 0) return
|
||||
if (event.action == 1) {
|
||||
pendingKeyUp.remove(keyCode)?.let(handler::removeCallbacks)
|
||||
target.key(keyCode, 1)
|
||||
return
|
||||
}
|
||||
// 同一次按键重复收到「按下」(长按重复)时不再叠加。
|
||||
if (pendingKeyUp.containsKey(keyCode)) return
|
||||
val up = Runnable {
|
||||
pendingKeyUp.remove(keyCode)
|
||||
target.key(keyCode, 1)
|
||||
}
|
||||
if (target.key(keyCode, 0)) {
|
||||
pendingKeyUp[keyCode] = up
|
||||
handler.postDelayed(up, KEY_AUTO_UP_MS)
|
||||
}
|
||||
}
|
||||
|
||||
private fun injectWheel(target: InputExecutor, event: ControlEvent.Wheel) {
|
||||
if (event.deltaX == 0 && event.deltaY == 0) return
|
||||
// 滚轮没有坐标,用屏幕中心兜底。
|
||||
val x = screenWidth / 2
|
||||
val y = screenHeight / 2
|
||||
target.scroll(x, y, event.deltaX, event.deltaY)
|
||||
}
|
||||
|
||||
private fun screenX(x: Int): Int {
|
||||
val width = screenWidth
|
||||
if (width <= 0) return x
|
||||
val frame = frameWidth
|
||||
val mapped = if (frame > 0 && frame != width) {
|
||||
((x.toLong() * width) / frame).toInt()
|
||||
} else {
|
||||
x
|
||||
}
|
||||
return mapped.coerceIn(0, width - 1)
|
||||
}
|
||||
|
||||
private fun screenY(y: Int): Int {
|
||||
val height = screenHeight
|
||||
if (height <= 0) return y
|
||||
val frame = frameHeight
|
||||
val mapped = if (frame > 0 && frame != height) {
|
||||
((y.toLong() * height) / frame).toInt()
|
||||
} else {
|
||||
y
|
||||
}
|
||||
return mapped.coerceIn(0, height - 1)
|
||||
}
|
||||
|
||||
private fun selectExecutor(context: Context): InputExecutor? {
|
||||
if (Privileged.canInjectWithoutAccessibility(context)) {
|
||||
val system = SystemInputExecutor()
|
||||
if (system.available) {
|
||||
Log.i(TAG, "输入注入:系统签名(InputManager.injectInputEvent)")
|
||||
return system
|
||||
}
|
||||
Log.w(TAG, "系统签名但 injectInputEvent 不可用,退回无障碍服务")
|
||||
}
|
||||
}
|
||||
|
||||
private fun injectMouse(event: ControlEvent.Mouse) {
|
||||
if (event.action == 0) {
|
||||
accessibility()?.tap(event.x, event.y) ?: shell("input", "tap", "${event.x}", "${event.y}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun injectKey(event: ControlEvent.Key) {
|
||||
when (event.keycode) {
|
||||
3 -> accessibility()?.systemAction(AccessibilityService.GLOBAL_ACTION_HOME)
|
||||
?: shell("input", "keyevent", "KEYCODE_HOME")
|
||||
4 -> accessibility()?.systemAction(AccessibilityService.GLOBAL_ACTION_BACK)
|
||||
?: shell("input", "keyevent", "KEYCODE_BACK")
|
||||
else -> shell("input", "keyevent", event.keycode.toString())
|
||||
}
|
||||
}
|
||||
|
||||
private fun injectWheel(event: ControlEvent.Wheel) {
|
||||
// AccessibilityService 不直接支持滚轮;映射为上下滑动。
|
||||
val service = accessibility()
|
||||
if (service != null) {
|
||||
service.swipe(720, 800, 720 + event.deltaX, 800 - event.deltaY * 60)
|
||||
}
|
||||
}
|
||||
|
||||
private fun injectText(text: String) {
|
||||
shell("input", "text", text.replace(" ", "%s"))
|
||||
}
|
||||
|
||||
private fun accessibility() = LancastAccessibilityService.instance
|
||||
|
||||
private fun shell(vararg command: String) {
|
||||
try {
|
||||
Runtime.getRuntime().exec(command)
|
||||
} catch (_: Exception) {
|
||||
// 普通应用无 shell 权限时静默降级到无障碍服务。
|
||||
}
|
||||
Log.i(TAG, "输入注入:无障碍服务(dispatchGesture)")
|
||||
return AccessibilityInputExecutor()
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
package com.ttstd.lancast.receiver.input
|
||||
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import android.view.InputDevice
|
||||
import android.view.InputEvent
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import java.lang.reflect.Method
|
||||
|
||||
/**
|
||||
* 系统签名应用的输入注入:反射 `android.hardware.input.InputManager#injectInputEvent`。
|
||||
*
|
||||
* 需要 `android.permission.INJECT_EVENTS`(signature|privileged),只有平台签名的系统应用能拿到,
|
||||
* 因此不需要无障碍服务,也能注入真实按键(包括文字输入框里的字符键)。
|
||||
*
|
||||
* 注意:hidden API 会随 Android 版本变化,反射失败时 [available] 为 false,
|
||||
* 上层([InputInjector])会自动退回无障碍执行器。
|
||||
*/
|
||||
class SystemInputExecutor : InputExecutor {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SystemInputExecutor"
|
||||
|
||||
/** InputManager.INJECT_INPUT_EVENT_MODE_ASYNC */
|
||||
private const val MODE_ASYNC = 0
|
||||
}
|
||||
|
||||
private val inputManager: Any?
|
||||
private val injectMethod: Method?
|
||||
|
||||
/** 当前手势按下的时刻,保证 DOWN/MOVE/UP 属于同一次手势。 */
|
||||
private var downTime = 0L
|
||||
private var lastX = 0
|
||||
private var lastY = 0
|
||||
|
||||
init {
|
||||
var manager: Any? = null
|
||||
var method: Method? = null
|
||||
try {
|
||||
val cls = Class.forName("android.hardware.input.InputManager")
|
||||
val instance = cls.getDeclaredMethod("getInstance")
|
||||
instance.isAccessible = true
|
||||
manager = instance.invoke(null)
|
||||
method = cls.getMethod("injectInputEvent", InputEvent::class.java, Int::class.javaPrimitiveType)
|
||||
} catch (error: Throwable) {
|
||||
Log.w(TAG, "InputManager.injectInputEvent 不可用", error)
|
||||
}
|
||||
inputManager = manager
|
||||
injectMethod = method
|
||||
}
|
||||
|
||||
override val name: String = "system-inject"
|
||||
|
||||
/** 反射是否可用(不可用时上层退回无障碍)。 */
|
||||
val available: Boolean get() = inputManager != null && injectMethod != null
|
||||
|
||||
override fun down(x: Int, y: Int) {
|
||||
downTime = SystemClock.uptimeMillis()
|
||||
lastX = x
|
||||
lastY = y
|
||||
injectMotion(MotionEvent.ACTION_DOWN, x, y)
|
||||
}
|
||||
|
||||
override fun move(x: Int, y: Int) {
|
||||
lastX = x
|
||||
lastY = y
|
||||
injectMotion(MotionEvent.ACTION_MOVE, x, y)
|
||||
}
|
||||
|
||||
override fun up(x: Int, y: Int) {
|
||||
lastX = x
|
||||
lastY = y
|
||||
injectMotion(MotionEvent.ACTION_UP, x, y)
|
||||
}
|
||||
|
||||
override fun cancel(x: Int, y: Int) {
|
||||
lastX = x
|
||||
lastY = y
|
||||
injectMotion(MotionEvent.ACTION_CANCEL, x, y)
|
||||
}
|
||||
|
||||
override fun key(keyCode: Int, action: Int): Boolean {
|
||||
val now = SystemClock.uptimeMillis()
|
||||
val keyAction = if (action == 1) KeyEvent.ACTION_UP else KeyEvent.ACTION_DOWN
|
||||
val event = KeyEvent(now, now, keyAction, keyCode, 0)
|
||||
// 显式声明来源为键盘:否则注入的按键会被系统/输入法丢弃,焦点在输入框时收不到字符。
|
||||
event.setSource(InputDevice.SOURCE_KEYBOARD)
|
||||
return inject(event)
|
||||
}
|
||||
override fun scroll(x: Int, y: Int, deltaX: Int, deltaY: Int): Boolean {
|
||||
if (deltaX == 0 && deltaY == 0) return true
|
||||
// MotionEvent 没有公开的 setAxisValue,直接用一次短拖拽模拟滚动,兼容性最好。
|
||||
val dx = deltaX * 40
|
||||
val dy = -deltaY * 120
|
||||
down(x, y)
|
||||
val steps = 6
|
||||
for (step in 1 until steps) {
|
||||
move(x + dx * step / steps, y + dy * step / steps)
|
||||
}
|
||||
up(x + dx, y + dy)
|
||||
return true
|
||||
}
|
||||
|
||||
override fun release() {
|
||||
// 手势还在进行时补一个 CANCEL,避免屏幕端残留按下的手指。
|
||||
if (downTime != 0L) {
|
||||
injectMotion(MotionEvent.ACTION_CANCEL, lastX, lastY)
|
||||
downTime = 0L
|
||||
}
|
||||
}
|
||||
|
||||
private fun injectMotion(action: Int, x: Int, y: Int) {
|
||||
val eventTime = SystemClock.uptimeMillis()
|
||||
val down = if (action == MotionEvent.ACTION_DOWN) eventTime else downTime
|
||||
val event = MotionEvent.obtain(down, eventTime, action, x.toFloat(), y.toFloat(), 0)
|
||||
event.setSource(InputDevice.SOURCE_TOUCHSCREEN)
|
||||
inject(event)
|
||||
// ASYNC 模式下系统已拷贝事件,本地实例可以回收(KeyEvent 不需要回收)。
|
||||
event.recycle()
|
||||
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
|
||||
downTime = 0L
|
||||
}
|
||||
}
|
||||
|
||||
private fun inject(event: InputEvent): Boolean {
|
||||
val manager = inputManager
|
||||
val method = injectMethod
|
||||
if (manager == null || method == null) {
|
||||
return false
|
||||
}
|
||||
return try {
|
||||
method.invoke(manager, event, MODE_ASYNC)
|
||||
true
|
||||
} catch (error: Throwable) {
|
||||
Log.w(TAG, "注入输入事件失败", error)
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.ttstd.lancast.receiver.util
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.ApplicationInfo
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Process
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
* 特权能力判定:安装在系统分区 **且** 平台签名(或共享系统 UID)时才算特权应用。
|
||||
*
|
||||
* 特权应用可以:
|
||||
* - 用 `CAPTURE_VIDEO_OUTPUT` 直接建 VirtualDisplay 镜像屏幕,跳过 MediaProjection 授权弹窗;
|
||||
* - 用 `INJECT_EVENTS` 通过 InputManager 注入输入事件,不依赖无障碍服务;
|
||||
* - 不申请通知/存储等运行时权限(平台签名应用在安装时已按签名授予)。
|
||||
*
|
||||
* 普通安装包(neutral)三条都不满足,仍走原来的授权弹窗 + 无障碍路径。
|
||||
*/
|
||||
object Privileged {
|
||||
private const val TAG = "Privileged"
|
||||
private const val PLATFORM_PACKAGE = "android"
|
||||
private const val SHARED_SYSTEM_UID = "android.uid.system"
|
||||
|
||||
const val PERMISSION_CAPTURE_VIDEO_OUTPUT = "android.permission.CAPTURE_VIDEO_OUTPUT"
|
||||
const val PERMISSION_INJECT_EVENTS = "android.permission.INJECT_EVENTS"
|
||||
|
||||
@Volatile
|
||||
private var cached: Boolean? = null
|
||||
|
||||
/** 是否安装在系统分区(含系统应用更新包)。 */
|
||||
fun isSystemApp(context: Context): Boolean = runCatching {
|
||||
val info = context.packageManager.getApplicationInfo(context.packageName, 0)
|
||||
(info.flags and ApplicationInfo.FLAG_SYSTEM) != 0 ||
|
||||
(info.flags and ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0
|
||||
}.getOrDefault(false)
|
||||
|
||||
/** 是否与系统核心包 `android` 同签名(即平台签名)。 */
|
||||
fun isSystemSignature(context: Context): Boolean = runCatching {
|
||||
context.packageManager.checkSignatures(context.packageName, PLATFORM_PACKAGE) ==
|
||||
PackageManager.SIGNATURE_MATCH
|
||||
}.getOrDefault(false)
|
||||
|
||||
/** 是否声明了 `android:sharedUserId="android.uid.system"`。 */
|
||||
fun isSharedSystemUid(context: Context): Boolean = runCatching {
|
||||
context.packageManager.getPackageInfo(context.packageName, 0).sharedUserId ==
|
||||
SHARED_SYSTEM_UID
|
||||
}.getOrDefault(false)
|
||||
|
||||
fun isSystemUid(): Boolean = runCatching { Process.myUid() == Process.SYSTEM_UID }
|
||||
.getOrDefault(false)
|
||||
|
||||
fun hasPermission(context: Context, permission: String): Boolean = runCatching {
|
||||
context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
|
||||
}.getOrDefault(false)
|
||||
|
||||
/**
|
||||
* 平台签名 + 系统身份(装在系统分区 / 共享系统 UID / 以 system uid 运行)才算特权。
|
||||
*
|
||||
* 只看平台签名不够稳妥,只看系统分区也会把普通 ROM 自带应用误判成特权;
|
||||
* 真正的能力仍以 [canCaptureWithoutProjection] / [canInjectWithoutAccessibility]
|
||||
* 里的权限检查为准,这里只做「值不值得去试」的门槛。
|
||||
*
|
||||
* 结果缓存:签名/安装位置在一次进程生命周期内不会变化,而 checkSignatures
|
||||
* 会走 PackageManager,别在每次点击里重复调用。
|
||||
*/
|
||||
fun isPrivileged(context: Context): Boolean {
|
||||
cached?.let { return it }
|
||||
val appContext = context.applicationContext
|
||||
val systemApp = isSystemApp(appContext)
|
||||
val sharedSystemUid = isSharedSystemUid(appContext)
|
||||
val platformSigned = isSystemSignature(appContext) || sharedSystemUid || isSystemUid()
|
||||
val value = platformSigned && (systemApp || sharedSystemUid || isSystemUid())
|
||||
cached = value
|
||||
Log.i(
|
||||
TAG,
|
||||
"systemApp=$systemApp platformSigned=$platformSigned " +
|
||||
"sharedSystemUid=$sharedSystemUid systemUid=${isSystemUid()} privileged=$value",
|
||||
)
|
||||
return value
|
||||
}
|
||||
|
||||
/** 能否免 MediaProjection 采集:特权应用且真的拿到了 CAPTURE_VIDEO_OUTPUT。 */
|
||||
fun canCaptureWithoutProjection(context: Context): Boolean =
|
||||
isPrivileged(context) && hasPermission(context, PERMISSION_CAPTURE_VIDEO_OUTPUT)
|
||||
|
||||
/** 能否用 InputManager 注入:特权应用且真的拿到了 INJECT_EVENTS。 */
|
||||
fun canInjectWithoutAccessibility(context: Context): Boolean =
|
||||
isPrivileged(context) && hasPermission(context, PERMISSION_INJECT_EVENTS)
|
||||
}
|
||||
Reference in new issue
Block a user