#android #google-maps #android-jetpack-compose #android-jetpack
Вопрос:
Я хочу, чтобы при выключении gps я видел диалоговое окно настроек(требуется) для включения gps, потому что моему приложению нужен GPS. Я написал код для этого и поместил его onCreate()
в основную активность, но диалоговое окно показывает мне только при запуске приложения, но я хочу видеть это диалоговое окно везде, где я выключил GPS в приложении.
val settingsClient = LocationServices.getSettingsClient(this) val locationRequest = LocationRequest() val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest) .setAlwaysShow(false) .setNeedBle(false) settingsClient.checkLocationSettings(builder.build()) .addOnCompleteListener { task -gt; if (task.isSuccessful) { val response = task.result ?: return@addOnCompleteListener val locationSettingsStates = response.locationSettingsStates Log.e("yyy", locationSettingsStates.toString()) // TODO } } .addOnFailureListener { e -gt; Timber.i("checkLocationSetting onFailure:" e.message) when ((e as ApiException).statusCode) { LocationSettingsStatusCodes.RESOLUTION_REQUIRED -gt; { Timber.i("Location settings are not satisfied. Attempting to upgrade " "location settings ") try { // Show the dialog by calling startResolutionForResult(), and check the // result in onActivityResult(). val rae = e as ResolvableApiException rae.startResolutionForResult(this, 0) } catch (sie: IntentSender.SendIntentException) { Timber.i("PendingIntent unable to execute request.") } } else -gt; { } } } }
Ответ №1:
Это способ сделать это:
Я создал класс LocationUtil:
class LocationUtil(context: Context) { companion object { const val MIN_TIME: Long = 1000L const val MIN_DISTANCE: Float = 0.0f } private val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager private var locationListener: LocationListener? = null val locationStateFlow = MutableStateFlowlt;Locationgt;(Location(LocationManager.GPS_PROVIDER)) val gpsProviderState = mutableStateOf(false) val isStart: MutableStatelt;Booleangt; = mutableStateOf(false) private val locHandlerThread = HandlerThread("LocationUtil Thread") init { locHandlerThread.start() } @SuppressLint("MissingPermission") fun start(minTimeMs: Long = MIN_TIME_MS, minDistanceM: Float = MIN_DISTANCE_M) { locationListener().let { locationListener = it locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTimeMs, minDistanceM, it, locHandlerThread.looper) } gpsProviderState.value = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) isStart.value = true } fun stop() { locationListener?.let { locationManager.removeUpdates(it) } isStart.value = false } private fun locationListener() = object : LocationListener { override fun onLocationChanged(location: Location) { locationStateFlow.value = location } override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) { } override fun onProviderEnabled(provider: String) { gpsProviderState.value = true } override fun onProviderDisabled(provider: String) { gpsProviderState.value = false } } }
и я создаю файл с некоторыми функциями:
private const val REQUEST_CODE_LOCATION_SOURCE_SETTINGS = 200 fun getLocationManager(context: Context): LocationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager fun isLocEnable(context: Context): Boolean { val locationManager = getLocationManager(context) return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) } @Composable fun IsLocationEnable(context: Context) { if (!isLocEnable(context)) { SimpleAlertDialog( title = stringResource(id = R.string.title), text = stringResource(id = R.string.dialog_gps_setting), singleButton = false, confirmText = stringResource(R.string.settings), dismissText = stringResource(R.string.cancel), onConfirm = { if (it) { Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS, Uri.fromParts( "package", context.packageName, null ) ).also { intent -gt; try { context.startActivity( intent ) } catch (e: ActivityNotFoundException) { Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS ).also { intentCatch -gt; context.startActivity( intentCatch ) } } } } }) } } @Composable fun LocationState(context: Activity) { IsLocationEnable(context) }
и, наконец, я использовал коды в основной деятельности:
Box(modifier = Modifier.fillMaxSize()) { Column(modifier = Modifier.fillMaxSize()) { ConnectivityStatus() ClientScaffold(clientNavigator) } val gpsEnable by locationUtil.gpsProviderState if (!gpsEnable) { IsLocationEnable(this@MainActivity) } }