我正在尝试将我的应用设置为使用运行时权限。我的请求对话框显示正常,但是当我在对话框中选择“接受”并调用onRequestPermissionsResult时,grantResults不会显示PERMISSION_GRANTED,并且应用程序不会获得权限。以下是我要求许可的方式:
ActivityCompat.requestPermissions((Activity) contnext,
new String[]{Manifest.permission.MANAGE_DOCUMENTS, Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
回调:
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode){
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// do good stuff
Log.i("net.bradmont.prayson", "Permissions granted by user");
} else {
Log.i("net.bradmont.prayson", "Permissions refused by user");
Log.i("net.bradmont.prayson", "grantResults.length " + grantResults.length);
for (int i = 0; i < grantResults.length; i++){
Log.i("net.bradmont.prayson", "grantResults[" + i +"]" + grantResults.length);
}
Snackbar snackbar1 = Snackbar.make(mCoordinator,
R.string.cant_open_file_no_permission, Snackbar.LENGTH_LONG);
snackbar1.show();
}
}
}
结果是,在接受权限对话框后,应用程序会显示错误的快餐栏。这是logcat中显示的内容:
net.bradmont.prayson I Permissions refused by user
I grantResults.length 2
I grantResults[0]2
I grantResults[1]2
我甚至无法弄清楚2在grantResults中的意义; PackageManager文档中唯一值为2的consts是COMPONENT_ENABLED_STATE_DISABLED和GET_RECEIVERS。
这到底是怎么回事?
答案 0 :(得分:1)
首先,你在循环中反复打印int[] grantResults
的长度而不是值。
for (int i = 0; i < grantResults.length; i++){
Log.i("net.bradmont.prayson", "grantResults[" + i +"]" + grantResults.length);
}
应该是:
for (int i = 0; i < grantResults.length; i++){
Log.i("net.bradmont.prayson", "grantResults[" + i +"]" + grantResults[i]);
}
其次,正如CommonsWare所说,Manifest.permission.MANAGE_DOCUMENTS
是Protection level: signature
,这意味着This permission cannot be granted to third-party apps.
会看到this。
由于您的第一个请求是MANAGE_DOCUMENTS
,因此不要错过grantResults
中的第一个值不是PackageManager.PERMISSION_GRANTED
。我猜第二个值实际上是与PERMISSION_GRANTED
请求相对应的Manifest.permission.READ_EXTERNAL_STORAGE
。
长话短说,摆脱MANAGE_DOCUMENTS
请求:
ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);