权限请求(WRITE_EXTERNAL_STORAGE)不会显示

时间:2017-01-27 12:01:41

标签: java android permissions

Android 6

我编写了下一个检查权限的代码,如果没有这样的权限,它会要求用户提供权限。

private void checkDiskPermission ()
{
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this, "no disk access" , Toast.LENGTH_LONG).show();
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
    }
    else
    {
        Toast.makeText(this, "disk access - OK" , Toast.LENGTH_LONG).show();
    }

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this, "no GPS access" , Toast.LENGTH_LONG).show();
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0);
    }
    else
    {
        Toast.makeText(this, "GPS access - OK" , Toast.LENGTH_LONG).show();
    }
}

此代码适用于GPS权限,但不适用于WRITE_EXTERNAL_STORAGE权限。只有一个案例会出现一个对话框。

为什么会这样?

谢谢!

3 个答案:

答案 0 :(得分:1)

因为您要同时请求它2次。 这就是它提出最后请求的原因。

解决方案是您必须在一个请求中同时询问两个权限

喜欢这个 -

private void checkDiskPermission ()
{
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this, "No Permissions" , Toast.LENGTH_LONG).show();
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 0);
    }
    else
    {
        Toast.makeText(this, "Has Permissions" , Toast.LENGTH_LONG).show();
    }
}

答案 1 :(得分:1)

如果permission > 1,则必须在运行时将它们组合在一起。

根据Google的说法,从Android 6.0(API级别23)开始,用户可以随时撤消任何应用的权限,即使该应用针对较低的API级别也是如此。无论您的应用针对哪种API级别,您都应该测试您的应用,以验证其在缺少所需权限时是否正常运行。

在询问多重权限时要记住的事项:

  1. 许可数量。
  2. 永远不要再问Checkox
  3. Look at the Source for Multiple Permission Request

答案 2 :(得分:0)

您的代码运行正常。在运行时权限的Java代码中没有问题。检查清单后,您是否添加了该行?

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>