如何解决Android Studio - 找到服务,但在 GattCallback 中的 onServicesDiscovered 中断开连接
我尝试将我的 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 举报,一经查实,本站将立刻删除。