fix: 阻塞调用包裹 withContext(IO) 使 withTimeout 可正确中断

- 步骤1 wifiDirect.initialize() 是同步阻塞调用,withTimeout 无法中断
- 改为 withTimeout(5000L) { withContext(Dispatchers.IO) { ... } }
- 超时后协程在 IO 线程被取消,TimeoutCancellationException 正确到达 catch
- 步骤2-5 同样加 withContext 防御性包裹
This commit is contained in:
2026-05-31 11:39:12 +08:00
parent ee29bd01bf
commit 788e196d48

View File

@@ -218,13 +218,15 @@ class AirDisplayManager(private val context: Context) {
_uiState.update { it.copy(serviceState = ServiceState.Initializing) }
try {
// 1. Wi-Fi Direct
// 1. Wi-Fi Direct(阻塞调用,用 withContext+withTimeout 可正确中断)
Log.w(TAG, " 步骤1: wifiDirect.initialize()")
try {
withTimeout(5000L) { wifiDirect.initialize() }
withTimeout(5000L) {
withContext(Dispatchers.IO) { wifiDirect.initialize() }
}
Log.w(TAG, " 步骤1: 完成")
} catch (e: TimeoutCancellationException) {
Log.w(TAG, " 步骤1: 超时5秒")
Log.w(TAG, " 步骤1: 超时5秒Wi-Fi Direct 不可用")
} catch (e: Exception) {
Log.w(TAG, " 步骤1: 失败(非致命): ${e.message}")
}
@@ -232,7 +234,7 @@ class AirDisplayManager(private val context: Context) {
// 2. 启动 ADP
Log.w(TAG, " 步骤2: adp.start()")
try {
withTimeout(5000L) { adp.start(AirDisplayProtocol.DEFAULT_PORT) }
withTimeout(5000L) { withContext(Dispatchers.IO) { adp.start(AirDisplayProtocol.DEFAULT_PORT) } }
Log.w(TAG, " 步骤2: 完成")
} catch (e: TimeoutCancellationException) {
Log.w(TAG, " 步骤2: 超时5秒")
@@ -243,7 +245,7 @@ class AirDisplayManager(private val context: Context) {
// 3. 注册 mDNS
Log.w(TAG, " 步骤3: mdns.register()")
try {
withTimeout(3000L) { mdns.register() }
withTimeout(3000L) { withContext(Dispatchers.IO) { mdns.register() } }
Log.w(TAG, " 步骤3: 完成")
} catch (e: TimeoutCancellationException) {
Log.w(TAG, " 步骤3: 超时3秒")
@@ -254,7 +256,7 @@ class AirDisplayManager(private val context: Context) {
// 4. 启动 RTSP
Log.w(TAG, " 步骤4: rtsp.start()")
try {
withTimeout(5000L) { rtsp.start() }
withTimeout(5000L) { withContext(Dispatchers.IO) { rtsp.start() } }
Log.w(TAG, " 步骤4: 完成")
} catch (e: TimeoutCancellationException) {
Log.w(TAG, " 步骤4: 超时5秒")
@@ -265,7 +267,7 @@ class AirDisplayManager(private val context: Context) {
// 5. 发现设备
Log.w(TAG, " 步骤5: wifiDirect.startDiscovery()")
try {
withTimeout(3000L) { wifiDirect.startDiscovery() }
withTimeout(3000L) { withContext(Dispatchers.IO) { wifiDirect.startDiscovery() } }
} catch (e: TimeoutCancellationException) {
Log.w(TAG, " 步骤5: 超时3秒")
} catch (e: Exception) {