in WearSpeakerSample/wear/src/main/java/com/example/android/wearable/speaker/SpeakerApp.kt [47:145]
fun SpeakerApp() {
MaterialTheme {
lateinit var requestPermissionLauncher: ManagedActivityResultLauncher<String, Boolean>
val context = LocalContext.current
val activity = context.findActivity()
val scope = rememberCoroutineScope()
val mainState = remember(activity) {
MainState(
activity = activity,
requestPermission = {
requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
}
)
}
requestPermissionLauncher = rememberLauncherForActivityResult(RequestPermission()) {
// We ignore the direct result here, since we're going to check anyway.
scope.launch {
mainState.permissionResultReturned()
}
}
val lifecycleOwner = LocalLifecycleOwner.current
// Notify the state holder whenever we become stopped to reset the state
DisposableEffect(mainState, scope, lifecycleOwner) {
val lifecycleObserver = object : DefaultLifecycleObserver {
override fun onStop(owner: LifecycleOwner) {
super.onStop(owner)
scope.launch { mainState.onStopped() }
}
}
lifecycleOwner.lifecycle.addObserver(lifecycleObserver)
onDispose {
lifecycleOwner.lifecycle.removeObserver(lifecycleObserver)
}
}
SpeakerScreen(
playbackState = mainState.playbackState,
isPermissionDenied = mainState.isPermissionDenied,
recordingProgress = mainState.recordingProgress,
onMicClicked = {
scope.launch {
mainState.onMicClicked()
}
},
onPlayClicked = {
scope.launch {
mainState.onPlayClicked()
}
},
onMusicClicked = {
scope.launch {
mainState.onMusicClicked()
}
},
)
if (mainState.showPermissionRationale) {
AlertDialog(
title = {
Text(text = stringResource(id = R.string.rationale_for_microphone_permission))
},
positiveButton = {
Button(
onClick = {
requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
mainState.showPermissionRationale = false
}
) {
Text(text = stringResource(id = R.string.ok))
}
},
negativeButton = {
Button(
onClick = {
mainState.showPermissionRationale = false
}
) {
Text(text = stringResource(id = R.string.cancel))
}
}
)
}
if (mainState.showSpeakerNotSupported) {
ConfirmationDialog(
onTimeout = { mainState.showSpeakerNotSupported = false }
) {
Text(text = stringResource(id = R.string.no_speaker_supported))
}
}
}
}