我正在为Android开发一款具有BLE功能的应用程序,除非我尝试多次连接和断开BLE设备,否则它的工作原理非常好。在连接/断开几次成功尝试后,即使首先连接,BLE设备也会在随机时间间隔后直接调用断开连接功能。
public boolean connect(final String address)
{
if (mBtAdapter == null || address == null) {
Log.v("Notification", "BluetoothAdapter not initialized or unspecified address.");
return false;
}
// Previously connected device. Try to reconnect.
//mBtDeviceAddress != null && address.equals(mBtDeviceAddress)&&
if (deviceGatt.get(address) != null) {
Log.v("Notification", "Trying to use an existing mBluetoothGatt for connection.");
if (deviceGatt.get(address).connect()) {
mConnectionState = STATE_CONNECTING;
Log.v("Notification","Connection State :" +mConnectionState);
return true;
} else {
return false;
}
}
final BluetoothDevice device = mBtAdapter.getRemoteDevice(address);
pairedDevice = device;
if (device == null) {
Log.v("Notification", "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the autoConnect
// parameter to false.
BluetoothGatt mBluetoothGatt = device.connectGatt(this,false,this.mGattCallBack);
deviceGatt.put(address,mBluetoothGatt);
Log.v("Notification", "Trying to create a new connection.");
Log.v("Notification","Size of device gatt "+deviceGatt.size());
mBtDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}
public boolean disconnect(BluetoothDevice device) {
if (mBtAdapter == null || deviceGatt.get(device.getAddress()) == null) {
Log.v("Notification", "BluetoothAdapter not initialized");
return false;
}
//Log.v("Notification","Device Address : "+device.getAddress());
deviceGatt.get(device.getAddress()).disconnect();
//deviceGatt.get(device.getAddress()).close();
return true;
}
答案 0 :(得分:0)
我不确定这是否对您有用但我发现bluetoothGatt在大约4-7分钟后自动断开连接,如果没有调用通知或特征写入。通过每5秒调用一次BluetoothGatt.readRemoteRssi()来解决这个问题。
@Override
public void onReadRemoteRssi(BluetoothGatt gatt,int rssi, int status){
if (status == BluetoothGatt.GATT_SUCCESS)
System.out.println("onReadRemoteRssi: " + rssi);
if (mBluetoothGatt != null)
myHandler.postDelayed(runnableReadRssi, 5000);
}
您还应确保关闭每个bluetoothGatt,并在不再需要它后设置为null。我已经读过,如果你有超过5个bluetoothGatts处于活动状态,你将收到一个关于无法连接到Gatt服务器的错误。