首先,即使是runtime permission,在运行时进行的权限请求,也应该在manifest中著名。
比如说:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.criminalintent">
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
...
有了这个权限,我们可以获取联系人列表里的联系人的id。
那如何进行权限请求呢?下面介绍一种高级的方法,只需要两个块。
- 首先,在点击事件时判断是否已获取请求:
binding.crimeSuspect.setOnClickListener { if (ContextCompat.checkSelfPermission( context!!,//2:填入当前申请权限所在的context实例 Manifest.permission.READ_CONTACTS//1:这里换成想要申请的权限 ) == PackageManager.PERMISSION_GRANTED ) { aLauncher.launch()//3:这一行换成自己处理有权限所做的任务逻辑 } else { // You can directly ask for the permission. // The registered ActivityResultCallback gets the result of this request. requestPermissionLauncher.launch(//4:这个参数是定义在activity或fragment中的字段,稍后介绍 Manifest.permission.READ_CONTACTS//5:和1的权限一样 ) } }
- 在fragment或activity中定义一个字段:
// Register the permissions callback, which handles the user's response to the // system permissions dialog. Save the return value, an instance of // ActivityResultLauncher. You can use either a val, as shown in this snippet, // or a lateinit var in your onAttach() or onCreate() method. val requestPermissionLauncher = registerForActivityResult(RequestPermission() ) { isGranted: Boolean -> if (isGranted) { // Permission is granted. Continue the action or workflow in your // app. } else { // Explain to the user that the feature is unavailable because the // features requires a permission that the user has denied. At the // same time, respect the user's decision. Don't link to system // settings in an effort to convince the user to change their // decision. } }
这两步就大功告成了!!还有,上面这两步需要依赖:
implementation 'androidx.activity:activity-ktx:1.3.0-alpha08'
implementation 'androidx.fragment:fragment-ktx:1.4.0-alpha01'
具体参考文档:https://developer.android.com/training/permissions/requesting