在Android 13及以上版本中,需要系统权限BLUETOOTH_PRIVILEGED才能使用BluetoothAdapter的getAddress()方法获取设备的蓝牙MAC地址。以下是获取蓝牙MAC地址的示例代码:
首先在AndroidManifest.xml文件中添加权限:
然后在代码中获取蓝牙MAC地址:
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter != null) { String bluetoothMacAddress = bluetoothAdapter.getAddress(); Log.d(TAG, "Bluetooth MAC address: " + bluetoothMacAddress); } else { Log.d(TAG, "Bluetooth is not supported on this device"); }
需要注意的是,在Android 10及以上版本,该方法会返回随机化的地址而不是设备的真实MAC地址。此外,BLUETOOTH_PRIVILEGED权限只能由系统应用程序获得,在非系统应用程序中无法获取该权限。如果您的应用程序需要使用设备的蓝牙MAC地址,请考虑使用其他方法,例如通过网络请求获取。