How do I notify users if the device they are trying to connect to does not connect, besides waiting and testing for a connection. There does not seem to be any callback for a failed connection after trying connectGatt(). Thanks!
Asked
Active
Viewed 1,065 times
1 Answers
0
The method: connGATT() has 3 parameters. The third one is a callback:
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
if you want to know the connection is success or not, you should add override the method:
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState)
Here is the link.https://developer.android.com/guide/topics/connectivity/bluetooth-le.html
The whole callback looks like this:
private final BluetoothGattCallback mGattCallback =
new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
Log.i(TAG, "Attempting to start service discovery:" +
mBluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
mConnectionState = STATE_DISCONNECTED;
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}
@Override
// New services discovered
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
@Override
// Result of a characteristic read operation
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
...
};
...
}

Meng Tim
- 408
- 1
- 6
- 19
-
Hi, I do have the callback set up, but there is no state change for 'failed to connect'. Bluetooth classic has 'mmSocket.connect()', and it throws an exception if connection does not happen. I don't know how to tell if the connection failed except by polling the device, or having a timeout on the 'State_Connected' flag. Is there something I am missing? Thank you. – tommyvdp Apr 27 '17 at 20:13
-
See you have "status" and "newStatus" right? If "status" !=GATT_SUCCESS, it means the gatt connection failed, If "status" == GATT_SUCCESS && "newState" == STATE_CONNECTED, it means the connection success and get a Peripheral connected. – Meng Tim Apr 27 '17 at 20:31
-
If I try to connect and the device is not available, onConnectionStateChange does not fire at all, so I cannot check the status. – tommyvdp Apr 28 '17 at 14:54