如何在 Jetpack Compose 中启用位置信息?

3

我正在请求位置权限,即使用户已经授权位置权限,如果位置设置被禁用,我仍无法获取GPS位置。如何在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)
            ) 
2个回答

8

创建像谷歌地图一样的启用位置权限对话框。

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
            }
        }
    }
    
}

太好了!...但是如何从按钮点击调用它...当我尝试这样做时...它给我一个错误,在rememberLauncherForActivityResult中说'@Composable invocation should happen inside the @Composable function'...请帮助我解决这个问题。 - Venkataramanan
@Venkataramanan 我更新了答案,希望能对你有所帮助。祝编程愉快! - user15301088
@KunalSharma 你介意分享完整的代码片段,包括导入吗?因为你的解决方案对我不起作用。(非常感谢您的任何回复) - RickertBrandsen
如果我在 Lifecycle.Event.ON_RESUME 中调用 checkLocationSetting,有时会显示错误:“在调用 launch() 之前,您必须确保 ActivityResultLauncher 已注册。” - Arsh Doda

2

你提供的链接只是用于处理权限,而不是启用他所要求的GPG设置位置。 - Ayoub Boumzebra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接