一、安卓6.0之前的版本
获取蓝牙适配器BluetoothAdpater
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
或者
BluetoothAdapter adapter = (BluetoothAdapter) getApplicationContext().getSystemService(BLUETOOTH_SERVICE);
//安卓6以后的版本使用此方法拿不到真实的MAC地址
String macAddr = adapter.getAddress();
二、安卓6.0之后的版本
打开蓝牙才能获得
/**
* 获取本机蓝牙地址
*/
private String getBluetoothAddress() {
try {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Field field = bluetoothAdapter.getClass().getDeclaredField("mService");
// 参数值为true,禁用访问控制检查
field.setAccessible(true);
Object bluetoothManagerService = field.get(bluetoothAdapter);
if (bluetoothManagerService == null) {
return null;
}
Method method = bluetoothManagerService.getClass().getMethod("getAddress");
Object address = method.invoke(bluetoothManagerService);
if (address != null && address instanceof String) {
return (String) address;
} else {
return null;
}
//抛一个总异常省的一堆代码...
} catch (Exception e) {
e.printStackTrace();
}
return null;
}