android 11 kotlin获取蓝牙mac地址

加权限

  1. 要获取system.uid系统权限,具体不细述,网上可查

  2. AndroidManifest.xml中添加蓝牙权限

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

不然会运行出错:
System.err: java.lang.reflect.InvocationTargetException
System.err: at java.lang.reflect.Method.invoke(Native Method)
System.err: Caused by: java.lang.SecurityException: Need BLUETOOTH permission: Neither user 10178 nor current process has android.permission.BLUETOOTH
Caused by: java.lang.SecurityException: Need LOCAL_MAC_ADDRESS permission: Neither user 10178 nor current process has android.permission.LOCAL_MAC_ADDRESS.

kotlin代码

  /**
     * 获取本机蓝牙地址, 确保蓝牙已开启,关闭状态无法获取到
     */
    private fun getBluetoothAddress(): String? {
        try {
            val bluetoothAdapter = (getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter
            val field: Field = bluetoothAdapter.javaClass.getDeclaredField("mService")
            field.isAccessible = true
            val bluetoothManagerService: Any = field.get(bluetoothAdapter) ?: return null
            val method: Method = bluetoothManagerService.javaClass.getMethod("getAddress")
            val address: Any? = method.invoke(bluetoothManagerService)
            return if (address != null && address is String) {
                address
            } else {
                null
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

作者:帅得不敢出门

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐