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权限。只有一个案例会出现一个对话框。
为什么会这样?
谢谢!
答案 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级别,您都应该测试您的应用,以验证其在缺少所需权限时是否正常运行。
在询问多重权限时要记住的事项:
答案 2 :(得分:0)
您的代码运行正常。在运行时权限的Java代码中没有问题。检查清单后,您是否添加了该行?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>