问题
I need to obtain device's Bluetooth MAC address.
Before Android 6 it was easy as BluetoothAdapter.getDefaultAdapter().getAddress()
. After that we had to use a simple workaround: String macAddress = android.provider.Settings.Secure.getString(context.getContentResolver(), "bluetooth_address");
. But later(in Android 8 AFAIK) it was also closed, but another workaround was discovered:
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
String bluetoothMacAddress = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M){
try {
Field mServiceField = bluetoothAdapter.getClass().getDeclaredField("mService");
mServiceField.setAccessible(true);
Object btManagerService = mServiceField.get(bluetoothAdapter);
if (btManagerService != null) {
bluetoothMacAddress = (String) btManagerService.getClass().getMethod("getAddress").invoke(btManagerService);
}
} catch (NoSuchFieldException e) {
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
} else {
bluetoothMacAddress = bluetoothAdapter.getAddress();
}
But starting from Android 8.1 trying to access that method throws exception:
java.lang.reflect.InvocationTargetException Caused by: java.lang.SecurityException: Need LOCAL_MAC_ADDRESS permission: Neither user 10141 nor current process has android.permission.LOCAL_MAC_ADDRESS
, which means that this method requires permission, available only for system-level apps.
So the question is if there is any workaround to get Bluetooth address in Android 8.1?
来源:https://stackoverflow.com/questions/50896816/device-bluetooth-address-in-oreo-8-1