android 11 kotlin获取蓝牙mac地址
加权限
-
要获取system.uid系统权限,具体不细述,网上可查 -
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
}
作者:帅得不敢出门
|