feat(receiver): 授权开关与按需投屏,新增 LocalSend 风格文件服务

- 新增 Prefs 持久化 + BootReceiver 开机自启,主开关打开后进入应用/开机自动准备待命

- Service 拆为待命/投屏两阶段:待命只维持广播与控制通道,不建编码器、不创建 VirtualDisplay

- 新增控制帧 msgType=8 Mirror:主控端请求投屏,被控端弹窗确认并校验屏幕录制权限后才开流

- 新增 MirrorRequestActivity 透明确认页(通知兜底 + 30s 超时自动拒绝)

- 投屏按本机真实分辨率(不强制横屏)适配,旋转/分辨率变化自动重建采集

- 新增 LocalSend 风格 HTTP 文件服务(53317,含 info/browse/download/upload/mirror),目录做根路径越权校验,主界面提供存储与通知权限申请

- 控制通道 msgType=7 增加 op=list 目录浏览;Rust/Dart 同步支持投屏请求并加工具栏按钮
This commit is contained in:
tongtong committed 2026-11-27 09:07:31 +08:00
1 parent 3feddb3434
commit f87ef59d98
23 files changed
+1840 -274

No files matched your search

@@ -3,9 +3,26 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- 文件服务:浏览/读写 Android 目录所需的存储权限 -->
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<!-- 后台弹窗确认投屏请求(可选,授予后主控端请求时可直接弹框) -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<application
android:allowBackup="false"
@@ -22,12 +39,30 @@
</intent-filter>
</activity>
<!-- 投屏确认页:透明对话框,独立任务栈避免影响主界面 -->
<activity
android:name=".MirrorRequestActivity"
android:excludeFromRecents="true"
android:exported="false"
android:taskAffinity="com.ttstd.lancast.receiver.request"
android:theme="@style/Theme.Lancast.Request" />
<service
android:name=".MediaProjectionService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="mediaProjection" />
<receiver
android:name=".BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service
android:name=".input.LancastAccessibilityService"
android:exported="false"
@@ -0,0 +1,47 @@
package com.ttstd.lancast.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
/**
* 开机自启。
*
* 主开关打开时,开机后把服务拉起来待命并尽量拉起界面完成屏幕录制授权。
*
* 注意:Android 10+ 限制后台启动 Activity,Android 14+ 还限制从 BOOT_COMPLETED 启动
* `mediaProjection` 类型前台服务,所以这里每一步都做失败兜底 —— 被系统拦截时用户下次打开
* 应用仍会自动进入待命([MainActivity.onCreate] 里的 autoGrant 分支)。
*/
class BootReceiver : BroadcastReceiver() {
companion object {
private const val TAG = "BootReceiver"
private const val ACTION_QUICKBOOT = "android.intent.action.QUICKBOOT_POWERON"
}
override fun onReceive(context: Context, intent: Intent?) {
val action = intent?.action ?: return
if (action != Intent.ACTION_BOOT_COMPLETED && action != ACTION_QUICKBOOT) return
if (!Prefs.autoGrant(context)) {
Log.i(TAG, "开机自启已关闭,跳过")
return
}
Log.i(TAG, "开机自启:尝试进入待命")
// 先尝试拉起界面(系统签名变体或已授予后台弹出权限时可用),同时拉起待命服务。
try {
context.startActivity(
Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
} catch (error: Exception) {
Log.w(TAG, "开机拉起界面被系统拦截: ${error.message}")
}
try {
MediaProjectionService.start(context)
} catch (error: Exception) {
Log.w(TAG, "开机启动待命服务失败: ${error.message}")
}
}
}
@@ -1,22 +1,31 @@
package com.ttstd.lancast.receiver
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Button
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.Switch
import android.widget.TextView
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 java.net.NetworkInterface
class MainActivity : Activity() {
companion object {
private const val REQUEST_CAPTURE = 1001
private const val REQUEST_STORAGE = 1002
private const val REQUEST_NOTIFICATIONS = 1003
/**
* 调试用:`adb shell am start -n com.ttstd.lancast.receiver/.MainActivity -e host 10.0.2.2`
@@ -28,40 +37,188 @@ class MainActivity : Activity() {
private lateinit var status: TextView
private lateinit var endpoint: TextView
private lateinit var pairing: TextView
private lateinit var fileInfo: TextView
private lateinit var storageInfo: TextView
private lateinit var autoSwitch: Switch
private lateinit var confirmSwitch: Switch
private val handler = Handler(Looper.getMainLooper())
private var hostOverride: String = ""
private var authRequested = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
hostOverride = intent?.getStringExtra(EXTRA_HOST)?.trim().orEmpty()
status = TextView(this).apply {
textSize = 18f
text = "状态:未开始"
}
endpoint = TextView(this).apply {
textSize = 13f
text = "正在获取本机地址…"
}
pairing = TextView(this).apply {
textSize = 13f
text = "配对码:生成中..."
}
val start = Button(this).apply { text = "授权并开始投屏" }
val stop = Button(this).apply { text = "停止" }
status = TextView(this).apply { textSize = 18f }
endpoint = TextView(this).apply { textSize = 13f }
pairing = TextView(this).apply { textSize = 13f }
fileInfo = TextView(this).apply { textSize = 13f }
storageInfo = TextView(this).apply { textSize = 12f }
setContentView(LinearLayout(this).apply {
autoSwitch = Switch(this).apply {
text = "允许远控(开机/进入应用自动准备)"
textSize = 14f
isChecked = Prefs.autoGrant(this@MainActivity)
setOnCheckedChangeListener { _, checked ->
Prefs.setAutoGrant(this@MainActivity, checked)
if (checked) {
startStandby()
autoAuthorize()
} else {
MediaProjectionService.stop(this@MainActivity)
}
refreshStatus
}
}
confirmSwitch = Switch(this).apply {
text = "主控端请求投屏时弹窗确认"
textSize = 14f
isChecked = Prefs.mirrorConfirm(this@MainActivity)
setOnCheckedChangeListener { _, checked ->
Prefs.setMirrorConfirm(this@MainActivity, checked)
}
}
val authorize = Button(this).apply {
text = "授权屏幕录制(仅待命,不投屏)"
setOnClickListener { startCaptureConsent() }
}
val startButton = Button(this).apply {
text = "启动待命服务"
setOnClickListener { startStandby() }
}
val storageButton = Button(this).apply {
text = "授予文件访问权限"
setOnClickListener { requestStorageAccess() }
}
val stop = Button(this).apply {
text = "停止"
setOnClickListener {
MediaProjectionService.stop(this@MainActivity)
status.text = "状态:已停止"
}
}
val content = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(48, 64, 48, 48)
setPadding(48, 64, 48, 64)
addView(status)
addView(endpoint)
addView(pairing)
addView(start)
addView(autoSwitch)
addView(confirmSwitch)
addView(authorize)
addView(startButton)
addView(storageInfo)
addView(storageButton)
addView(fileInfo)
addView(stop)
})
}
setContentView(ScrollView(this).apply { addView(content) })
requestNotificationPermission()
// 开关已打开时,进入应用即自动准备(服务待命 + 预授权屏幕录制)。
if (Prefs.autoGrant(this)) {
startStandby()
}
refreshLocalInfo()
}
override fun onResume() {
super.onResume()
handler.post(refreshStatus)
if (Prefs.autoGrant(this) && !MediaProjectionService.hasProjection && !authRequested) {
autoAuthorize()
}
}
override fun onPause() {
handler.removeCallbacks(refreshStatus)
super.onPause()
}
// ------------------------------------------------------------------ 动作
private fun startStandby() {
MediaProjectionService.start(this, hostOverride, "")
status.text = "状态:正在进入待命…"
handler.postDelayed({ refreshStatus }, 300)
}
/** 进入应用/开机后的自动授权:只申请屏幕录制凭证,不创建 VirtualDisplay。 */
private fun autoAuthorize() {
if (authRequested || MediaProjectionService.hasProjection) return
authRequested = true
startCaptureConsent()
}
private fun startCaptureConsent() {
if (MediaProjectionService.hasProjection) {
Toast.makeText(this, "已持有屏幕录制授权", Toast.LENGTH_SHORT).show()
return
}
val manager = getSystemService(MediaProjectionManager::class.java)
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_CAPTURE)
}
private fun requestStorageAccess() {
if (StorageAccess.canBrowseAll(this)) {
Toast.makeText(this, "已具备完整文件访问权限", Toast.LENGTH_SHORT).show()
refreshStatus
return
}
val settings = StorageAccess.allFilesSettingsIntent(this)
if (settings != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Toast.makeText(this, "请在设置中允许「所有文件访问」", Toast.LENGTH_LONG).show()
runCatching { startActivity(settings) }
.onFailure { requestPermissions(StorageAccess.runtimePermissions(), REQUEST_STORAGE) }
} else {
requestPermissions(StorageAccess.runtimePermissions(), REQUEST_STORAGE)
}
}
private fun requestNotificationPermission() {
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)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode != REQUEST_CAPTURE) return
if (resultCode == RESULT_OK && data != null) {
// 只把凭证交给服务持有,不触发投屏。
MediaProjectionService.attachProjection(this, resultCode, data, mirrorAfter = false)
Toast.makeText(this, "已授权,服务保持待命(未投屏)", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "未授权屏幕录制,主控端请求时将再次询问", Toast.LENGTH_SHORT).show()
}
refreshStatus
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray,
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_STORAGE || requestCode == REQUEST_NOTIFICATIONS) {
refreshStatus
}
}
// ------------------------------------------------------------------ 状态
private fun refreshLocalInfo() {
Thread {
val ip = try { localIp() } catch (_: Exception) { "" }
val ip = try {
localIp()
} catch (_: Exception) {
""
}
val endpointText = if (ip.isEmpty()) {
"无法获取本机 IP,请检查网络"
} else {
@@ -77,55 +234,41 @@ class MainActivity : Activity() {
pairing.text = pairingText
}
}.start()
start.setOnClickListener {
// 系统同一时刻只允许一路 MediaProjection:会话进行中再次授权会让正在采集的
// 那一路失效(non-current MediaProjection),必须等停止后再重新授权。
if (MediaProjectionService.isRunning) {
Toast.makeText(this, "投屏已在进行中,请先点「停止」", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
val manager = getSystemService(MediaProjectionManager::class.java)
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_CAPTURE)
}
stop.setOnClickListener {
MediaProjectionService.stop(this)
status.text = "状态:已停止"
}
}
override fun onResume() {
super.onResume()
handler.post(refreshStatus)
}
override fun onPause() {
handler.removeCallbacks(refreshStatus)
super.onPause()
}
/** 采集过程中持续刷新「等待主控端 / 已发现主控端」。 */
/** 采集过程中持续刷新状态、文件服务地址与权限提示。 */
private val refreshStatus = object : Runnable {
override fun run() {
val state = MediaProjectionService.state
status.text = when {
hostOverride.isNotEmpty() -> "状态:已指定主控端 $hostOverride"
!MediaProjectionService.isRunning -> "状态:未开始"
MediaProjectionService.discoveredHost.isNotEmpty() ->
"状态:采集中 · 已发现主控端 ${MediaProjectionService.discoveredHost}"
else -> "状态:采集中 · 等待主控端连接(无需填写 IP)"
state == MediaProjectionService.State.STREAMING -> "状态:投屏中"
state == MediaProjectionService.State.STANDBY -> buildString {
append("状态:待命(未投屏)")
val host = MediaProjectionService.discoveredHost
append(if (host.isNotEmpty()) " · 主控端 $host" else " · 等待主控端连接")
append(if (MediaProjectionService.hasProjection) " · 已获屏幕授权" else " · 未授权屏幕录制")
}
else -> "状态:未运行"
}
endpoint.text = if (hostOverride.isNotEmpty()) {
"已指定主控端:$hostOverride"
} else {
endpoint.text
}
val port = MediaProjectionService.filePort
val ip = runCatching { localIp() }.getOrDefault("")
fileInfo.text = when {
port <= 0 -> "文件服务:未启动(下方可手动启动待命服务)"
ip.isEmpty() -> "文件服务端口:$port"
else -> "文件服务:http://$ip:$port\n令牌:${Prefs.fileToken(this@MainActivity)}"
}
storageInfo.text = "文件访问:${StorageAccess.summary(this@MainActivity)}"
handler.postDelayed(this, 1000)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode != REQUEST_CAPTURE || resultCode != RESULT_OK || data == null) return
// host 留空即走 UDP 信标自动发现;信令服务器未配置时传空串。
MediaProjectionService.start(this, resultCode, data, hostOverride, "")
status.text = "状态:连接中..."
}
private fun localIp(): String = NetworkInterface.getNetworkInterfaces().toList()
.flatMap { it.inetAddresses.toList() }
.firstOrNull { !it.isLoopbackAddress && it is java.net.Inet4Address }
@@ -3,6 +3,7 @@ package com.ttstd.lancast.receiver
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
@@ -13,82 +14,169 @@ import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import android.view.Display
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 java.util.UUID
/**
* 常驻前台服务。分两个阶段:
*
* - **待命(STANDBY)**:只广播设备信息、维持控制通道、提供文件服务;**不投屏**,不占用编码器。
* - **投屏(STREAMING)**:收到主控端 [MirrorAction.REQUEST] 且用户确认、权限校验通过后,
* 才建立编码器与 VirtualDisplay 开始推流。
*
* 屏幕录制授权(MediaProjection)只在需要投屏时才真正使用;即使提前拿到凭证也不会创建
* VirtualDisplay,因此「授权」不等于「投屏」。
*/
class MediaProjectionService : Service() {
enum class State { IDLE, STANDBY, STREAMING }
companion object {
private const val TAG = "MediaProjectionService"
private const val CHANNEL_ID = "media_projection_service_channel"
private const val CHANNEL_SERVICE = "lancast_service_channel"
private const val CHANNEL_REQUEST = "lancast_request_channel"
private const val NOTIFICATION_ID = 1001
private const val REQUEST_NOTIFICATION_ID = 1002
private const val REQUEST_TIMEOUT_MS = 30_000L
const val ACTION_START = "com.ttstd.lancast.receiver.action.START"
const val ACTION_STOP = "com.ttstd.lancast.receiver.action.STOP"
const val ACTION_ATTACH_PROJECTION = "com.ttstd.lancast.receiver.action.ATTACH_PROJECTION"
const val ACTION_MIRROR_START = "com.ttstd.lancast.receiver.action.MIRROR_START"
const val ACTION_MIRROR_DENY = "com.ttstd.lancast.receiver.action.MIRROR_DENY"
const val ACTION_MIRROR_STOP = "com.ttstd.lancast.receiver.action.MIRROR_STOP"
const val EXTRA_RESULT_CODE = "extra_result_code"
const val EXTRA_DATA = "extra_data"
const val EXTRA_HOST = "extra_host"
const val EXTRA_SIGNALING_URL = "extra_signaling_url"
const val EXTRA_MIRROR_AFTER = "extra_mirror_after"
@Volatile
var state: State = State.IDLE
private set
/** 服务是否在运行(待命或投屏)。 */
@Volatile
var isRunning = false
private set
/** 文件服务实际监听端口(0 表示未启动)。 */
@Volatile
var filePort = 0
private set
/** 是否有待确认的投屏请求。 */
@Volatile
var pendingRequest = false
private set
@Volatile
var projectionReady = false
private set
/** 已持有可用的屏幕录制凭证(不代表正在投屏)。 */
val hasProjection: Boolean get() = projectionReady
val isStreaming: Boolean get() = state == State.STREAMING
/** 通过 UDP 信标自动发现的主控端地址(空串表示还没发现)。 */
val discoveredHost: String
get() = com.ttstd.lancast.receiver.discovery.HostBeacon.lastHost
fun start(context: Context, resultCode: Int, data: Intent, host: String, signalingUrl: String) {
/** 启动待命服务(不需要屏幕录制授权)。 */
fun start(context: Context, host: String = "", signalingUrl: String = "") {
val intent = Intent(context, MediaProjectionService::class.java).apply {
action = ACTION_START
putExtra(EXTRA_RESULT_CODE, resultCode)
putExtra(EXTRA_DATA, data)
putExtra(EXTRA_HOST, host)
putExtra(EXTRA_SIGNALING_URL, signalingUrl)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
} else {
context.startService(intent)
}
context.startForegroundService(intent)
}
fun stop(context: Context) {
val intent = Intent(context, MediaProjectionService::class.java).apply {
context.startForegroundService(Intent(context, MediaProjectionService::class.java).apply {
action = ACTION_STOP
})
}
/** 把屏幕录制授权凭证交给服务;[mirrorAfter] 为 true 时立即开始投屏。 */
fun attachProjection(context: Context, resultCode: Int, data: Intent, mirrorAfter: Boolean) {
val intent = Intent(context, MediaProjectionService::class.java).apply {
action = ACTION_ATTACH_PROJECTION
putExtra(EXTRA_RESULT_CODE, resultCode)
putExtra(EXTRA_DATA, data)
putExtra(EXTRA_MIRROR_AFTER, mirrorAfter)
}
context.startService(intent)
context.startForegroundService(intent)
}
fun startMirroring(context: Context) = sendAction(context, ACTION_MIRROR_START)
fun denyMirroring(context: Context) = sendAction(context, ACTION_MIRROR_DENY)
fun stopMirroring(context: Context) = sendAction(context, ACTION_MIRROR_STOP)
private fun sendAction(context: Context, action: String) {
context.startForegroundService(
Intent(context, MediaProjectionService::class.java).setAction(action),
)
}
}
private var session: ReceiverSession? = null
private var beacon: com.ttstd.lancast.receiver.discovery.HostBeacon? = null
private var beacon: HostBeacon? = null
private var fileServer: FileHttpServer? = null
/** 当前投影实例;必须持有引用,销毁时显式 stop(),否则会残留为「当前投影」。 */
private var projection: MediaProjection? = null
private var projectionCallback: MediaProjection.Callback? = null
/** 保护 [session] / [projection] / [generation] / [starting] 的状态锁。 */
private val stateLock = Any()
private var hostOverride = ""
private var signalingUrl = ""
/**
* 会话世代号,每次启动或销毁时递增。后台启动线程持旧世代号时不再操作投影,
* 避免上一路 MediaProjection 已被新一路顶掉后仍去 createVirtualDisplay。
*/
private var generation = 0
private val handler = Handler(Looper.getMainLooper())
private val requestTimeout = Runnable { denyPending("确认超时") }
/** 正在创建投影 / 虚拟显示(尚未成功也未失败)。用于拦截重复启动请求。 */
private var starting = false
/** 采集链路建立/销毁较重(MediaCodec + VirtualDisplay),放到单线程串行执行。 */
private var worker = java.util.concurrent.Executors.newSingleThreadExecutor()
private fun execWorker(task: () -> Unit) {
try {
worker.execute(task)
} catch (_: Exception) {
// 线程池在上一轮 stop 时已关闭(服务实例被复用),重建一个。
worker = java.util.concurrent.Executors.newSingleThreadExecutor()
runCatching { worker.execute(task) }
}
}
private val notificationManager by lazy {
getSystemService(NotificationManager::class.java)
}
override fun onCreate() {
super.onCreate()
createNotificationChannel()
createNotificationChannels()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
ensureForeground()
when (intent?.action) {
ACTION_START -> {
null, ACTION_START -> {
if (intent != null) {
hostOverride = intent.getStringExtra(EXTRA_HOST) ?: hostOverride
signalingUrl = intent.getStringExtra(EXTRA_SIGNALING_URL) ?: signalingUrl
}
ensureSession()
}
ACTION_ATTACH_PROJECTION -> {
val resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, 0)
val data: Intent? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
intent.getParcelableExtra(EXTRA_DATA, Intent::class.java)
@@ -96,181 +184,253 @@ class MediaProjectionService : Service() {
@Suppress("DEPRECATION")
intent.getParcelableExtra(EXTRA_DATA)
}
val host = intent.getStringExtra(EXTRA_HOST) ?: ""
val signalingUrl = intent.getStringExtra(EXTRA_SIGNALING_URL) ?: ""
val mirrorAfter = intent.getBooleanExtra(EXTRA_MIRROR_AFTER, false)
if (resultCode != 0 && data != null) {
startForegroundServiceWithNotification()
startProjectionSession(resultCode, data, host, signalingUrl)
attachProjection(resultCode, data, mirrorAfter)
} else {
stopSelf()
session?.notifyMirror(MirrorAction.ERROR, "屏幕录制授权失败")
}
}
ACTION_MIRROR_START -> beginMirroring()
ACTION_MIRROR_DENY -> denyPending("用户拒绝")
ACTION_MIRROR_STOP -> endMirroring(reply = true)
ACTION_STOP -> {
stopProjectionSession()
teardown()
stopSelf()
}
else -> ensureSession()
}
return START_NOT_STICKY
}
private fun startForegroundServiceWithNotification() {
val notification = createNotification()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(
NOTIFICATION_ID,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
)
} else {
startForeground(NOTIFICATION_ID, notification)
// ------------------------------------------------------------------ 会话
/** 待命:建会话、广播、文件服务,全程不投屏。 */
private fun ensureSession() {
if (session != null) return
val created = ReceiverSession(this, hostOverride, signalingUrl, "")
// 请求来自控制通道读线程,统一切回主线程处理。
created.onMirrorRequest = { action, message ->
handler.post { handleMirrorAction(action, message) }
}
created.onStreamingLost = {
projectionReady = false
state = State.STANDBY
updateNotification()
}
session = created
created.start()
startBeacon()
startFileServer()
state = State.STANDBY
isRunning = true
updateNotification()
Log.i(TAG, "服务进入待命状态")
}
private fun startBeacon() {
if (beacon != null) return
HostBeacon.resetHost()
val metrics = realMetrics()
beacon = HostBeacon(
HostBeacon.Offer(
id = UUID.randomUUID().toString(),
name = "Android Receiver",
model = Build.MODEL ?: "Android",
resolution = "${metrics.widthPixels}x${metrics.heightPixels}",
),
).also { it.start() }
}
private fun startFileServer() {
if (fileServer != null) return
if (!Prefs.fileServiceEnabled(this)) return
val server = FileHttpServer(
context = this,
tokenProvider = { Prefs.fileToken(this) },
onMirrorRequest = { requestConfirmation() },
)
val port = server.start()
if (port > 0) {
fileServer = server
filePort = port
}
}
private fun startProjectionSession(resultCode: Int, data: Intent, host: String, signalingUrl: String) {
val gen = synchronized(stateLock) {
// 系统同一时刻只允许一路 MediaProjection 处于活动状态:再调一次 getMediaProjection
// 会立刻让上一路失效,其 createVirtualDisplay 便抛
// "Cannot create VirtualDisplay with non-current MediaProjection"。
if (starting || session != null) {
Log.w(TAG, "忽略重复启动请求(starting=$starting, running=${session != null})")
return
}
starting = true
++generation
}
// ------------------------------------------------------------------ 投屏
/** 接收主控端投屏控制事件。 */
private fun handleMirrorAction(action: Int, message: String) {
Log.i(TAG, "投屏控制事件: ${MirrorAction.name(action)} $message")
when (action) {
MirrorAction.REQUEST -> {
if (state == State.STREAMING) {
// 已经在投屏,幂等回执即可。
session?.notifyMirror(MirrorAction.GRANTED)
return
}
// 免确认模式下也要先有屏幕录制凭证,否则仍需要用户走一次授权。
if (!Prefs.mirrorConfirm(this) && projectionReady) {
beginMirroring()
return
}
requestConfirmation()
}
MirrorAction.STOP -> endMirroring(reply = true)
else -> Unit
}
}
/** 弹窗 + 通知双通道确认:前台直接弹框,后台靠通知(有悬浮窗权限时也能直接弹框)。 */
private fun requestConfirmation() {
if (pendingRequest) {
Log.i(TAG, "已有待确认的投屏请求,忽略重复请求")
return
}
pendingRequest = true
showRequestNotification()
MirrorRequestActivity.launch(this)
handler.postDelayed(requestTimeout, REQUEST_TIMEOUT_MS)
}
private fun cancelPendingRequest() {
pendingRequest = false
handler.removeCallbacks(requestTimeout)
notificationManager?.cancel(REQUEST_NOTIFICATION_ID)
}
private fun denyPending(reason: String) {
if (!pendingRequest) return
cancelPendingRequest()
session?.notifyMirror(MirrorAction.DENIED, reason)
Log.i(TAG, "投屏请求被拒绝: $reason")
}
/** 校验权限并开始投屏(用户已确认)。 */
private fun beginMirroring() {
ensureSession()
// Android 14+ 要求 createVirtualDisplay 时存在 mediaProjection 类型的前台服务,
// 这里在真正开流前再确认一次(此时用户已授予屏幕录制权限)。
ensureForeground()
val current = session ?: return
val active = projection
if (active == null || !projectionReady) {
current.notifyMirror(MirrorAction.ERROR, "设备尚未授予屏幕录制权限")
Toast.makeText(this, "尚未授权屏幕录制,请先完成授权", Toast.LENGTH_SHORT).show()
return
}
cancelPendingRequest()
execWorker {
val started = current.beginMirroring(active)
handler.post {
if (started) {
state = State.STREAMING
current.notifyMirror(MirrorAction.GRANTED)
Log.i(TAG, "已开始投屏")
} else {
state = State.STANDBY
current.notifyMirror(MirrorAction.ERROR, "屏幕采集启动失败")
}
updateNotification()
}
}
}
private fun endMirroring(reply: Boolean) {
val current = session
if (current != null) execWorker { current.endMirroring() }
if (state == State.STREAMING) {
state = State.STANDBY
if (reply) session?.notifyMirror(MirrorAction.STOPPED)
updateNotification()
Log.i(TAG, "已停止投屏,回到待命")
}
}
/** 拿到/复用 MediaProjection 凭证。真正创建 VirtualDisplay 在 beginMirroring 里。 */
private fun attachProjection(resultCode: Int, data: Intent, mirrorAfter: Boolean) {
ensureSession()
if (projection != null && projectionReady) {
if (mirrorAfter) beginMirroring()
return
}
val manager = getSystemService(MediaProjectionManager::class.java)
val created = try {
manager?.getMediaProjection(resultCode, data)
} catch (e: Exception) {
Log.e(TAG, "getMediaProjection failed", e)
} catch (error: Exception) {
Log.e(TAG, "getMediaProjection 失败", error)
null
}
if (created == null) {
Toast.makeText(this, "MediaProjection 授权失败,请重新授权", Toast.LENGTH_SHORT).show()
stopProjectionSession()
stopSelf()
Toast.makeText(this, "屏幕录制授权失败,请重试", Toast.LENGTH_SHORT).show()
session?.notifyMirror(MirrorAction.ERROR, "屏幕录制授权失败")
return
}
val callback = object : MediaProjection.Callback() {
override fun onStop() {
Log.i(TAG, "MediaProjection session stopped by system")
Handler(Looper.getMainLooper()).post {
// 只拆掉自己这一路,避免旧投影的回调把新会话拆了。
if (isCurrentProjection(created)) {
stopProjectionSession()
stopSelf()
Log.i(TAG, "MediaProjection 已被系统或用户停止")
handler.post {
if (projection === created) {
releaseProjection()
session?.endMirroring()
state = if (session != null) State.STANDBY else State.IDLE
updateNotification()
}
}
}
}
projection = created
projectionCallback = callback
created.registerCallback(callback, Handler(Looper.getMainLooper()))
projectionReady = true
created.registerCallback(callback, handler)
Log.i(TAG, "已获得屏幕录制凭证(尚未投屏)")
startBeacon()
val current = ReceiverSession(
context = this,
projection = created,
hostOverride = host,
signalingUrl = signalingUrl,
certificatePem = "",
)
session = current
// 连接建立包含 TCP 握手,必须在后台线程执行,避免服务主线程 ANR。
Thread {
try {
if (!isCurrentGeneration(gen)) {
current.stop()
return@Thread
}
current.start()
if (!isCurrentGeneration(gen)) {
current.stop()
return@Thread
}
isRunning = true
synchronized(stateLock) { if (gen == generation) starting = false }
Log.i(TAG, "Receiver session started")
} catch (e: Throwable) {
// 用 Throwable 兜底,避免异常逃逸后 starting 卡在 true 让会话再也无法重建。
Log.e(TAG, "Failed to start receiver session", e)
Handler(Looper.getMainLooper()).post { failStart(gen, e) }
}
}.start()
if (mirrorAfter) beginMirroring()
}
/** 启动失败:只有仍是当前世代时才拆会话,避免误杀新会话。 */
private fun failStart(gen: Int, error: Throwable) {
if (!isCurrentGeneration(gen)) return
val raw = error.message ?: error.javaClass.simpleName
val message = if (raw.contains("non-current", ignoreCase = true)) {
"投屏授权已失效,请重新点击「授权并开始投屏」"
} else {
raw
}
Toast.makeText(this, "连接失败: $message", Toast.LENGTH_SHORT).show()
stopProjectionSession()
stopSelf()
}
private fun isCurrentGeneration(gen: Int): Boolean = synchronized(stateLock) { gen == generation }
private fun isCurrentProjection(target: MediaProjection): Boolean =
synchronized(stateLock) { projection === target }
/** 开启 UDP 信标:一边广播自身,一边收集主控端的 host 应答。 */
private fun startBeacon() {
if (beacon != null) return
val metrics = resources.displayMetrics
val width = maxOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1920)
val height = minOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1080)
com.ttstd.lancast.receiver.discovery.HostBeacon.resetHost()
beacon = com.ttstd.lancast.receiver.discovery.HostBeacon(
device = com.ttstd.lancast.receiver.discovery.HostBeacon.Offer(
id = java.util.UUID.randomUUID().toString(),
name = "Android Receiver",
model = Build.MODEL ?: "Android",
resolution = "${width}x$height",
),
).also { it.start() }
}
private fun stopProjectionSession() {
synchronized(stateLock) {
// 递增世代号,让仍在启动流程里的后台线程失效,不再碰已被顶掉的投影。
++generation
starting = false
}
session?.stop()
session = null
private fun releaseProjection() {
val callback = projectionCallback
val current = projection
projectionCallback = null
projection = null
projectionReady = false
if (callback != null && current != null) {
runCatching { current.unregisterCallback(callback) }
.onFailure { Log.w(TAG, "unregisterCallback failed", it) }
.onFailure { Log.w(TAG, "unregisterCallback 失败", it) }
}
// 必须显式 stop():否则系统仍把上一路投影视为「当前」投影,
// 下一次 createVirtualDisplay 会抛 non-current MediaProjection。
if (current != null) {
runCatching { current.stop() }
.onFailure { Log.w(TAG, "projection.stop() failed", it) }
.onFailure { Log.w(TAG, "projection.stop() 失败", it) }
}
}
private fun teardown() {
handler.removeCallbacksAndMessages(null)
pendingRequest = false
state = State.IDLE
isRunning = false
filePort = 0
session?.stop()
session = null
worker.shutdownNow()
fileServer?.stop()
fileServer = null
beacon?.stop()
beacon = null
com.ttstd.lancast.receiver.discovery.HostBeacon.resetHost()
isRunning = false
HostBeacon.resetHost()
releaseProjection()
notificationManager?.cancel(REQUEST_NOTIFICATION_ID)
}
override fun onDestroy() {
stopProjectionSession()
teardown()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
stopForeground(STOP_FOREGROUND_REMOVE)
} else {
@@ -282,32 +442,128 @@ class MediaProjectionService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
CHANNEL_ID,
"屏幕投屏服务",
NotificationManager.IMPORTANCE_LOW
).apply {
description = "保持屏幕捕获服务在后台运行"
// ------------------------------------------------------------------ 通知
private fun ensureForeground() {
val notification = buildServiceNotification()
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(
NOTIFICATION_ID,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION,
)
} else {
startForeground(NOTIFICATION_ID, notification)
}
val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(channel)
} catch (error: Exception) {
Log.e(TAG, "startForeground(mediaProjection) 失败,降级为普通前台服务", error)
runCatching { startForeground(NOTIFICATION_ID, notification) }
.onFailure { Log.e(TAG, "startForeground 降级同样失败", it) }
}
}
private fun createNotification(): Notification {
private fun updateNotification() {
notificationManager?.notify(NOTIFICATION_ID, buildServiceNotification())
}
private fun buildServiceNotification(): Notification {
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(this, CHANNEL_ID)
Notification.Builder(this, CHANNEL_SERVICE)
} else {
@Suppress("DEPRECATION")
Notification.Builder(this)
}
val text = when (state) {
State.STREAMING -> "正在向主控端投屏"
State.STANDBY -> "待命中,等待主控端请求(未投屏)"
State.IDLE -> "服务启动中…"
}
val contentIntent = PendingIntent.getActivity(
this,
0,
Intent(this, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
return builder
.setContentTitle("Lancast 投屏服务")
.setContentText("屏幕投屏服务正在运行中")
.setContentTitle("TTSTD 远控服务")
.setContentText(text)
.setSmallIcon(android.R.drawable.ic_menu_camera)
.setOngoing(true)
.setContentIntent(contentIntent)
.build()
}
private fun showRequestNotification() {
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(this, CHANNEL_REQUEST)
} else {
@Suppress("DEPRECATION")
Notification.Builder(this)
}
val allow = PendingIntent.getService(
this,
10,
Intent(this, MediaProjectionService::class.java).setAction(ACTION_MIRROR_START),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
val deny = PendingIntent.getService(
this,
11,
Intent(this, MediaProjectionService::class.java).setAction(ACTION_MIRROR_DENY),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
val open = PendingIntent.getActivity(
this,
12,
Intent(this, MirrorRequestActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
val notification = builder
.setContentTitle("投屏请求")
.setContentText("主控端请求查看您的屏幕,是否允许?")
.setSmallIcon(android.R.drawable.ic_menu_view)
.setPriority(Notification.PRIORITY_HIGH)
.setOngoing(true)
.setContentIntent(open)
.addAction(Notification.Action.Builder(null, "允许", allow).build())
.addAction(Notification.Action.Builder(null, "拒绝", deny).build())
.build()
notificationManager?.notify(REQUEST_NOTIFICATION_ID, notification)
}
private fun createNotificationChannels() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val service = NotificationChannel(
CHANNEL_SERVICE,
"远控服务",
NotificationManager.IMPORTANCE_LOW,
).apply {
description = "保持待命/投屏服务在后台运行"
}
val request = NotificationChannel(
CHANNEL_REQUEST,
"投屏请求",
NotificationManager.IMPORTANCE_HIGH,
).apply {
description = "主控端请求投屏时提醒确认"
enableVibration(true)
}
notificationManager?.createNotificationChannel(service)
notificationManager?.createNotificationChannel(request)
}
private fun realMetrics(): DisplayMetrics {
val metrics = DisplayMetrics()
val manager = getSystemService(android.hardware.display.DisplayManager::class.java)
val display = manager?.getDisplay(Display.DEFAULT_DISPLAY)
if (display != null) {
@Suppress("DEPRECATION")
display.getRealMetrics(metrics)
} else {
metrics.setTo(resources.displayMetrics)
}
return metrics
}
}
@@ -0,0 +1,113 @@
package com.ttstd.lancast.receiver
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.WindowManager
/**
* 投屏确认页(透明主题,只显示一个对话框)。
*
* 主控端下发 [com.ttstd.lancast.receiver.protocol.MirrorAction.REQUEST] 后由 Service 拉起:
* - 用户拒绝 → 回 DENIED;
* - 用户允许且已有屏幕录制凭证 → 直接开流(GRANTED);
* - 用户允许但没有凭证 → 现场走系统授权,成功后带着凭证开流。
*/
class MirrorRequestActivity : Activity() {
companion object {
private const val TAG = "MirrorRequest"
private const val REQUEST_CAPTURE = 2001
private const val TIMEOUT_MS = 30_000L
/**
* 尝试拉起确认页。Android 10+ 后台启动 Activity 会被系统拦截,
* 此时用户会看到服务发出的高优先级通知,点击同样能进入本页。
*/
fun launch(context: Context) {
try {
context.startActivity(
Intent(context, MirrorRequestActivity::class.java).apply {
addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK or
Intent.FLAG_ACTIVITY_CLEAR_TOP or
Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS,
)
},
)
} catch (error: Exception) {
Log.w(TAG, "无法直接拉起确认页: ${error.message}")
}
}
}
private val handler = Handler(Looper.getMainLooper())
private var decided = false
private val timeout = Runnable { finishWith(false, "确认超时") }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
handler.postDelayed(timeout, TIMEOUT_MS)
showDialog()
}
private fun showDialog() {
AlertDialog.Builder(this)
.setTitle("投屏请求")
.setMessage("主控端请求查看您的屏幕。\n\n允许后开始投屏,您可随时在通知栏或本应用内停止。")
.setCancelable(false)
.setPositiveButton("允许") { _, _ -> onAllow() }
.setNegativeButton("拒绝") { _, _ -> finishWith(false, "用户拒绝") }
.show()
}
private fun onAllow() {
if (MediaProjectionService.hasProjection) {
MediaProjectionService.startMirroring(this)
finishWith(true, null)
return
}
val manager = getSystemService(MediaProjectionManager::class.java)
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_CAPTURE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode != REQUEST_CAPTURE) return
if (resultCode == RESULT_OK && data != null) {
MediaProjectionService.attachProjection(this, resultCode, data, mirrorAfter = true)
finishWith(true, null)
} else {
finishWith(false, "用户取消授权")
}
}
private fun finishWith(granted: Boolean, reason: String?) {
if (decided) return
decided = true
handler.removeCallbacks(timeout)
if (!granted) MediaProjectionService.denyMirroring(this)
finish()
}
override fun onDestroy() {
if (!decided) {
// 页面被意外销毁(返回键等)也要给主控端一个明确答复,避免它一直等待。
decided = true
handler.removeCallbacks(timeout)
MediaProjectionService.denyMirroring(this)
}
super.onDestroy()
}
override fun onBackPressed() {
finishWith(false, "用户取消")
}
}
@@ -0,0 +1,59 @@
package com.ttstd.lancast.receiver
import android.content.Context
import java.security.SecureRandom
/**
* 轻量配置存储。
*
* - [autoGrant]:主开关「允许远控」。打开后进入应用/开机自动启动待命服务,并自动发起一次
* 屏幕录制授权(仅获得凭证,不创建 VirtualDisplay,因此不会立即投屏)。
* - [fileServiceEnabled]:LocalSend 风格文件服务(浏览/下载/接收)。
* - [fileToken]:文件服务访问令牌,首次使用时生成,显示在主界面供主控端填写。
*/
object Prefs {
private const val NAME = "lancast_receiver_prefs"
private const val KEY_AUTO_GRANT = "auto_grant"
private const val KEY_FILE_SERVICE = "file_service_enabled"
private const val KEY_FILE_TOKEN = "file_token"
private const val KEY_MIRROR_CONFIRM = "mirror_confirm"
private fun prefs(context: Context) = context.applicationContext
.getSharedPreferences(NAME, Context.MODE_PRIVATE)
fun autoGrant(context: Context): Boolean = prefs(context).getBoolean(KEY_AUTO_GRANT, false)
fun setAutoGrant(context: Context, value: Boolean) {
prefs(context).edit().putBoolean(KEY_AUTO_GRANT, value).apply()
}
/** 主控端请求投屏时是否需要本机弹窗确认(默认需要,安全优先)。 */
fun mirrorConfirm(context: Context): Boolean = prefs(context).getBoolean(KEY_MIRROR_CONFIRM, true)
fun setMirrorConfirm(context: Context, value: Boolean) {
prefs(context).edit().putBoolean(KEY_MIRROR_CONFIRM, value).apply()
}
fun fileServiceEnabled(context: Context): Boolean =
prefs(context).getBoolean(KEY_FILE_SERVICE, true)
fun setFileServiceEnabled(context: Context, value: Boolean) {
prefs(context).edit().putBoolean(KEY_FILE_SERVICE, value).apply()
}
fun fileToken(context: Context): String {
val store = prefs(context)
val existing = store.getString(KEY_FILE_TOKEN, null)
if (!existing.isNullOrEmpty()) return existing
return rotateFileToken(context)
}
fun rotateFileToken(context: Context): String {
val random = SecureRandom()
val token = buildString {
repeat(8) { append('0' + random.nextInt(10)) }
}
prefs(context).edit().putString(KEY_FILE_TOKEN, token).apply()
return token
}
}
@@ -1,9 +1,15 @@
package com.ttstd.lancast.receiver
import android.content.Context
import android.hardware.display.DisplayManager
import android.media.projection.MediaProjection
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.DisplayMetrics
import android.util.Log
import android.view.Display
import com.ttstd.lancast.receiver.capture.AudioCapturer
import com.ttstd.lancast.receiver.capture.ScreenCapturer
import com.ttstd.lancast.receiver.clipboard.ClipboardBridge
@@ -13,6 +19,7 @@ import com.ttstd.lancast.receiver.discovery.NsdAdvertiser
import com.ttstd.lancast.receiver.discovery.ReceiverAnnouncer
import com.ttstd.lancast.receiver.encode.OpusEncoder
import com.ttstd.lancast.receiver.encode.VideoEncoder
import com.ttstd.lancast.receiver.file.FileBrowser
import com.ttstd.lancast.receiver.file.FileService
import com.ttstd.lancast.receiver.input.InputInjector
import com.ttstd.lancast.receiver.protocol.ControlEvent
@@ -21,9 +28,16 @@ import java.io.File
import java.util.UUID
import java.util.concurrent.Executors
/**
* 被控端会话。分两个阶段:
*
* 1. **待命**([start]):只做设备广播 + 控制通道拨号,不占用编码器、不创建 VirtualDisplay,
* 因此不会投屏,主控端可以随时下发投屏请求。
* 2. **投屏**([beginMirroring]):拿到 MediaProjection 后按本机真实屏幕尺寸建立
* 编码器 + VirtualDisplay + 音频采集,期间跟随屏幕旋转/分辨率变化自动重建。
*/
class ReceiverSession(
private val context: Context,
private val projection: MediaProjection,
/** 主控端地址;为空时通过 UDP 信标自动发现(推荐)。 */
private val hostOverride: String,
private val signalingUrl: String,
@@ -31,16 +45,33 @@ class ReceiverSession(
private val preferH265: Boolean = false,
private val bitrateMbps: Int = 8,
) {
companion object {
private const val TAG = "ReceiverSession"
/** 编码长边上限,兼顾清晰度与局域网带宽。 */
private const val MAX_LONG_SIDE = 1920
}
private val executor = Executors.newFixedThreadPool(3)
private val clipboard = ClipboardBridge(context)
private val injector = InputInjector(context)
private val fileService = FileService(File(context.filesDir, "file-inbox"))
private val fileService = FileService(File(context.filesDir, "file-inbox"), FileBrowser(context))
private val opusEncoder = OpusEncoder()
private val displayManager = context.getSystemService(DisplayManager::class.java)
private val mainHandler = Handler(Looper.getMainLooper())
private val fingerprint: String = ""
@Volatile
private var transport: ReceiverTransport? = null
/** 主控端投屏请求回调:(action, message),由 Service 绑定。 */
@Volatile
var onMirrorRequest: ((Int, String) -> Unit)? = null
/** 投屏过程中采集链路重建失败的回调。 */
@Volatile
var onStreamingLost: (() -> Unit)? = null
private val encoder = VideoEncoder { buffer, info ->
transport?.sendVideo(buffer, info, preferH265)
}
@@ -49,38 +80,150 @@ class ReceiverSession(
private var audio: AudioCapturer? = null
private var announcer: ReceiverAnnouncer? = null
private var nsdAdvertiser: NsdAdvertiser? = null
@Volatile
private var running = false
fun start() {
if (running) return
running = true
val metrics = context.resources.displayMetrics
val width = maxOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1920)
val height = minOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1080)
/** 是否正在投屏(采集链路已建立)。 */
@Volatile
var mirroring = false
private set
try {
startCapture(width, height, metrics.densityDpi)
startPublishing(width, height)
} catch (e: Exception) {
// 启动失败必须彻底释放已申请的编码器/虚拟显示,否则会残留并阻塞下次启动。
running = false
stop()
throw e
private val captureLock = Any()
private var projection: MediaProjection? = null
private var captureWidth = 0
private var captureHeight = 0
private var captureDensity = 0
private val displayListener = object : DisplayManager.DisplayListener {
override fun onDisplayAdded(displayId: Int) = Unit
override fun onDisplayRemoved(displayId: Int) = Unit
override fun onDisplayChanged(displayId: Int) {
if (displayId == Display.DEFAULT_DISPLAY) scheduleResize()
}
}
/** 建立采集链路:编码器 + VirtualDisplay + 剪贴板。 */
private fun startCapture(width: Int, height: Int, densityDpi: Int) {
encoder.start(width, height, 30, bitrateMbps * 1_000_000, preferH265)
val surface = encoder.inputSurface
?: throw IllegalStateException("视频编码器未返回输入 Surface")
capturer = ScreenCapturer(projection, surface, densityDpi).also { it.start(width, height) }
/** 待命启动:只建立发现与控制链路。 */
fun start() {
if (running) return
running = true
displayManager?.registerDisplayListener(displayListener, mainHandler)
opusEncoder.start()
clipboard.start { text -> transport?.sendControl(ControlEvent.Clipboard(text)) }
startPublishing()
executor.execute {
while (running) {
// 与采集链路的建立/重建互斥,避免旋转重建时两个线程同时操作 MediaCodec。
synchronized(captureLock) { encoder.drain() }
try {
Thread.sleep(if (mirroring) 4 else 20)
} catch (_: InterruptedException) {
return@execute
}
}
}
executor.execute { connectWhenHostReady() }
Log.i(TAG, "会话进入待命状态(未投屏)")
}
/** 发布设备信息 / 音频采集 / 拨号线程。 */
private fun startPublishing(width: Int, height: Int) {
/**
* 开始投屏。必须在 [start] 之后、且持有有效的 MediaProjection 时调用。
* @return 是否成功建立采集链路。
*/
fun beginMirroring(projection: MediaProjection): Boolean {
if (!running) return false
synchronized(captureLock) {
if (mirroring) return true
this.projection = projection
return try {
startCapture()
mirroring = true
Log.i(TAG, "开始投屏 ${captureWidth}x$captureHeight")
true
} catch (error: Exception) {
Log.e(TAG, "开启采集失败", error)
releaseCapture()
false
}
}
}
/** 停止投屏但保留会话(回到待命)。 */
fun endMirroring() {
synchronized(captureLock) {
if (!mirroring) return
mirroring = false
releaseCapture()
Log.i(TAG, "已停止投屏,回到待命状态")
}
}
/** 回送投屏应答给主控端。 */
fun notifyMirror(action: Int, message: String = "") {
transport?.sendMirror(action, message)
}
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()
encoder.start(captureWidth, captureHeight, 30, bitrateMbps * 1_000_000, preferH265)
val surface = encoder.inputSurface
?: throw IllegalStateException("视频编码器未返回输入 Surface")
capturer = ScreenCapturer(current, 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
opusEncoder.encode(pcm).forEach { packet ->
active.sendAudio(packet, SystemClock.elapsedRealtimeNanos() / 1000)
}
}.also { it.start() }
}
}
private fun releaseCapture() {
runCatching { capturer?.stop() }.onFailure { Log.w(TAG, "释放采集失败", it) }
capturer = null
runCatching { audio?.stop() }.onFailure { Log.w(TAG, "释放音频采集失败", it) }
audio = null
runCatching { encoder.stop() }.onFailure { Log.w(TAG, "释放编码器失败", it) }
}
/** 屏幕旋转或分辨率变化后,按新尺寸重建编码器与 VirtualDisplay。 */
private fun scheduleResize() {
if (!mirroring) return
executor.execute {
synchronized(captureLock) {
if (!mirroring) return@execute
val size = currentScreenSize()
if (size[0] == captureWidth && size[1] == captureHeight) return@execute
Log.i(TAG, "屏幕尺寸变化 ${captureWidth}x$captureHeight -> ${size[0]}x${size[1]},重建采集")
releaseCapture()
try {
startCapture()
} catch (error: Exception) {
Log.e(TAG, "按新尺寸重建采集失败", error)
mirroring = false
releaseCapture()
onStreamingLost?.invoke()
}
}
}
}
/** 发布设备信息并启动控制通道拨号。 */
private fun startPublishing() {
val size = currentScreenSize()
val device = AnnouncedDevice(
id = UUID.randomUUID().toString(),
name = "Android Receiver",
@@ -88,33 +231,17 @@ class ReceiverSession(
mediaPort = 41000,
controlPort = 41001,
fingerprint = this@ReceiverSession.fingerprint,
capabilities = listOf("h264", "opus", "uibc", "clipboard", "file"),
capabilities = listOf(
"h264", "opus", "uibc", "clipboard", "file", "mirror-request", "file-browse",
),
model = Build.MODEL,
resolution = "${width}x$height",
resolution = "${size[0]}x${size[1]}",
)
// 信令服务器是跨网段兜底:没有配置(空串)时不必启动,避免无谓的失败请求。
if (signalingUrl.isNotBlank()) {
announcer = ReceiverAnnouncer(signalingUrl, device).also { it.start() }
}
nsdAdvertiser = NsdAdvertiser(context, device).also { it.start() }
opusEncoder.start()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
audio = AudioCapturer(projection) { pcm ->
val current = transport ?: return@AudioCapturer
opusEncoder.encode(pcm).forEach { packet ->
current.sendAudio(packet, SystemClock.elapsedRealtimeNanos() / 1000)
}
}.also { it.start() }
}
executor.execute {
while (running) {
encoder.drain()
Thread.sleep(4)
}
}
executor.execute { connectWhenHostReady() }
}
/** 等主控端地址可用(信标发现或手动覆盖)后再拨号,之后由 transport 自己重连。 */
@@ -133,6 +260,7 @@ class ReceiverSession(
clipboard,
fileService,
)
created.onMirrorEvent = { action, message -> onMirrorRequest?.invoke(action, message) }
transport = created
created.start()
return
@@ -147,18 +275,53 @@ class ReceiverSession(
fun stop() {
running = false
capturer?.stop()
audio?.stop()
displayManager?.unregisterDisplayListener(displayListener)
endMirroring()
clipboard.stop()
announcer?.stop()
nsdAdvertiser?.stop()
opusEncoder.stop()
transport?.stop()
transport = null
encoder.stop()
runCatching { encoder.stop() }
executor.shutdownNow()
}
/** 本机真实屏幕尺寸(跟随旋转),长边限制在 [MAX_LONG_SIDE] 内,宽高取偶数。 */
private fun currentScreenSize(): 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 fit(metrics.widthPixels, metrics.heightPixels)
}
private fun currentDensity(): Int {
val display = displayManager?.getDisplay(Display.DEFAULT_DISPLAY)
?: return context.resources.displayMetrics.densityDpi
val metrics = DisplayMetrics()
@Suppress("DEPRECATION")
display.getRealMetrics(metrics)
return if (metrics.densityDpi > 0) metrics.densityDpi else context.resources.displayMetrics.densityDpi
}
private fun fit(width: Int, height: Int): IntArray {
var w = width.coerceAtLeast(16)
var h = height.coerceAtLeast(16)
val longSide = maxOf(w, h)
if (longSide > MAX_LONG_SIDE) {
val scale = MAX_LONG_SIDE.toDouble() / longSide
w = (w * scale).toInt()
h = (h * scale).toInt()
}
// H.264/HEVC 要求偶数尺寸。
return intArrayOf(w.coerceAtLeast(16) and 1.inv(), h.coerceAtLeast(16) and 1.inv())
}
private val localIp: String
get() = java.net.NetworkInterface.getNetworkInterfaces().toList()
.flatMap { it.inetAddresses.toList() }
@@ -160,7 +160,14 @@ class HostBeacon(
put("media", mediaPort)
put("audio", audioPort)
put("fp", "")
put("cap", JSONArray(listOf("h264", "opus", "uibc", "clipboard", "file")))
put(
"cap",
JSONArray(
listOf(
"h264", "opus", "uibc", "clipboard", "file", "mirror-request", "file-browse",
),
),
)
}
return json.toString().toByteArray(Charsets.UTF_8)
}
@@ -0,0 +1,106 @@
package com.ttstd.lancast.receiver.file
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
/**
* 只读目录浏览 + 路径越权校验。
*
* 所有对外暴露的路径都必须是 [allowedRoots] 之下的规范路径,避免 `../` 穿越读到私有数据。
*/
class FileBrowser(private val context: Context) {
companion object {
/** 单次列举的最大条目数,防止一次请求拉爆内存/带宽。 */
private const val MAX_ENTRIES = 2000
}
fun allowedRoots(): List<File> = StorageAccess.roots(context)
fun rootsJson(): JSONArray {
val array = JSONArray()
allowedRoots().forEach { root ->
array.put(
JSONObject()
.put("name", root.name.ifEmpty { root.absolutePath })
.put("path", root.absolutePath),
)
}
return array
}
/** 把请求路径规范化,并校验仍落在允许的根目录内。 */
fun resolve(path: String): File {
val roots = allowedRoots()
if (roots.isEmpty()) throw SecurityException("没有可访问的存储目录")
val candidate = if (path.isBlank()) roots.first() else File(path)
val canonical = try {
candidate.canonicalFile
} catch (error: Exception) {
throw SecurityException("非法路径: $path")
}
val allowed = roots.any { root ->
val rootPath = try {
root.canonicalPath
} catch (_: Exception) {
root.absolutePath
}
canonical.path == rootPath || canonical.path.startsWith(rootPath + File.separator)
}
if (!allowed) throw SecurityException("路径不在允许范围内: $path")
return canonical
}
/** 列举目录,返回 `{path, parent, roots, entries:[{name,path,dir,size,mtime}]}`。 */
fun list(path: String): JSONObject {
val dir = resolve(path)
if (!dir.exists()) throw IllegalArgumentException("目录不存在: ${dir.absolutePath}")
if (!dir.isDirectory) throw IllegalArgumentException("不是目录: ${dir.absolutePath}")
val entryArray = JSONArray()
val children = dir.listFiles() ?: emptyArray()
children.asSequence()
.filterNot { it.name.startsWith(".") }
.sortedWith(compareByDescending<File> { it.isDirectory }.thenBy { it.name.lowercase() })
.take(MAX_ENTRIES)
.forEach { child ->
entryArray.put(
JSONObject()
.put("name", child.name)
.put("path", child.absolutePath)
.put("dir", child.isDirectory)
.put("size", if (child.isDirectory) 0L else child.length())
.put("mtime", child.lastModified()),
)
}
val parent = dir.parentFile
val parentPath = if (parent != null) {
try {
resolve(parent.absolutePath).absolutePath
} catch (_: SecurityException) {
""
}
} else {
""
}
return JSONObject()
.put("path", dir.absolutePath)
.put("parent", parentPath)
.put("roots", rootsJson())
.put("entries", entryArray)
}
/** 计算上传落盘目标文件(限定在允许范围内,文件名做基本清洗)。 */
fun uploadTarget(dirPath: String, name: String): File {
val dir = resolve(dirPath)
if (!dir.isDirectory) throw IllegalArgumentException("目标不是目录")
val safe = name.replace('/', '_').replace('\\', '_').replace("..", "_").ifEmpty {
"upload-${System.currentTimeMillis()}"
}
return File(dir, safe)
}
}
@@ -0,0 +1,362 @@
package com.ttstd.lancast.receiver.file
import android.content.Context
import android.os.Build
import android.util.Log
import org.json.JSONObject
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.io.OutputStream
import java.net.InetSocketAddress
import java.net.ServerSocket
import java.net.Socket
import java.net.URLDecoder
import java.nio.charset.StandardCharsets
import java.util.concurrent.Executors
/**
* LocalSend 风格的文件服务(默认 53317,被占用时顺延)。
*
* 提供的能力:
* - `GET /api/localsend/v1/info`、`/api/localsend/v2/info`:LocalSend 设备信息(无需令牌)
* - `POST /api/localsend/v1/register`、`/v2/register`:LocalSend 注册握手(无需令牌)
* - `GET /browse?path=`:浏览 Android 目录(返回 JSON)
* - `GET /download?path=`:下载单个文件
* - `POST /api/localsend/v2/upload?path=&name=`:接收文件到指定目录
* - `POST /mirror/request`:触发一次投屏确认(便于不开主控端也能验证)
*
* 除 info/register 外都要求 `?token=`(或 `X-Lancast-Token` 头)与主界面显示的一致。
*/
class FileHttpServer(
private val context: Context,
private val tokenProvider: () -> String,
private val onMirrorRequest: (String) -> Unit,
) {
companion object {
private const val TAG = "FileHttpServer"
private val CANDIDATE_PORTS = intArrayOf(53317, 53318, 53319, 53320)
private const val MAX_BODY = 64L * 1024 * 1024
}
private val browser = FileBrowser(context)
private val workers = Executors.newCachedThreadPool()
private var serverSocket: ServerSocket? = null
private var acceptThread: Thread? = null
@Volatile
private var running = false
@Volatile
var boundPort: Int = 0
private set
val isRunning: Boolean get() = running
fun start(): Int {
if (running) return boundPort
for (port in CANDIDATE_PORTS) {
try {
val socket = ServerSocket().apply {
reuseAddress = true
bind(InetSocketAddress(port))
}
serverSocket = socket
boundPort = port
running = true
acceptThread = Thread({ acceptLoop(socket) }, "lancast-file-http").apply {
isDaemon = true
start()
}
Log.i(TAG, "文件服务已启动,端口 $port")
return port
} catch (error: Exception) {
Log.w(TAG, "端口 $port 不可用: ${error.message}")
}
}
Log.e(TAG, "没有可用端口,文件服务未启动")
return 0
}
fun stop() {
running = false
try {
serverSocket?.close()
} catch (_: Exception) {
}
serverSocket = null
acceptThread?.interrupt()
acceptThread = null
workers.shutdownNow()
boundPort = 0
}
private fun acceptLoop(socket: ServerSocket) {
while (running) {
val client = try {
socket.accept()
} catch (error: Exception) {
if (!running) return
continue
}
workers.execute { handle(client) }
}
}
private fun handle(socket: Socket) {
socket.use { client ->
client.soTimeout = 15000
val input = BufferedInputStream(client.getInputStream())
val output = BufferedOutputStream(client.getOutputStream())
try {
val requestLine = readLine(input) ?: return
val parts = requestLine.split(' ')
if (parts.size < 2) return
val method = parts[0].uppercase()
val target = parts[1]
val headers = mutableMapOf<String, String>()
while (true) {
val line = readLine(input) ?: break
if (line.isEmpty()) break
val index = line.indexOf(':')
if (index > 0) {
headers[line.substring(0, index).trim().lowercase()] = line.substring(index + 1).trim()
}
}
val body = readBody(input, headers)
val path = target.substringBefore('?')
val query = parseQuery(target.substringAfter('?', ""))
val response = try {
route(method, path, query, headers, body)
} catch (error: SecurityException) {
jsonResponse(403, error.message ?: "禁止访问")
} catch (error: Exception) {
jsonResponse(400, error.message ?: "请求失败")
}
writeResponse(output, response)
} catch (error: Exception) {
Log.w(TAG, "连接处理失败: ${error.message}")
}
}
}
private fun route(
method: String,
path: String,
query: Map<String, String>,
headers: Map<String, String>,
body: ByteArray,
): Response {
// LocalSend 发现/注册接口不需要令牌,方便桌面端识别设备。
if (path == "/api/localsend/v1/info" || path == "/api/localsend/v2/info") {
return jsonResponse(200, infoJson())
}
if (path.endsWith("/register")) {
return Response(204, "application/json")
}
if (!authorized(query, headers)) {
return jsonResponse(403, "令牌无效,请填写主界面显示的文件服务令牌")
}
return when (path) {
"/", "/index.html" -> htmlResponse(indexHtml())
"/browse" -> jsonResponse(200, browser.list(query["path"] ?: "").toString())
"/download" -> download(query["path"] ?: "")
"/api/localsend/v2/upload", "/api/localsend/v1/upload" -> upload(query, body)
"/mirror/request" -> {
onMirrorRequest(query["host"] ?: "")
jsonResponse(200, JSONObject().put("ok", true).toString())
}
else -> jsonResponse(404, "未知接口: $path")
}
}
private fun download(path: String): Response {
if (path.isBlank()) return jsonResponse(400, "缺少 path 参数")
val file = browser.resolve(path)
if (!file.exists() || !file.isFile) return jsonResponse(404, "文件不存在")
val mime = mimeOf(file.name)
return Response(
code = 200,
contentType = mime,
file = file,
headers = listOf("Content-Disposition" to "attachment; filename=\"${file.name}\""),
)
}
private fun upload(query: Map<String, String>, body: ByteArray): Response {
val dir = query["path"] ?: browser.allowedRoots().firstOrNull()?.absolutePath
?: return jsonResponse(400, "缺少 path 参数")
val name = query["name"] ?: "upload-${System.currentTimeMillis()}"
val target = browser.uploadTarget(dir, name)
target.parentFile?.mkdirs()
target.outputStream().use { it.write(body) }
return jsonResponse(
200,
JSONObject()
.put("ok", true)
.put("path", target.absolutePath)
.put("size", target.length())
.toString(),
)
}
private fun authorized(query: Map<String, String>, headers: Map<String, String>): Boolean {
val expected = tokenProvider()
if (expected.isEmpty()) return true
val provided = query["token"] ?: headers["x-lancast-token"]
return provided == expected
}
private fun infoJson(): String = JSONObject().apply {
put("alias", "TTSTD Receiver")
put("version", "2.1")
put("deviceModel", Build.MODEL ?: "Android")
put("deviceType", "mobile")
put("fingerprint", tokenProvider())
put("port", boundPort)
put("protocol", "http")
put("download", false)
put("announce", false)
}.toString()
private fun indexHtml(): String = """
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>TTSTD 文件服务</title>
<style>
body{font-family:system-ui,sans-serif;margin:0;padding:24px;background:#111;color:#eee}
h1{font-size:18px;margin:0 0 12px}
code{background:#222;padding:2px 6px;border-radius:4px}
a{color:#4da3ff;text-decoration:none}
ul{padding-left:18px;line-height:1.9}
</style></head><body>
<h1>TTSTD 文件服务</h1>
<p>本页仅用于自检,实际请由主控端访问接口。</p>
<ul>
<li><a href="/api/localsend/v2/info">/api/localsend/v2/info</a></li>
<li><a href="/browse?token=__TOKEN__">/browse</a> 浏览根目录</li>
<li><code>GET /download?path=&amp;token=</code> 下载文件</li>
<li><code>POST /api/localsend/v2/upload?path=&amp;name=&amp;token=</code> 接收文件</li>
<li><code>POST /mirror/request?token=</code> 触发投屏确认</li>
</ul></body></html>
""".trimIndent().replace("__TOKEN__", tokenProvider())
private fun mimeOf(name: String): String {
val extension = name.substringAfterLast('.', "").lowercase()
return when (extension) {
"txt", "log", "md" -> "text/plain; charset=utf-8"
"json" -> "application/json; charset=utf-8"
"html", "htm" -> "text/html; charset=utf-8"
"jpg", "jpeg" -> "image/jpeg"
"png" -> "image/png"
"gif" -> "image/gif"
"webp" -> "image/webp"
"mp4" -> "video/mp4"
"mkv" -> "video/x-matroska"
"mp3" -> "audio/mpeg"
"apk" -> "application/vnd.android.package-archive"
"pdf" -> "application/pdf"
"zip" -> "application/zip"
else -> "application/octet-stream"
}
}
private fun jsonResponse(code: Int, message: String): Response {
val payload = if (message.trimStart().startsWith("{")) {
message
} else {
JSONObject().put("error", message).toString()
}
return Response(code, "application/json; charset=utf-8", payload.toByteArray(StandardCharsets.UTF_8))
}
private fun htmlResponse(html: String): Response =
Response(200, "text/html; charset=utf-8", html.toByteArray(StandardCharsets.UTF_8))
private fun readBody(input: InputStream, headers: Map<String, String>): ByteArray {
val length = headers["content-length"]?.toLongOrNull() ?: 0L
if (length <= 0) return ByteArray(0)
require(length <= MAX_BODY) { "请求体过大" }
val buffer = ByteArray(length.toInt())
var read = 0
while (read < buffer.size) {
val count = input.read(buffer, read, buffer.size - read)
if (count < 0) break
read += count
}
return if (read == buffer.size) buffer else buffer.copyOf(read)
}
private fun readLine(input: InputStream): String? {
val builder = StringBuilder()
while (true) {
val value = input.read()
if (value < 0) return if (builder.isEmpty()) null else builder.toString()
if (value == '\n'.code) break
if (value != '\r'.code) builder.append(value.toChar())
if (builder.length > 8192) break
}
return builder.toString()
}
private fun parseQuery(raw: String): Map<String, String> {
if (raw.isBlank()) return emptyMap()
val result = mutableMapOf<String, String>()
raw.split('&').forEach { pair ->
if (pair.isBlank()) return@forEach
val key = pair.substringBefore('=')
val value = pair.substringAfter('=', "")
result[decode(key)] = decode(value)
}
return result
}
private fun decode(value: String): String = try {
URLDecoder.decode(value, "UTF-8")
} catch (_: Exception) {
value
}
private fun writeResponse(output: OutputStream, response: Response) {
val length = response.file?.length() ?: response.body?.size?.toLong() ?: 0L
val header = StringBuilder()
.append("HTTP/1.1 ${response.code} ${statusText(response.code)}\r\n")
.append("Content-Type: ${response.contentType}\r\n")
.append("Content-Length: $length\r\n")
.append("Connection: close\r\n")
.append("Access-Control-Allow-Origin: *\r\n")
response.headers.forEach { (key, value) -> header.append("$key: $value\r\n") }
header.append("\r\n")
output.write(header.toString().toByteArray(StandardCharsets.UTF_8))
if (response.file != null) {
FileInputStream(response.file).use { stream -> stream.copyTo(output, 64 * 1024) }
} else if (response.body != null && response.body.isNotEmpty()) {
output.write(response.body)
}
output.flush()
}
private fun statusText(code: Int): String = when (code) {
200 -> "OK"
204 -> "No Content"
400 -> "Bad Request"
403 -> "Forbidden"
404 -> "Not Found"
else -> "OK"
}
private class Response(
val code: Int,
val contentType: String,
val body: ByteArray? = null,
val file: File? = null,
val headers: List<Pair<String, String>> = emptyList(),
)
}
@@ -8,7 +8,12 @@ import java.security.MessageDigest
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
class FileService(private val root: File) {
class FileService(
private val root: File,
/** 目录浏览能力;为空时控制通道的 `list` 操作会返回错误。 */
private val browser: FileBrowser? = null,
) {
private data class Entry(
val id: String,
val name: String,
@@ -82,6 +87,12 @@ class FileService(private val root: File) {
sessions.remove(sessionId)
}
/** 控制通道 msgType=7 的 `op=list`:浏览 Android 文件目录。 */
fun list(path: String): String {
val current = browser ?: throw IllegalStateException("文件浏览未启用")
return current.list(path).toString()
}
private fun safeName(name: String) = name.replace("/", "_").replace("\\", "_").replace("..", "_")
private fun sha256(file: File): String =
@@ -0,0 +1,78 @@
package com.ttstd.lancast.receiver.file
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import java.io.File
/**
* 存储访问权限封装。
*
* Android 11+ 想浏览整块外部存储(含其它应用目录)必须拿到「所有文件访问权限」
* ([Environment.isExternalStorageManager]);否则只能退回到应用自己的外部私有目录,
* 那个目录不需要任何权限,但看不到用户的相册/下载等文件。
*/
object StorageAccess {
/** 是否具备「浏览整块外部存储」的能力。 */
fun canBrowseAll(context: Context): Boolean =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Environment.isExternalStorageManager()
} else {
hasPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
}
fun hasPermission(context: Context, permission: String): Boolean =
context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
/** 运行时权限申请列表:Android 13+ 申请媒体读权限,更早版本申请存储读权限。 */
fun runtimePermissions(): Array<String> = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> arrayOf(
Manifest.permission.READ_MEDIA_IMAGES,
Manifest.permission.READ_MEDIA_VIDEO,
Manifest.permission.READ_MEDIA_AUDIO,
)
else -> arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
}
/** Android 11+ 的「所有文件访问权限」受系统设置页控制,只能跳转授予。 */
fun allFilesSettingsIntent(context: Context): Intent? =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Intent(
Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
Uri.parse("package:${context.packageName}"),
)
} else {
null
}
/** 可浏览的根目录(按优先级)。 */
fun roots(context: Context): List<File> {
val result = mutableListOf<File>()
if (canBrowseAll(context)) {
@Suppress("DEPRECATION")
val external = Environment.getExternalStorageDirectory()
if (external != null && external.exists()) result += external
}
// 应用外部私有目录始终可读写,作为没有全盘权限时的兜底。
context.getExternalFilesDir(null)?.let { result += it }
return result.distinctBy { it.absolutePath }
}
fun primaryRoot(context: Context): File? = roots(context).firstOrNull()
/** 给界面展示的一句话描述。 */
fun summary(context: Context): String = when {
canBrowseAll(context) ->
"已授权访问全部文件,可浏览 /storage/emulated/0"
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R ->
"未授予「所有文件访问权限」,仅能浏览应用私有目录"
else ->
"未授予存储读取权限,仅能浏览应用私有目录"
}
}
@@ -16,6 +16,8 @@ class InputInjector(private val context: Context) {
is ControlEvent.Wheel -> injectWheel(event)
is ControlEvent.Clipboard -> injectText(event.text)
is ControlEvent.Ping, is ControlEvent.Pong -> Unit
// 投屏请求由 Service 处理,不参与输入注入。
is ControlEvent.Mirror -> Unit
}
}
@@ -10,6 +10,38 @@ sealed class ControlEvent {
data class Clipboard(val text: String) : ControlEvent()
data class Ping(val timestamp: Long) : ControlEvent()
data class Pong(val timestamp: Long) : ControlEvent()
/**
* 投屏请求 / 应答(msgType = 8)。
*
* payload = `[action:u8]` + 可选 UTF-8 文本(用于 ERROR/DENIED 的原因说明)。
*/
data class Mirror(val action: Int, val message: String = "") : ControlEvent()
}
/**
* [ControlEvent.Mirror] 的 action 取值。
*
* 主控端 → Android:REQUEST / STOP。
* Android → 主控端:GRANTED / DENIED / STOPPED / ERROR。
*/
object MirrorAction {
const val REQUEST = 0
const val STOP = 1
const val GRANTED = 2
const val DENIED = 3
const val STOPPED = 4
const val ERROR = 5
fun name(action: Int): String = when (action) {
REQUEST -> "request"
STOP -> "stop"
GRANTED -> "granted"
DENIED -> "denied"
STOPPED -> "stopped"
ERROR -> "error"
else -> "unknown($action)"
}
}
data class ControlFrame(val version: Int, val sequence: Int, val event: ControlEvent)
@@ -73,6 +105,16 @@ object ControlFrames {
if (payload.size != 8) return null
ControlEvent.Pong(u64(payload, 0))
}
8 -> {
if (payload.isEmpty()) return null
val action = payload[0].toInt() and 0xff
val message = if (payload.size > 1) {
String(payload, 1, payload.size - 1, StandardCharsets.UTF_8)
} else {
""
}
ControlEvent.Mirror(action, message)
}
else -> return null
}
return ControlFrame(version, sequence, event)
@@ -95,6 +137,11 @@ object ControlFrames {
}
is ControlEvent.Ping -> u64Bytes(event.timestamp)
is ControlEvent.Pong -> u64Bytes(event.timestamp)
is ControlEvent.Mirror -> if (event.message.isEmpty()) {
byteArrayOf(event.action.toByte())
} else {
byteArrayOf(event.action.toByte()) + event.message.toByteArray(StandardCharsets.UTF_8)
}
}
return byteArrayOf(VERSION.toByte(), msgType(event).toByte()) +
u16Bytes(sequence) + u32Bytes(payload.size) + payload
@@ -108,6 +155,7 @@ object ControlFrames {
is ControlEvent.Clipboard -> 4
is ControlEvent.Ping -> 5
is ControlEvent.Pong -> 6
is ControlEvent.Mirror -> 8
}
private fun u16(bytes: ByteArray, offset: Int) =
@@ -52,6 +52,18 @@ class ReceiverTransport(
val keyEstablished: Boolean get() = keys != null
/**
* 收到主控端投屏请求/停止请求时的回调:(action, message)。
* 由 Service 绑定,用于弹窗确认与开流/停流。
*/
@Volatile
var onMirrorEvent: ((Int, String) -> Unit)? = null
/** 回送投屏应答(GRANTED / DENIED / STOPPED / ERROR)。 */
fun sendMirror(action: Int, message: String = "") {
sendControl(ControlEvent.Mirror(action, message))
}
fun start() {
if (active) return
active = true
@@ -203,6 +215,8 @@ class ReceiverTransport(
when (val event = frame.event) {
is ControlEvent.Clipboard -> clipboard.publish(event.text)
is ControlEvent.Ping -> sendControl(ControlEvent.Pong(event.timestamp))
is ControlEvent.Pong -> Unit
is ControlEvent.Mirror -> onMirrorEvent?.invoke(event.action, event.message)
else -> injector.inject(frame)
}
}
@@ -229,6 +243,16 @@ class ReceiverTransport(
}
"progress" -> sendRaw(7, fileService.progress(request.getString("sessionId")))
"cancel" -> fileService.cancel(request.getString("sessionId"))
"list" -> {
val json = try {
JSONObject(fileService.list(request.optString("path", ""))).put("op", "list")
} catch (error: Exception) {
JSONObject()
.put("op", "list")
.put("error", error.message ?: "目录浏览失败")
}
sendRaw(7, json.toString())
}
}
}
@@ -4,4 +4,12 @@
<item name="android:windowBackground">@android:color/background_dark</item>
<item name="android:textColorPrimary">@android:color/white</item>
</style>
<!-- 投屏确认页:半透明对话框样式,不显示标题栏。 -->
<style name="Theme.Lancast.Request" parent="@android:style/Theme.Material.Light.Dialog.NoActionBar">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:windowNoTitle">true</item>
</style>
</resources>