Android 5.1.1上不会自动授予ACCESS_COARSE_LOCATION

时间:2017-06-27 13:44:38

标签: android android-permissions android-5.1.1-lollipop

我正在检查应用程序是否因Android M而授予ACCESS_COARSE_LOCATION权限。据我所知,版本低于Marshmallow的设备会自动授予安装所有权限。

但是,如果我添加这段代码,它会在Android 5.1.1上返回false

if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)

是否因为我用于测试的设备完全禁止访问所有应用的位置?

2 个答案:

答案 0 :(得分:0)

代替此:

if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
 == PackageManager.PERMISSION_GRANTED)

使用此:

if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
 == PackageManager.PERMISSION_GRANTED)

对于低于6.0的设备,如果检查粗略位置,您将获得权限被拒绝(-1)。

答案 1 :(得分:-1)

实际上Android最低sdk版本21-22,即5.0不需要检查权限,但是当我们必须在不同的手机上测试我们的应用程序时,例如。在最低sdk版本23上,即在棉花糖上。您需要在应用程序外部检查权限。

在您的Starting_Activity中写下以下代码

//requesting Permission
private void requestingPermission(){
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_NETWORK_STATE)){
        //Exaplian here why you need this permission
    }
    //Ask for the permission
    ActivityCompat.requestPermissions(this,new String[]{ 
            Manifest.permission.ACCESS_NETWORK_STATE, },STORAGE_PERMISSION_CODE);
}

现在添加另一个

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    //checking the request code of Permission request
    if (requestCode == STORAGE_PERMISSION_CODE){
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){//Toast.makeText(getApplicationContext(),"Permission Granted",Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(getApplicationContext(),"Permission Denied",Toast.LENGTH_SHORT).show();
        }
    }
}

请勿在您的活动onCreate()方法

中忘记调用以下方法
requestingPermission();