I'm developing an app with Kotlin and Jetpack Compose.
I have to show an alertDialog after a certain time, everything works fine while the app is in the foreground, but, if the time ends while the app is in the background, when I go back to the app the dialog doesn't appear. Only the faded background is shown but not the dialog, and I can't interact with the app. I noticed that the dialog reappears if I rotate the device, probably because a configuration change is triggered. I just want to show the dialog after a certain time and the time runs even if the app is in the background.
I tested the code below on two emulators (Pixel 2 Api 30 and Pixel C Api 30) and the problem does not exist, while in my real device (Xiaomi Mi A2 Api 29) there is this problem.
This is a screenshot of the app:
If I click the button after some time the alertDialog appears:
but If I click the button and then I navigate out of the app and the time finishes, when I go back to the app, this is the result:
This is the code:
MainScreen.kt
@Composable
fun MainScreen(
viewModel: MainViewModel = hiltViewModel()
) {
val uiState = viewModel.uiState.collectAsState()
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Button(onClick = { viewModel.showDialogAfterSomeTime() }) {
Text(text = "Show Dialog After Some Time")
}
}
if (uiState.value.showDialog) {
AlertDialog(
onDismissRequest = { /*TODO*/ },
confirmButton = {
TextButton(onClick = { /*TODO*/ }) {
Text(text = "Ok")
}
},
title = {
Text(text = "Title")
},
text = {
Text(text = "Text")
}
)
}
}
MainViewModel.kt
data class MainScreenUiState(val showDialog: Boolean)
@HiltViewModel
class MainViewModel @Inject constructor() : ViewModel() {
private val _uiState = MutableStateFlow(MainScreenUiState(showDialog = false))
val uiState = _uiState.asStateFlow()
fun showDialogAfterSomeTime() {
viewModelScope.launch {
delay(4000)
_uiState.update { MainScreenUiState(showDialog = true) }
}
}
}
Thanks.