完全断开蓝牙低功耗设备的连接 [英] Totally Disconnect a Bluetooth Low Energy Device
问题描述
我在Android中使用connectGatt()
方法连接到BLE设备.效果很好.
I connect to a BLE device with the connectGatt()
method in Android. This works great.
当我断开连接时,请使用以下内容:
When I disconnect I use the following:
private void disconnectDevice() {
gatt.disconnect();
}
当我收到回叫时,我将关闭.
When I receive the callback I do a close.
private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
Log.d("BLED-GATT", "STATE_CONNECTED");
setUIConnectionStatus("Discover services on device...", Color.YELLOW);
checkEnableAddButton(simpleTrackEditText.getText().toString());
gatt.discoverServices();
break;
case BluetoothProfile.STATE_DISCONNECTED:
Log.d("BLED-GATT", "STATE_DISCONNECTED");
setUIConnectionStatus("Not Connected!", Color.RED);
gatt.close();
break;
default:
Log.d("BLED-GATT", "STATE_OTHER");
}
}
}
这已执行,调用disconnectDevice()
后我无法再控制设备.该设备本身似乎认为它仍处于连接状态,因为我无法将其置于广播可见性模式下(如果已经具有连接,则会发生这种情况).但是,如果我终止该应用程序并再次打开它,则可以将设备设置为广播模式.这告诉我该应用未正确断开连接.
This is executed and I can no longer control the device after calling disconnectDevice()
. The device itself seems to think that it is still connected since I cant put it in broadcasting visibility mode (which happens if it already has a connection). However, if I kill the application and open it again then I can set the device in broadcasting mode. This tells me the app was not properly disconnected.
知道我在这里错过了什么吗?
Any idea what I missed here?
推荐答案
问题是我在扫描期间多次连接到同一设备,导致我的应用程序同时打开了许多连接.添加!isConnected()
解决了该问题:
The problem was that I during scanning was connecting to the same device multiple times causing my application to have many connections open at the same time. Adding !isConnected()
solved the problem:
/**
* Connects to the device. Does nothing if already connected.
* @param macAddress the address of the device.
*/
private void connectDevice(String macAddress) {
if (isConnected()) {
return;
}
device = bluetoothAdapter.getRemoteDevice(macAddress);
if (device == null) {
this.sendToast("Device Not Available");
} else {
Log.d("BLED", "Connecting...");
gatt = device.connectGatt(this, true, gattCallback);
}
}
这篇关于完全断开蓝牙低功耗设备的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!