fix(receiver): 修复重复授权导致 MediaProjection 失效崩溃

- 会话启动改为单飞行:starting/会话存在时忽略重复 ACTION_START,避免第二路 getMediaProjection 让第一路失效

- 持有并显式 stop() 旧 MediaProjection,销毁前先注销回调,防止残留为当前投影

- 引入世代号,后台启动线程发现已被新会话取代时立即停止,不再操作过期投影

- 启动失败时彻底释放编码器/虚拟显示,并给出 non-current 的可读提示

- MainActivity 拦截会话进行中的再次授权请求
This commit is contained in:
tongtong committed 2026-11-27 08:40:07 +08:00
1 parent 5442dbff2c
commit 3feddb3434
4 files changed
+150 -43

No files matched your search

+1
View File
@@ -45,3 +45,4 @@ desktop.ini
# ===== Logs ===== # ===== Logs =====
*.log *.log
android_receiver/.remotecompile/
@@ -9,6 +9,7 @@ import android.os.Looper
import android.widget.Button import android.widget.Button
import android.widget.LinearLayout import android.widget.LinearLayout
import android.widget.TextView import android.widget.TextView
import android.widget.Toast
import com.ttstd.lancast.receiver.discovery.HostBeacon import com.ttstd.lancast.receiver.discovery.HostBeacon
import com.ttstd.lancast.receiver.session.PairingCode import com.ttstd.lancast.receiver.session.PairingCode
import java.net.NetworkInterface import java.net.NetworkInterface
@@ -78,6 +79,12 @@ class MainActivity : Activity() {
}.start() }.start()
start.setOnClickListener { start.setOnClickListener {
// 系统同一时刻只允许一路 MediaProjection:会话进行中再次授权会让正在采集的
// 那一路失效(non-current MediaProjection),必须等停止后再重新授权。
if (MediaProjectionService.isRunning) {
Toast.makeText(this, "投屏已在进行中,请先点「停止」", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
val manager = getSystemService(MediaProjectionManager::class.java) val manager = getSystemService(MediaProjectionManager::class.java)
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_CAPTURE) startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_CAPTURE)
} }
@@ -65,6 +65,22 @@ class MediaProjectionService : Service() {
private var session: ReceiverSession? = null private var session: ReceiverSession? = null
private var beacon: com.ttstd.lancast.receiver.discovery.HostBeacon? = null private var beacon: com.ttstd.lancast.receiver.discovery.HostBeacon? = null
/** 当前投影实例;必须持有引用,销毁时显式 stop(),否则会残留为「当前投影」。 */
private var projection: MediaProjection? = null
private var projectionCallback: MediaProjection.Callback? = null
/** 保护 [session] / [projection] / [generation] / [starting] 的状态锁。 */
private val stateLock = Any()
/**
* 会话世代号,每次启动或销毁时递增。后台启动线程持旧世代号时不再操作投影,
* 避免上一路 MediaProjection 已被新一路顶掉后仍去 createVirtualDisplay。
*/
private var generation = 0
/** 正在创建投影 / 虚拟显示(尚未成功也未失败)。用于拦截重复启动请求。 */
private var starting = false
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
createNotificationChannel() createNotificationChannel()
@@ -112,55 +128,100 @@ class MediaProjectionService : Service() {
} }
private fun startProjectionSession(resultCode: Int, data: Intent, host: String, signalingUrl: String) { private fun startProjectionSession(resultCode: Int, data: Intent, host: String, signalingUrl: String) {
stopProjectionSession() val gen = synchronized(stateLock) {
try { // 系统同一时刻只允许一路 MediaProjection 处于活动状态:再调一次 getMediaProjection
val manager = getSystemService(MediaProjectionManager::class.java) // 会立刻让上一路失效,其 createVirtualDisplay 便抛
val projection = manager.getMediaProjection(resultCode, data) // "Cannot create VirtualDisplay with non-current MediaProjection"。
if (projection == null) { if (starting || session != null) {
Toast.makeText(this, "MediaProjection 授权失败", Toast.LENGTH_SHORT).show() Log.w(TAG, "忽略重复启动请求(starting=$starting, running=${session != null})")
stopSelf()
return return
} }
starting = true
++generation
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val manager = getSystemService(MediaProjectionManager::class.java)
projection.registerCallback(object : MediaProjection.Callback() { val created = try {
override fun onStop() { manager?.getMediaProjection(resultCode, data)
Log.i(TAG, "MediaProjection session stopped by system") } catch (e: Exception) {
Log.e(TAG, "getMediaProjection failed", e)
null
}
if (created == null) {
Toast.makeText(this, "MediaProjection 授权失败,请重新授权", Toast.LENGTH_SHORT).show()
stopProjectionSession()
stopSelf()
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() stopProjectionSession()
stopSelf() stopSelf()
} }
}, Handler(Looper.getMainLooper()))
}
startBeacon()
session = ReceiverSession(
context = this,
projection = projection,
hostOverride = host,
signalingUrl = signalingUrl,
certificatePem = "",
)
// 连接建立包含 TCP 握手,必须在后台线程执行,避免服务主线程 ANR。
Thread {
try {
session?.start()
isRunning = true
} catch (e: Exception) {
Log.e(TAG, "Failed to start receiver session", e)
Handler(Looper.getMainLooper()).post {
Toast.makeText(this@MediaProjectionService, "连接失败: ${e.message}", Toast.LENGTH_SHORT).show()
}
stopProjectionSession()
stopSelf()
} }
}.start() }
} catch (e: Exception) {
Log.e(TAG, "Failed to start MediaProjection session", e)
Toast.makeText(this, "启动屏幕投影失败: ${e.message}", Toast.LENGTH_SHORT).show()
stopSelf()
} }
projection = created
projectionCallback = callback
created.registerCallback(callback, Handler(Looper.getMainLooper()))
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()
} }
/** 启动失败:只有仍是当前世代时才拆会话,避免误杀新会话。 */
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 应答。 */ /** 开启 UDP 信标:一边广播自身,一边收集主控端的 host 应答。 */
private fun startBeacon() { private fun startBeacon() {
if (beacon != null) return if (beacon != null) return
@@ -179,8 +240,29 @@ class MediaProjectionService : Service() {
} }
private fun stopProjectionSession() { private fun stopProjectionSession() {
synchronized(stateLock) {
// 递增世代号,让仍在启动流程里的后台线程失效,不再碰已被顶掉的投影。
++generation
starting = false
}
session?.stop() session?.stop()
session = null session = null
val callback = projectionCallback
val current = projection
projectionCallback = null
projection = null
if (callback != null && current != null) {
runCatching { current.unregisterCallback(callback) }
.onFailure { Log.w(TAG, "unregisterCallback failed", it) }
}
// 必须显式 stop():否则系统仍把上一路投影视为「当前」投影,
// 下一次 createVirtualDisplay 会抛 non-current MediaProjection。
if (current != null) {
runCatching { current.stop() }
.onFailure { Log.w(TAG, "projection.stop() failed", it) }
}
beacon?.stop() beacon?.stop()
beacon = null beacon = null
com.ttstd.lancast.receiver.discovery.HostBeacon.resetHost() com.ttstd.lancast.receiver.discovery.HostBeacon.resetHost()
@@ -59,11 +59,28 @@ class ReceiverSession(
val width = maxOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1920) val width = maxOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1920)
val height = minOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1080) val height = minOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1080)
encoder.start(width, height, 30, bitrateMbps * 1_000_000, preferH265) try {
val surface = encoder.inputSurface ?: return startCapture(width, height, metrics.densityDpi)
capturer = ScreenCapturer(projection, surface, metrics.densityDpi).also { it.start(width, height) } startPublishing(width, height)
clipboard.start { text -> transport?.sendControl(ControlEvent.Clipboard(text)) } } catch (e: Exception) {
// 启动失败必须彻底释放已申请的编码器/虚拟显示,否则会残留并阻塞下次启动。
running = false
stop()
throw e
}
}
/** 建立采集链路:编码器 + 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) }
clipboard.start { text -> transport?.sendControl(ControlEvent.Clipboard(text)) }
}
/** 发布设备信息 / 音频采集 / 拨号线程。 */
private fun startPublishing(width: Int, height: Int) {
val device = AnnouncedDevice( val device = AnnouncedDevice(
id = UUID.randomUUID().toString(), id = UUID.randomUUID().toString(),
name = "Android Receiver", name = "Android Receiver",