Handler(Looper.getMainLooper()).postDelayed({
if (AndroidManager.bluetoothMicrophone()) {
aigcSpeech.speaking("蓝牙麦克风连接")
}
Log.d(TAG, "Bluetooth connected")
}, 3000)
private val handler = object : Handler(Looper.myLooper()!!) {
override fun handleMessage(msg: Message) {
when (msg.what) {
// 处理计时逻辑
START -> {
// 计算时间
val hours = seconds / 3600
val minutes = (seconds % 3600) / 60
val secs = seconds % 60
val time = if (hours == 0) {
String.format("%02d:%02d", minutes, secs)
} else {
String.format("%02d:%02d:%02d", hours, minutes, secs)
}
// 更新UI
lifecycleScope.launch {
phoneBinding?.textViewTimer?.text = time
}
seconds++
// 继续发送下一次计时消息(形成循环)
sendEmptyMessageDelayed(START, 1000)
}
// 处理停止指令
STOP -> {
// 移除所有未处理的消息,终止循环
removeCallbacksAndMessages(null)
seconds = 0 // 重置计时
}
}
}
}
// 消息类型常量
private const val START = 1 // 计时 tick
private const val STOP = 2 // 停止指令
private var seconds = 0
// 启动计时器
private fun startTimer() {
seconds = 0
// 发送第一个计时消息,启动循环
handler.sendEmptyMessage(START)
}
// 停止计时器(通过发送停止消息)
private fun stopTimer() {
handler.sendEmptyMessage(STOP)
}