Поэтому я подумал, что буду слушать изменения, когда пользователь переключает состояние, как показано на рисунке. видео, и как только оно включено, я продолжаю.
В настоящее время взаимодействие с пользователем ужасное, потому что единственный способ — перезапустить приложение.
манифест
Код: Выделить всё
Код: Выделить всё
class LocationBroadCast(private val onProviderStatusChanged: (Boolean) -> Unit): BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
try {
val locationManager = context.getSystemService(LOCATION_SERVICE) as LocationManager
val isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
android.util.Log.i("STATUS", "$isGPSEnabled") // THIS never logs
onProviderStatusChanged(isGPSEnabled)
} catch (ex: Exception) {
}
}
}
Код: Выделить всё
@Composable
private fun RequestEnableLocationDialog(
context: Context,
onRequestPermissionResult: (Boolean) -> Unit) {
val locationProviderChangedReceiver = LocationBroadCast(onRequestPermissionResult)
LocalBroadcastManager.getInstance(context)
.registerReceiver(locationProviderChangedReceiver, IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION))
DisposableEffect(Unit) {
onDispose {
LocalBroadcastManager.getInstance(context)
.unregisterReceiver(locationProviderChangedReceiver)
}
}
val openSettingsLauncher =
rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartActivityForResult(),
) { result ->
android.util.Log.i("result", "${result} ${result.resultCode}")
if (result.resultCode == RESULT_OK) {
// Check if location is enabled after user exits Settings
if (locationEnabled(context)) {
// Location is enabled, relaunch LocationPicker
onRequestPermissionResult(true)
}
}
}
AlertDialog(
onDismissRequest = { onRequestPermissionResult(false) },
title = { Text(text = "Location") },
text = { Text(text = "Description") },
confirmButton = {
TextButton(
onClick = {
openSettingsLauncher.launch(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
},
) {
Text(text = "Enable Location in Device Settings")
}
},
dismissButton = {
TextButton(
onClick = { onRequestPermissionResult(false) },
) {
Text(text = "Cancel")
}
},
)
}
Подробнее здесь: https://stackoverflow.com/questions/781 ... on-and-off