Я хочу написать всегда на приложении для ОС. Мои часы Samsung используют Android 14.0. < /P>
Минимальный SDK установлен на 29, Target и Compillise SDK до 35. < /P>
Добавлен разрешение Wake_lock в Manifest. Методы AmbientLifeCycleCallback не вызываются. < /P>
Что я делаю неправильно?class MainViewModel : ViewModel() {
private val modeMutableStateFlow = MutableStateFlow("Interactive")
private val counterMutableStateFlow = MutableStateFlow(0)
val modeStateFlow = modeMutableStateFlow.asStateFlow()
val counterStateFlow = counterMutableStateFlow.asStateFlow()
fun updateMode(ambient: Boolean) {
modeMutableStateFlow.update { if(ambient) "Ambient" else "Interactive" }
}
fun updateCounter() {
counterMutableStateFlow.update { counterMutableStateFlow.value + 1 }
}
}
< /code>
mainactivity.kt
class MainActivity : ComponentActivity() {
private val vm: MainViewModel by viewModels()
private val callbacks = object : AmbientLifecycleObserver.AmbientLifecycleCallback {
override fun onEnterAmbient(ambientDetails: AmbientLifecycleObserver.AmbientDetails) {
// ... Called when moving from interactive mode into ambient mode.
Log.i(this.javaClass.simpleName, "enter ambient")
vm.updateMode(ambient = true)
}
override fun onExitAmbient() {
// ... Called when leaving ambient mode, back into interactive mode.
Log.i(this.javaClass.simpleName, "exit ambient")
vm.updateMode(ambient = false)
}
override fun onUpdateAmbient() {
// ... Called by the system in order to allow the app to periodically
// update the display while in ambient mode. Typically the system will
// call this every 60 seconds.
Log.i(this.javaClass.simpleName, "update ambient")
vm.updateCounter()
}
}
private val ambientObserver = AmbientLifecycleObserver(this, callbacks)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycle.addObserver(ambientObserver)
setContent {
AlwaysOnTheme {
vm.WearApp()
}
}
}
override fun onDestroy() {
lifecycle.removeObserver(ambientObserver)
super.onDestroy()
}
}
@Composable
fun MainViewModel.WearApp() {
val mode by modeStateFlow.collectAsState()
val counter by counterStateFlow.collectAsState()
Column(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colors.background),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text(text = mode)
Text(text = counter.toString())
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... get-called