请求应用程序运行时权限 (Android)

Requesting app runtime permissions (Android)

我想编写一个简单的应用程序来访问设备的位置。只有我会使用该应用程序。这是我大约 10 年来第一次尝试编写 Android 应用程序,所以这是我第一次不得不处理运行时权限。

我的第一个问题是,鉴于该应用仅供我使用,是否可以绕过运行时权限代码的需要?

否则,是否有任何简单的示例代码可以填补 Android documentation 中的众多空白?

举个例子:文档包括以下内容:

when {
ContextCompat.checkSelfPermission(
        CONTEXT,
        Manifest.permission.REQUESTED_PERMISSION
        ) == PackageManager.PERMISSION_GRANTED -> {
    // You can use the API that requires the permission.
    performAction(...)

这是什么意思?什么"API that requires the permission"?用什么代替“...”?

页面上还有其他几个类似的空白。

您提到该应用仅供您使用,那么您不必编写运行时权限的代码,您可以跳过它...

如何做到这一点...?

第 1 步:只需将您需要的所有权限放入应用程序清单文件并安装应用程序

第 2 步:转到 应用设置应用信息 中的 phone 并检查 app 权限 你提到的所有权限都会显示在那里,只需手动切换它们

这就是现在编写代码来访问您应该在获得许可后编写的内容

is it possible to by-pass the need for runtime permission code?

您仍然需要 <uses-permission> 元素。但您可以通过“设置”应用手动授予您的应用权限。

运行时权限代码的要点是向用户请求权限并防止未授予该权限的情况。在你的情况下,如果你的应用程序因为你撤销了权限而崩溃,你可以对开发人员大喊大叫。反过来,作为开发人员的您可以对作为用户的您大喊大叫,因为您未能手动授予权限。因为你会对自己大吼大叫,所以建议在一个私人的地方这样做,或者在你的耳朵里戴上蓝牙耳机作为掩护。 :-)

What does this mean?

我们请求运行时权限,因为我们想使用一些受此类权限保护的 Android API。我们通常不请求运行时权限,因为有一天早上我们醒来后认为请求运行时权限听起来是一件非常有趣的事情。

What "API that requires the permission"? What replaces the "..."?

在您的情况下,它似乎是 LocationManager 上的方法或使用来自 Google Play 服务的融合位置 API 的内容。

is there any simple example code that fills in the numerous gaps in the Android documentation?

问题是 "example code" 有 5% 与许可相关,而 95% 无论您使用什么都需要许可。任何仅显示权限的示例代码都将具有您不喜欢文档中的相同手动波浪形内容。在您的情况下,任何使用位置 APIs 的最新示例还应显示运行时权限元素。

FWIW,this directory contains several sample projects from this book that show getting the location. They are a bit old but do show requesting runtime permissions (mostly contained in an AbstractPermissionActivity). This sample is newer and in Kotlin, but it is for file-access permissions, not for locations (and is covered in this other book).

  1. 如果您想避免 运行 时间许可请求,您可以使用 Android 低于 23(Android 6 Marshmellow)
  2. 的 SDK 版本构建您的应用

  1. Android API 23 级或以上(在清单文件中添加权限后):

首先,将您的权限添加到 AndroidManifest.xml 文件:

<uses-permission android:name="android.permission.THE_PERMISSION" />

然后在你的Activity:

检查权限:

fun checkPermission(permission: String): Boolean {
        return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
    }

获得权限:

fun getPermission(permission: String) {
    ActivityCompat.requestPermissions(this, arrayOf(permission), REQ_CODE_PERMISSION)
}

获取权限结果:

override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<out String>,
    grantResults: IntArray
) {
    if (requestCode == REQ_CODE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        ...      
    }
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

如果您使用的是片段:

片段包含请求权限并将结果返回其 onRequestPermissionsResult 的方法:

fun getPermission(permission: String) {
    requestPermissions(arrayOf(permission), REQ_CODE_PERMISSION)
}

REQ_CODE_PERMISSION:是一些随机数,例如 123,您可以用它来识别您的请求。