Vla*_*nko 7 android bluetooth android-bluetooth
我需要获取设备的蓝牙 MAC 地址。
在 Android 6 之前,它就像BluetoothAdapter.getDefaultAdapter().getAddress(). 之后,我们不得不使用一个简单的解决方法:String macAddress = android.provider.Settings.Secure.getString(context.getContentResolver(), "bluetooth_address");. 但后来(在 Android 8 AFAIK 中)它也被关闭,但发现了另一种解决方法:
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();
}
Run Code Online (Sandbox Code Playgroud)
但是从 Android 8.1 开始尝试访问该方法会引发异常:
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,这意味着此方法需要权限,仅适用于系统级应用程序。
所以问题是是否有任何解决方法可以在 Android 8.1 中获取蓝牙地址?
| 归档时间: |
|
| 查看次数: |
2329 次 |
| 最近记录: |