【发布时间】:2017-11-24 12:02:13
【问题描述】:
我正在尝试将我的信标连接到 Gattservice。在回调 onConnectionStateChange 中,它总是失败,我得到了
状态码 133 和 257。
Somehwere 写道 133 代表许多连接。在我的代码中有带有 gatt.disconnect() 的行。 我不知道如何解决它,因为所有其他 gattexamples 都是相同的。如果发现错误很重要,我正在使用 Android 6.0.1 版本和 API 23。 这是我的代码:
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if(status == BluetoothGatt.GATT_SUCCESS) {
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
mBleDevices.add(gatt.getDevice());
Log.i("Beacons", "STATE_CONNECTED");
runOnUiThread(new Runnable() {
@Override
public void run() {
mBluetoothGatt.discoverServices();
}
});
break;
case BluetoothProfile.STATE_DISCONNECTED:
Log.e("Beacons", "STATE_DISCONNECTED");
mBleDevices.remove(gatt.getDevice());
mBluetoothGatt.disconnect();
mBluetoothGatt = null;
break;
default:
Log.e("Beacons", "STATE_OTHER");
}
} else {
Log.e("Beacons", "ERROR WITH CONNECTING " + status);
mBleDevices.remove(gatt.getDevice());
}
}
我的 ScanCallback 如下所示:
public void onScanResult(int callbackType, ScanResult result) {
runOnUiThread(new Runnable() {
@Override
public void run() {
BluetoothDevice btDevice = result.getDevice();
connectToDevice(btDevice);
}
});
}
然后像这样开始连接:
runOnUiThread(new Runnable() {
@Override
public void run() {
mBluetoothGatt = btDevice.connectGatt(getApplicationContext(), true, connectCallback);
}
});
connectCallback 会导致 onConnectionStateChange 函数。 感谢您的帮助!
【问题讨论】:
-
你有beacon的服务uuid吗?
-
Michalik,您将多次收到扫描回调,因此 onScanResult() 正在多次调用,并且您尝试为每个回调连接设备,即您尝试多次连接设备.尝试在列表视图中显示扫描回调结果,然后连接到相应的设备
-
是的,但这是连接后应该做的事情,对吗?如果有连接,我调用 gatt.getServices(),将它们保存在一个变量中并检查其中一项服务是否与我想要的相同:gattServices.get(i).getUuid().equals(Battery_Service_UUID) ,并对其进行进一步的操作。
标签: android bluetooth-lowenergy beacon gatt