【问题标题】:Asking for location permission, grantResults is empty请求位置权限,grantResults 为空
【发布时间】:2018-03-11 18:06:24
【问题描述】:

我在请求位置许可时遇到了一些问题。该活动扩展了 AppCompatActivity

这是请求

if (ActivityCompat.checkSelfPermission(this,
    android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

    ActivityCompat.requestPermissions(this,
    arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_RC)

    return
}

这就是我检查响应的方式

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    if (requestCode == LOCATION_PERMISSION_RC) {
        if (grantResults.isNotEmpty()) {
            if ( grantResults[0] == PackageManager.PERMISSION_GRANTED ) {
                // permission was granted
                Toast.makeText(this, "Permission granted", Toast.LENGTH_LONG).show()
                setUpMap()
                startLocationUpdates()
            } else {
                Toast.makeText(this, "Permission denied", Toast.LENGTH_LONG).show()
            }
        } else {
            Toast.makeText(this, "grantResults is empty", Toast.LENGTH_LONG).show()
        }
    }
}

如果我授予权限,应用程序会显示 toast 消息,其中说 grantArray 为空,但实际上已授予权限,我可以使用 MyLocation 层。

根据documentation

grantResults - int:授予相应权限的结果,即PERMISSION_GRANTEDPERMISSION_DENIED。从不null

当我得到一个空数组时。

这不是一个真正的问题,因为它足以移除吐司,但我想了解为什么会发生这种情况以及如何解决这种行为。

编辑:

我已经添加了更多调试行,每个 if 语句中的日志消息和 onRequestPermissionsResult() 中的第一条指令,我发现随着包含地图的活动开始,onRequestPermissionsResult() 是调用并且grantResults 为空,因为我尚未授予或拒绝该权限。现在,当我点击Allow 时,函数onRequestPermissionsResult() 被第二次调用,在这种情况下会显示消息Permission granted

新的疑问是:函数onRequestPermissionsResult()在活动开始时被调用是否正常? ActivityCompat.checkSelfPermission() 会触发 onRequestPermissionsResult() 检查权限吗?

【问题讨论】:

  • .isNotEmpty() kt 的函数 ??或您的 custom function 。 PS。我用java编写代码。
  • 这是一个kt函数,相当于if( grantResults.size() &gt; 0)
  • 你把第一个调试点放在哪里了??是在 checkSelfPermission 上吗??
  • 我把所有的日志都放在onRequestPermissionsResult()里面
  • 用红点调试..可以正确理解流程..!!

标签: android google-maps kotlin android-permissions


【解决方案1】:

我认为您的许可请求因某种原因被取消了。

// 如果请求被取消,结果数组为空。 https://developer.android.com/training/permissions/requesting#handle-response

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 2017-09-13
    • 2016-12-06
    • 2015-12-07
    • 2014-11-17
    • 2021-08-18
    相关资源
    最近更新 更多