我正在尝试专门针对Android sdk测试运行时权限> 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
。在应用程序的设置中,虽然显示了无权限授予/请求。
我错过了什么或做错了吗?谢谢你的帮助。
答案 0 :(得分:2)
所以在这里。我发现对于android sdk > 22
,虽然运行时权限是以编程方式为您的应用程序添加的,但仍然需要在AndroidManifest.xml
文件中声明您的应用程序权限。所以,在添加代码之后:
<uses-permission android:name="android.permission.WRITE_CALENDAR"/>
在AndroidManifest.xml
中,应用程序要求获得许可,并且最终正常运行。
有关更多信息:Android M permission dialog not showing
谢谢所有人帮助我。
答案 1 :(得分:0)
您错过了代码的顺序。检查一下:
@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
}
}
有一点不同,即使在您知道正在讨论CALENDAR权限之前,您也会询问是否已授予权限。因此,您应首先检查当前的权限响应是否是您想要的,然后检查是否授予了权限。
来源:https://developer.android.com/training/permissions/requesting.html