You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Geolocater请求用户权限时出现Permission denied问题

问题说明

尝试获取用户当前位置作为Google Maps相机起始位置,已在Android Manifest中添加以下权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

但运行应用时抛出SecurityException,提示定位权限被拒绝。

解决方案

Android 6.0(API 23)及以上版本中,定位权限属于危险权限,仅在Manifest中声明无法直接生效,必须动态向用户申请授权。

  • 步骤1:动态申请权限
    前台定位需申请ACCESS_FINE_LOCATION或ACCESS_COARSE_LOCATION;若需后台定位(Android 10+),需额外申请ACCESS_BACKGROUND_LOCATION(需用户明确授权)。推荐使用Activity Result API实现权限申请:

    // 在Activity/Fragment中注册权限申请回调
    private val locationPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { results ->
        val hasFineLocation = results[Manifest.permission.ACCESS_FINE_LOCATION] ?: false
        val hasCoarseLocation = results[Manifest.permission.ACCESS_COARSE_LOCATION] ?: false
    
        if (hasFineLocation || hasCoarseLocation) {
            // 权限授权成功,执行获取位置逻辑
            startLocationFetch()
        } else {
            // 权限被拒绝,引导用户到设置页开启
            Toast.makeText(this, "需开启定位权限才能显示当前位置", Toast.LENGTH_SHORT).show()
        }
    }
    
    // 发起权限申请
    fun requestLocationPermissions() {
        val permissions = mutableListOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )
        // Android 10+需要后台定位时添加对应权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            permissions.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
        }
        locationPermissionLauncher.launch(permissions.toTypedArray())
    }
    
  • 步骤2:检查权限状态再执行定位逻辑
    在调用定位API前,先检查权限是否已授予,避免直接触发异常:

    fun startLocationFetch() {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED ||
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            // 执行获取当前位置并设置Google Maps相机的逻辑
            // 例如使用FusedLocationProviderClient获取位置
        }
    }
    
  • 步骤3:处理后台定位权限(可选)
    Android 10+中,ACCESS_BACKGROUND_LOCATION权限无法通过常规弹窗直接申请,需引导用户到应用设置页面手动开启:

    fun openAppSettings() {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
            data = Uri.fromParts("package", packageName, null)
        }
        startActivity(intent)
    }
    

内容的提问来源于stack exchange,提问作者Ronit Kataria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 21:48:14