【问题标题】:Unclear IDE warning for getFusedLocationClient in Android StudioAndroid Studio 中 getFusedLocationClient 的 IDE 警告不明确
【发布时间】:2021-03-31 17:38:04
【问题描述】:

我的代码在 Android Studio 中收到以下 IDE 警告:

调用需要可能被用户拒绝的权限:代码应显式检查权限是否可用(使用 checkPermission)或显式处理潜在的 SecurityException

我的代码如下所示。它应该设置一个GoogleMap 对象以正常显示带有用户位置的框架,如果他们禁用了位置(location == null)或拒绝应用程序的位置权限(addOnFailureListener),则显示整个德国的框架。

fusedLocationClient.lastLocation.addOnFailureListener(this) {
    Log.e("onRequestPermissions", "fail")
    mMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(51.17, 10.45), 6F))  // Germany
}

fusedLocationClient.lastLocation.addOnSuccessListener(this) { location ->
    Log.e("onRequestPermissions", "succ")
    if (location == null)
        mMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(51.17, 10.45), 6F))  // Germany
    else
        mMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(location.latitude, location.longitude), 13F))
}

我不明白为什么打电话给fusedLocationClient (getFusedLocationClient) 会给我这个错误信息。我以为FusedLocationProviderClient 总是在那里,我正在处理用户拒绝位置权限addOnFailureListener 内部 的情况。那么,如果我什至不允许调用getFusedLocationClient,我怎么可能附加这个失败回调。

Android Studio 用严重的“错误”和全红色文本处理此警告,这使我的代码看起来很糟糕。

【问题讨论】:

    标签: android android-studio kotlin lint


    【解决方案1】:

    为了让 Lint 知道您“知道相应的权限检查并在代码中的其他地方处理它”,将 @SuppressLint("MissingPermission") 注释添加到包含代码的方法中。 p>

    @SuppressLint 注释

    表示 Lint 应该忽略注释元素的指定警告。

    【讨论】:

    • @xjcl,在您发布的代码中,您没有进行权限检查。请参阅Request app permissions 了解更多信息。
    【解决方案2】:

    错误实际上是要求您明确检查是否启用了请求的权限,或者您可以通过向该代码添加 @SuppressLint 注释来禁用 lint 检查。

    PermissionChecker.PERMISSION_GRANTED ==
                            PermissionChecker.checkSelfPermission(
                                requireContext(),
                                Manifest.permission.ACCESS_FINE_LOCATION
                            ))
    

    或者

    @SuppressLint("MissingPermission")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 2018-03-15
      • 2013-10-27
      • 2015-11-16
      • 2022-06-17
      相关资源
      最近更新 更多