runtime permission写法

首先,即使是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。

那如何进行权限请求呢?下面介绍一种高级的方法,只需要两个块。

  1. 首先,在点击事件时判断是否已获取请求:
    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的权限一样
                    )
                }
            }
    
  2. 在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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值