我正在尝试测试运行时权限,特别是Android > 23的运行时权限。但我的应用程序是自动授予权限的,无需询问。
注意:我使用的是sdk 24。下面是我正在使用的代码片段:
public void onCalendarClick(View view) {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) == PackageManager
.PERMISSION_DENIED) {
if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_CALENDAR)) {
//Display Explanation to the user
//For granting permissions to the app.
}
else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CALENDAR}, CALLBACK_CALENDAR);
}
}
}
@Override
public void onRequestPermissionsResult(int resultCode, String permission[], int grantResults[]) {
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast toast;
switch (resultCode) {
case CALLBACK_CALENDAR : toast = Toast.makeText(this,"Calendar Permission Granted!!",Toast.LENGTH_LONG);
toast.show(); break;
//Other Cases
}
}
}
当我单击Calendar Button
时,onCalendarClick()
方法将运行,但不需要任何许可,该应用程序将直接显示已授予的日历权限!! toast
。但是,在应用程序的设置中,不显示授予/请求的权限。
我是错过了什么还是做错了什么?谢谢你的帮助。
发布于 2017-06-05 10:55:34
所以就是这样了。我发现对于android sdk > 22
,虽然运行时权限是通过编程为您的应用程序添加的,但是仍然需要在文件中声明应用程序的权限。因此,在添加代码之后:
<uses-permission android:name="android.permission.WRITE_CALENDAR"/>
在AndroidManifest.xml
中,该应用程序请求许可,它终于开始工作了。欲知更多信息:Android M permission dialog not showing .Thanks to all For helping )
发布于 2017-06-05 10:21:24
你错过了代码的顺序。检查一下这个:
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case CALLBACK_CALENDAR: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// calendar-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
有一点不同,您在知道您正在讨论日历权限之前,就询问权限是否被授予。因此,您应该首先检查当前权限响应是否是所需的响应,然后检查权限是否被授予。
来源:https://developer.android.com/training/permissions/requesting.html
https://stackoverflow.com/questions/44374646
复制