如何以编程方式区分 android 中连接的蓝牙设备?

How to differentiate the connected bluetooth device in android programmatically?

是蓝牙耳机还是手机phones?

如何在 android 代码中区分蓝牙耳机和启用蓝牙的 android 设备。

我正在开发一个小应用程序,因为我有一个阻止通过蓝牙传输数据的功能,但它需要允许通过蓝牙耳机进行通信。

请帮我区分连接的蓝牙设备是耳机/android设备(手机phone)等,

提前谢谢你。

扫描并找到 BluetoothDevice 后调用方法 BluetoothDevice.getBluetoothClass()。这将 return 一个 BluetoothClass 对象并且 documentation 声明如下:

Represents a Bluetooth class, which describes general characteristics and capabilities of a device. For example, a Bluetooth class will specify the general device type such as a phone, a computer, or headset, and whether it's capable of services such as audio or telephony.

因此,在允许用户 select 连接到设备或过滤显示的 BluetoothDevice 列表之前,请尝试查看 BluetoothClass 是否有正确的设备类型。

BluetoothClass bluetoothClass = bluetoothDevice.getBluetoothClass();
if(bluetoothClass.getDeviceClass() == BluetoothClass.Device.AUDIO_VIDEO_HEADPHONES) {
    // allow user to select this device. I'm not sure exactly which type
    // headphones will be but this is a good guess. You can connect to
    // your Bluetooth headset to find out for sure.
}

可以找到不同的设备 class 常量 here 如果您想进一步区分设备 class。