[蓝牙] Android 8.1 获取蓝牙设备地址无效;02:00:00:00:00:00

序言:

对于这个问题, 谷歌是这样说的:
	为了向用户提供更好的数据保护,从此版本开始,Android删除了使用Wi-Fi和蓝牙API对应用程序的设备本地硬件标识符的编程访问。

链接地址:https://developer.android.com/about/versions/marshmallow/android-6.0-changes#behavior-hardware-id

ok、至此我们已经知道为什么获取不了相关的mac地址,不过不要担心, 车到山前必有路,船到桥头自然直,容许我卖个关子先。

关子五快钱一个,需要私聊我Q 7641436

接下来是解决办法利用反射,虽然不好, 但是可以解决实际问题:

/**
	获取蓝牙地址
*/
private String getBluetoothMacAddress() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        String bluetoothMacAddress = "";
        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 | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignore) {

        }
        return bluetoothMacAddress;
    }

不推荐这样做,但是我只有这个办法, 后续如果有更好的办法,我会继续更新这篇文章。

猜你喜欢

转载自blog.csdn.net/a_Chaon/article/details/85616377
00