I used the open source code of Android's Wear OS Exercise Sample to create an exercise program. Its function is to stop exercising immediately when the time is equal to the number of seconds I set. But when the watch enters ambient mode, the program cannot be effectively stopped. How can I solve this problem?
This is the main code:
private suspend fun sixMinTrain(second: Int = 30) {
val duration = activeDurationCheckpoint.displayDuration(
Instant.now(),
cachedExerciseState
)
Log.d(TAG, "state = $cachedExerciseState")
//擷取總秒數,當秒數=360時重製計時器並發出警示音
if (cachedExerciseState == ExerciseState.ACTIVE) {
val totalSecond = duration.seconds.toInt()
Log.d(TAG, "sec = ${duration.seconds}")
if (totalSecond == second) {
Log.d(TAG, "update")
// 呼叫exerciseService停止運動
val service = checkNotNull(serviceConnection.exerciseService)
service.endExercise()
wakeUpScreen()
//更新錶面的時間
updateChronometer()
//撥放警示音
playSoundAsync()
}
}
}
This is ambient mode code
inner class AmbientModeHandler {
internal fun onAmbientEvent(event: AmbientEvent) {
when (event) {
is AmbientEvent.Enter -> onEnterAmbient()
is AmbientEvent.Exit -> onExitAmbient()
is AmbientEvent.Update -> onUpdateAmbient()
}
}
private fun onEnterAmbient() {
// Note: Apps should also handle low-bit ambient and burn-in protection.
unbindViewsFromService()
setAmbientUiState(true)
performOneTimeUiUpdate()
Log.d(TAG, "onEnterAmbient")
}
private fun onExitAmbient() {
performOneTimeUiUpdate()
setAmbientUiState(false)
bindViewsToService()
Log.d(TAG, "onExitAmbient")
}
private fun onUpdateAmbient() {
performOneTimeUiUpdate()
Log.d(TAG, "onUpdateAmbient")
}
}
This is where I set up the program
private fun bindViewsToService() {
if (uiBindingJob != null) return
uiBindingJob = viewLifecycleOwner.lifecycleScope.launch {
serviceConnection.repeatWhenConnected { service ->
// Use separate launch blocks because each .collect executes indefinitely.
launch {
service.exerciseState.collect {
updateExerciseStatus(it)
}
}
launch {
service.latestMetrics.collect {
it?.let {
updateMetrics(it)
}
sixMinTrain()
}
}
I tried replacing other timers, but found that the problem was not this. The same problem would occur as soon as I entered ambient mode.