如何检查 API 级别 23 下的权限?

How can I check permission under API level 23?

我的一个应用程序有权限 RECORD_AUDIO 而我的应用程序的 targetSdkVersion 是 22。我无法在运行时检查权限。但我注意到如果我在 Android 6.0 及更高版本中安装我的应用程序。用户可以在系统应用权限设置中手动拒绝权限。所以我的问题是如何检查我的应用是否在 API 级别 23 下获得 grand Audio 许可?

我找了好久,只在Android M.

中找到一些document关于如何检查权限的内容

我注意到上下文有一个函数 checkCallingOrSelfPermission, but it's behavior is strange under Android 6.0. I am using the solution from here。但是我在系统应用程序设置中手动关闭应用程序权限之后。我得到的结果不是我所期望的。

String permission = "android.permission.RECORD_AUDIO";
int ret = context.checkCallingPermission(permission);

忘了说:

minSdkVersion 9
targetSdkVersion 22

编辑:

我注意到有一个 是将 v4 支持库升级到 v23。升级我的 v4 支持库会有点复杂。所以我想要另一个解决方案。

在API22及以下:

int permission = PermissionChecker.checkSelfPermission(context, permission);

if (permission == PermissionChecker.PERMISSION_GRANTED) {
    // good to go
} else {
    // permission not granted, you decide what to do
}

在API23岁及以上:

来自文档:

If your app needs a dangerous permission, you must check whether you have that permission every time you perform an operation that requires that permission. The user is always free to revoke the permission, so even if the app used the camera yesterday, it can't assume it still has that permission today.

To check if you have a permission, call the ContextCompat.checkSelfPermission() method. For example, this snippet shows how to check if the activity has permission to write to the calendar:

// Assume thisActivity is the current activity
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
        Manifest.permission.WRITE_CALENDAR);

If the app has the permission, the method returns PackageManager.PERMISSION_GRANTED, and the app can proceed with the operation. If the app does not have the permission, the method returns PERMISSION_DENIED, and the app has to explicitly ask the user for permission.

https://developer.android.com/training/permissions/requesting.html

请仔细阅读此 link 将指导您如何设置权限并减少您实施权限的工作

您需要查看 System PermissionsRequesting Permissions

危险权限和特殊权限示例 https://github.com/henrychuangtw/AndroidRuntimePermission

对于 Api 22 及更低版本,如果我没记错的话,你不需要在运行时检查权限,你只需在 AndroidManifest 添加它们,应用程序会询问这个第一次安装时只允许一次。所以可能你需要检查你的 AndroidManifest,你能把这个添加到这里吗?

如果您想在 Api 23 以及更低版本上使用您的应用程序:

您可以尝试使用if语句检查Sdk版本,如果是23或更高版本,则在运行时请求dungerous权限。

if (android.os.Build.VERSION.SDK_INT > 23) { /*Ask Dungerous Permissions here*/ }

也许它会解决 Api 22 和更低版本的问题。

您可以从 Requesting Permissions at Run Time

查看如何请求 runetime 权限

此外,您还必须将 Api 23 编译添加到您的应用程序中,并将您的目标设置为 Api 23.

编辑:现在我看到你提到了,将你的支持库升级到 v23 很复杂,但我不明白为什么。您只需要安装一些 SDK 并将一些字符串添加到 gradle。您是否使用自定义支持库之类的东西?