You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Kotlin中checkSelfPermission自定义校验函数失效问题

解决Android Kotlin封装权限检查后仍触发Lint权限错误的问题

你遇到的是Lint静态代码分析的局限性问题:Lint无法识别你封装在checkPermissionTwo()里的权限检查逻辑,它只会直接扫描代码中是否有checkSelfPermission的显式调用,所以即便你已经通过封装函数完成了权限校验,它依然会抛出权限缺失的提示。

解决方法

1. 给权限检查函数添加Lint抑制注解

直接给checkPermissionTwo()添加@SuppressLint("MissingPermission")注解,告诉Lint该函数已经完成了权限检查,无需再提示:

import android.annotation.SuppressLint

@SuppressLint("MissingPermission")
fun checkPermissionTwo(): Boolean {
    return permissionsCheck().all { permission ->
        ActivityCompat.checkSelfPermission(
            application.applicationContext, permission
        ) == PackageManager.PERMISSION_GRANTED
    }
}

这个方法最简洁,也能保留你封装权限检查的初衷,后续所有调用checkPermissionTwo()的地方都不会再触发该Lint错误。

2. (可选)在调用处单独抑制Lint

如果不想给整个函数加注解,也可以在调用stopScan方法的位置添加注解:

fun stopScan(adapter: BluetoothAdapter) {
    if (isBluetoothStateOn(adapter) && checkPermissionTwo()) {
        @SuppressLint("MissingPermission")
        bluetoothLeScanner?.stopScan(leScanCallback)
    }
}

不过这种方式需要在每个调用点都添加注解,不如第一种高效。

额外注意:修复代码语法错误

你的stopScan函数里的if条件写法有误,逗号应该改成逻辑与&&,否则会编译报错:

// 错误写法
if (isBluetoothStateOn(adapter), checkPermissionTwo())

// 正确写法
if (isBluetoothStateOn(adapter) && checkPermissionTwo())

内容的提问来源于stack exchange,提问作者Compose Learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 06:20:22