Android中的运行时权限出错

时间:2018-03-17 07:24:15

标签: android permissions kotlin

Hiii,当我在我的应用程序中创建运行时权限时,错误消失了,这里没问题,但是当我在(onRequestPermissionsResult)方法上进行覆盖,并确保按用户提供Premission时,也会显示Error关于许可?为什么?我怎么能克服它?:这个错误是:

Call required permission which maybe rejected by user: code should explicitly check to see if permission is available...etc)

这是我的代码:

private fun startLocationUpdates() {
if( ActivityCompat.checkSelfPermission(applicationContext, android.Manifest.permission.ACCESS_FINE_LOCATION)
        != PackageManager.PERMISSION_GRANTED
        && ActivityCompat.checkSelfPermission(applicationContext, android.Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED){
    ActivityCompat.requestPermissions(this@DisplayMembers, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION), REQUEST_DISP_LOC)
}else {
    //=====================//
    mFusedLocationClient?.requestLocationUpdates(LocationRequest(),
            LocationCallBack(),
            null)
    //====================//
}

}

 override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    when(requestCode){
        REQUEST_DISP_LOC -> {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                mFusedLocationClient?.requestLocationUpdates(LocationRequest(),
                        LocationCallBack(),
                        null)
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

因为在任何时候,用户都可以拒绝许可,每次查找用户的位置时,都必须检查是否允许检查权限:

if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

然后您可以根据需要检查位置:

mFusedLocationClient?.requestLocationUpdates(LocationRequest(),
                    LocationCallBack(),
                    null)

希望这会有所帮助

答案 1 :(得分:1)

您曾经在mFusedLocationClient?.requestLocationUpdates内拨打onRequestPermissionResult。只有结果数组,而不是权限详细信息。因此,您只知道首先调用哪个权限以及授予哪些权限,但android工作室不知道它。

所以你必须这样打电话:

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    when(requestCode){
        REQUEST_DISP_LOC -> {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               startLocationUpdates()
            }
        }
    }
}