我有一个与我的Nexus 5X(运行Android 7.1)配对的蓝牙耳机,并且我想连接到耳机的GATT服务器。我用下面的代码试了一下:onServices在连接到GATT服务器时从未被调用
private BluetoothGattCallback btleGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
Log.d(TAG, "onConnectionStateChange: " + status + ", " + newState);
if(newState == STATE_CONNECTED) {
Log.d(TAG, "Device connected");
boolean ans = gatt.discoverServices();
Log.d(TAG, "Discover Services started: " + ans);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
Log.d(TAG, "Number of Services: " + gatt.getServices().size());
}
};
public void onDeviceClicked(BluetoothDevice device) {
BluetoothGatt gatt = device.connectGatt(this, false, btleGattCallback);
Log.d(TAG, "Connected to GATT: " + gatt.connect());
}
如果我点击我的UI onDeviceClicked
耳机打电话,谈到这个日志输出:
<!-- language: lang-none -->
Connected to GATT: true
onConnectionStateChange: 0, 2 // GATT_SUCCESS, STATE_CONNECTED
Device connected
Discover Services started: true
正如你可以看到onServicesDiscovered
是从来没有发射。我试图拨打connectGatt
与TRANSPORT_LE
(ref),但后来我得到一个onConnectionStateChange: 133, 0
。我还发现this question这就是为什么我加入了回答二中提到的gatt.connect()
方法的原因。
你有什么想法,为什么我没有得到onServicesDiscovered
回调?
在你的代码示例中,你引用'mBluetoothGatt.discoverServices();'和一个局部变量'BluetoothGatt gatt = device.connectGatt(this,false,btleGattCallback);'?它可能不是同一个实例或设备吗? – ayvazj
对不起,这是出于测试原因。我在上面的代码中改变了它,但它也不起作用。 – Cilenco