I am requesting location permissions and even after the user granted location permissions i cannot get gps location if location settings is disabled. How can i request user to enable the location settings in jetpack compose?
val multiplePermissionsState = rememberMultiplePermissionsState(
listOf(
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_BACKGROUND_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION
)
)
Button(onClick = {
multiplePermissionsState.launchMultiplePermissionRequest()
},
modifier = Modifier.background(MaterialTheme.colors.primary)
)
Create enable location permission dialog like google map.
import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.IntentSender
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.location.*
import com.google.android.gms.tasks.Task
@Composable
fun Layout() {
val context: Context = LocalContext.current
val settingResultRequest = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartIntentSenderForResult()
) { activityResult ->
if (activityResult.resultCode == RESULT_OK)
Log.d("appDebug", "Accepted")
else {
Log.d("appDebug", "Denied")
}
}
Button(onClick = {
checkLocationSetting(
context = context,
onDisabled = { intentSenderRequest ->
settingResultRequest.launch(intentSenderRequest)
},
onEnabled = { /* This will call when setting is already enabled */ }
)
}) {
Text(text = "Request permission")
}
}
// call this function on button click
fun checkLocationSetting(
context: Context,
onDisabled: (IntentSenderRequest) -> Unit,
onEnabled: () -> Unit
) {
val locationRequest = LocationRequest.create().apply {
interval = 1000
fastestInterval = 1000
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
val client: SettingsClient = LocationServices.getSettingsClient(context)
val builder: LocationSettingsRequest.Builder = LocationSettingsRequest
.Builder()
.addLocationRequest(locationRequest)
val gpsSettingTask: Task<LocationSettingsResponse> =
client.checkLocationSettings(builder.build())
gpsSettingTask.addOnSuccessListener { onEnabled() }
gpsSettingTask.addOnFailureListener { exception ->
if (exception is ResolvableApiException) {
try {
val intentSenderRequest = IntentSenderRequest
.Builder(exception.resolution)
.build()
onDisabled(intentSenderRequest)
} catch (sendEx: IntentSender.SendIntentException) {
// ignore here
}
}
}
}