1

我尝试使用 ble 设备开发一个简单的 android 应用程序。我从 Internet 上找到了许多源代码。但是,它们都是从扫描可用 ble 设备列表开始的。因为我有设备的 MAC 地址、服务的 UUID 和特性。如何连接到已知设备并直接读取一个特定特征?

4

3 回答 3

2

要连接特定的蓝牙设备,该设备具有设备的 MAC 地址、服务的 UUID 和特征等详细信息,您已经知道了。为此,您需要一个 BluetoothDevice 对象来进行如下调用:

yourBluetoothDevice.connectGatt(getApplicationContext(), false, bleGattCallback);

所以对于这个(你的蓝牙设备),你必须首先开始扫描,通过比较它的 MAC 地址来获得相同的设备对象进行连接。但是,您在 onLeScan 回调中获得了相同的设备对象,只需停止扫描并与同一设备建立连接。

注意:建立连接应该在 UIThread(使用 Handler、runOnUIThread 或 mainlooperThread)上,否则会在某些设备中出现“无法注册回调”的问题

这里 yourBluetoothDevice 是要与您建立连接的设备对象引用。bleGattCallback 是注册的新的 BluetoothGattCallback() 回调,用于连接状态、发现的服务、读写特性等。

于 2016-09-16T07:07:24.100 回答
0

看看createInsecureRfcommSocketToServiceRecord。像这样的东西:

UUID uuid = UUID.fromString("<Your UUID>");
BluetoothSocket socket = yourBLEDevice.createInsecureRfcommSocketToServiceRecord(uuid);
Method m = yourBLEDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
socket = (BluetoothSocket) m.invoke(yourBLEDevice, 1);
于 2014-08-25T04:05:43.900 回答
0

如果您已经知道 mac 地址,可以尝试以下方法:

final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mMacAddress);
final BluetoothGatt mGatt = device.connectGatt(getApplication(), false, gattCallback);
于 2018-08-28T01:26:02.640 回答