fix: 修复 MainActivity 多行字符串格式和 UI 线程安全问题

- 使用 Kotlin 原始字符串语法替代错误的拼接格式
- 修复 stopCamera() 中 UI 更新不在主线程的问题
- 添加 cameraHelper 重复启动检查

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
let5sne.win10
2026-02-12 22:39:42 +08:00
parent 0699931fd4
commit e9741b4dd2

View File

@@ -48,8 +48,11 @@ class MainActivity : AppCompatActivity() {
Toast.makeText(this, "图片已保存到相册", Toast.LENGTH_SHORT).show() Toast.makeText(this, "图片已保存到相册", Toast.LENGTH_SHORT).show()
} }
// 自动启动 if (ContextCompat.checkSelfPermission(
if (checkPermission()) { this,
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED
) {
startCamera() startCamera()
} }
} }
@@ -68,15 +71,23 @@ class MainActivity : AppCompatActivity() {
} }
private fun startCamera() { private fun startCamera() {
if (cameraHelper != null) return
mjpegServer = MjpegServer(8080)
cameraHelper = CameraHelper(this) { frame, _, _ -> cameraHelper = CameraHelper(this) { frame, _, _ ->
mjpegServer?.updateFrame(frame) mjpegServer?.updateFrame(frame)
} }
mjpegServer = MjpegServer(8080) // Start the server and update UI once started
mjpegServer?.start { mjpegServer?.start {
runOnUiThread { runOnUiThread {
findViewById<TextView>(R.id.tv_status).text = findViewById<TextView>(R.id.tv_status).text = """
"服务运行中端口: 8080IP: 无需IP (ADB模式)USB连接命令:adb forward tcp:8080 tcp:8080" 服务运行中
端口: 8080
IP: 无需IP (ADB模式)
USB连接命令:
adb forward tcp:8080 tcp:8080
""".trimIndent()
findViewById<Button>(R.id.btn_start).isEnabled = false findViewById<Button>(R.id.btn_start).isEnabled = false
findViewById<Button>(R.id.btn_stop).isEnabled = true findViewById<Button>(R.id.btn_stop).isEnabled = true
} }
@@ -87,12 +98,16 @@ class MainActivity : AppCompatActivity() {
private fun stopCamera() { private fun stopCamera() {
cameraHelper?.stop() cameraHelper?.stop()
cameraHelper = null
mjpegServer?.stop() mjpegServer?.stop()
mjpegServer = null
runOnUiThread {
findViewById<TextView>(R.id.tv_status).text = "服务已停止" findViewById<TextView>(R.id.tv_status).text = "服务已停止"
findViewById<Button>(R.id.btn_start).isEnabled = true findViewById<Button>(R.id.btn_start).isEnabled = true
findViewById<Button>(R.id.btn_stop).isEnabled = false findViewById<Button>(R.id.btn_stop).isEnabled = false
} }
}
override fun onDestroy() { override fun onDestroy() {
super.onDestroy() super.onDestroy()