以前提到過獲取系統的藍牙地址,最近發如今Anroid O版本上出現了沒法獲取的現象。通過不斷查詢,發現瞭解決方法是替換成下面的方案:
private String getBluetoothMacAddress() { 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(); } return bluetoothMacAddress; }
緣由在於在8.0版本上關於系統的權限作了更爲嚴格的要求,原有的經過Secure的映射獲取的方式已經被捨棄。目前經過BluetoothManagerService的反射獲取能夠獲得BT mac地址。android
參考git