问题描述
我尝试将我的 Android 手机连接到 BLE 设备(Bluefruit Feather 32u4 板),但我在 Gatt 回调的 onServicesdiscovered() 函数中立即断开连接。
我在 onConnectionStateChange() 方法中成功连接到设备,所以我调用 onServicesdiscovered() 然后断开连接。知道为什么吗?如果您有任何想法,我将不胜感激。
以下是我捕获进程和 Gatt 回调函数的日志快照:
private BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(final BluetoothGatt gatt,final int status,final int newState) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.d(TAG,"onConnectionStateChange: GATT_SUCCESS");
int bondstate = device.getBondState();
//Take action depending on the bond state
//can't discover services when still bonding
if (bondstate == BOND_NONE || bondstate == BOND_BONDED) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.d(TAG,"onConnectionStateChange: STATE_CONNECTED");
boolean result = gatt.discoverServices();
if (!result) {
textView.setText("Failed to discover services.");
Log.d(TAG,"onConnectionStateChange: Failed TO disCOVER SERVICES");
return;
} else {
textView.setText("Found services.");
Log.d(TAG,"onConnectionStateChange: FOUND SERVICES");
}
} else {
//gatt status is either disconnected,disconnecting or connecting so can't discover services
//or an error has occurred
Log.d(TAG,"onConnectionStateChange: ERROR. disCONNECTED.");
gatt.close();
}
}
}
}
@Override
public void onServicesdiscovered(BluetoothGatt gatt,int status) {
super.onServicesdiscovered(gatt,status);
//if an error has occurred,return; need to retry the connection
if (status == GATT_INTERNAL_ERROR) {
Log.d(TAG,"onServicesdiscovered: GATT_INTERNAL_ERROR");
textView.setText("An internal error has occurred when discovering services.");
gatt.disconnect();
return;
}
//if accidentally got disconnected,close
else if (status == BluetoothProfile.STATE_disCONNECTED) {
Log.d(TAG,"onServicesdiscovered: disCONNECTED.");
textView.setText("On Services: disconnected.");
gatt.close();
return;
}
//assuming that everything went fine,get the discovered services
else {
Log.d(TAG,"onServicesdiscovered: LOOK FOR SERVICES");
final List<BluetoothGattService> services = gatt.getServices();
listView.setAdapter((listadapter) gattAdapter);
}
}
};
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)