获取当前连接的蓝牙设备的名称

首先需要在清单文件添加权限:

    <!-- 蓝牙权限 -->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

获取当前连接蓝牙设备名称需要先获取已绑定或已匹配的蓝牙列表,然后再一个一个判断是否在连接状态,但是因为android现在将获取蓝牙设备连接状态的方法隐藏了,所以我们需要使用反射调用,下面是获取连接状态的源码:

 /**
     * Returns whether there is an open connection to this device.
     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
     *
     * @return True if there is at least one open connection to this device.
     * @hide  (注意这个,已隐藏)
     */
    @SystemApi
    @RequiresPermission(android.Manifest.permission.BLUETOOTH)
    public boolean isConnected() {
        final IBluetooth service = sService;
        if (service == null) {
            // BT is not enabled, we cannot be connected.
            return false;
        }
        try {
            return service.getConnectionState(this) != CONNECTION_STATE_DISCONNECTED;
        } catch (RemoteException e) {
            Log.e(TAG, "", e);
            return false;
        }
    }
 

明白了这个后就好办了,下面是获取当前连接的蓝牙设备名称的方法代码:

   private String getConnectedBtDevice() {
           //获取蓝牙适配器
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //得到已匹配的蓝牙设备列表
        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
        if (bondedDevices != null && bondedDevices.size() > 0) {
            for (BluetoothDevice bondedDevice : bondedDevices) {
                try {
                    //使用反射调用被隐藏的方法
                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    isConnectedMethod.setAccessible(true);
                    boolean isConnected = (boolean) isConnectedMethod.invoke(bondedDevice, (Object[]) null);
                    Log.e("123", "isConnected:" + isConnected);
                    if (isConnected) {
                        return bondedDevice.getName();
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

还有一种通过

 BluetoothProfile 

而且要遍历各种 类型的额蓝牙设备 ,比如 音响 ,头戴,耳机,常用,等。

具体不显示 ,问 GPT

文章参考:

Android蓝牙连接蓝牙音箱和耳机的 A2dp与Headset Profile_a2dp和headset_小简木子的博客-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值