我用BT低能能够行李报警装置(Link)工作,并已与我的Nexus 7HOWTO连接到蓝牙LE设备上的Android(平台19)
继docs 我成功配对,现在想使用以下代码连接到设备:
private BluetoothGattCallback callback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
Log.i(TAG, "le onConnectionStateChange ["+newState+"]");
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.i(TAG, "le device connected");
onConnect(gatt.getDevice());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.i(TAG, "le device disconnected");
onDisconnect(gatt.getDevice());
}
}
@Override
public void onServicesDiscovered (BluetoothGatt gatt, int status) {
Log.i(TAG, "onServicesDiscovered");
}
};
for (BluetoothDevice device : BluetoothAdapter.getDefaultAdapter().getBondedDevices()) {
int type = device.getType();
if (type == BluetoothDevice.DEVICE_TYPE_LE || type == BluetoothDevice.DEVICE_TYPE_DUAL) {
List<BluetoothDevice> connectedDevices =
bluetoothManager.getConnectedDevices(BluetoothProfile.GATT);
if (!connectedDevices.contains(device)) {
BluetoothGatt gatt = device.connectGatt(App.getContext(), false, callback);
gatt.connect();
gatt.discoverServices();
List<BluetoothGattService> services = gatt.getServices();
}
}
}
但是,无法启动连接。一段时间后(几秒钟),连接状态 更改为BluetoothProfile.STATE_DISCONNECTED - 即使BluetoothProfile.STATE_CONNECTED 未被达到。我在这里做错了什么?
可以在未连接的情况下绑定设备。 gatt.connect()实际运行吗?开始扫描更常见,以获取可用设备的列表,而不是假设它已经连接。你也可以尝试一下。 –
仔细看,它说!connectedDevices.contains(设备)。上面的代码遍历绑定设备列表,并尝试与当前未连接的设备建立连接。循环中的代码被运行,并且回调被调用,但是不用于BluetoothProfile.STATE_CONNECTED – fabian
除了上述评论之外,另一个可能的帮助是你不想调用discoverServices,而gattServices是序列化的。您希望等待每个回调,否则getServices将不会返回任何内容。我还注意到,您正试图连接到通常使用RSSI检测信号强度和距离的标签,因此我不确定GATT服务器的定义有多好。 – Zomb