Sun*_*nny 2 android bluetooth-lowenergy gatt beacon
我正在尝试将我的信标连接到 Gattservice。在回调 onConnectionStateChange 中,它总是失败,我得到了
状态代码 133 和 257。
Somehwere 写道,133 代表许多联系。在我的代码中,有一些带有 gatt.disconnect() 的行。我不知道如何解决它,因为所有其他 gatt 示例都是相同的。如果发现错误很重要,我正在使用 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());
}
}
Run Code Online (Sandbox Code Playgroud)
我的 ScanCallback 看起来像这样:
public void onScanResult(int callbackType, ScanResult result) {
runOnUiThread(new Runnable() {
@Override
public void run() {
BluetoothDevice btDevice = result.getDevice();
connectToDevice(btDevice);
}
});
}
Run Code Online (Sandbox Code Playgroud)
并像这样开始连接:
runOnUiThread(new Runnable() {
@Override
public void run() {
mBluetoothGatt = btDevice.connectGatt(getApplicationContext(), true, connectCallback);
}
});
Run Code Online (Sandbox Code Playgroud)
connectCallback 会引发 onConnectionStateChange 函数。感谢您的帮助!
在某些 Android 设备上,如果 Android 手机之前未与外围设备配对(绑定),我会在连接时看到 133 错误。如果我在应用程序尝试在后台连接的同时进入“设置”->“蓝牙”,则连接可以正常工作。(奇怪的是,您不需要在屏幕上执行任何操作,只需将其打开即可。)一旦第一次成功,错误就会永远消失。
我猜这是一个安全限制,但我还没有找到优雅解决它的正确方法。
小智 5
我必须在调用中指定传输参数才能解决此问题。这是一个可选的第四个参数,用于指定它是 BLE 设备。
mBluetoothGatt = device.connectGatt(this, false, mGattCallback, 2);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11177 次 |
| 最近记录: |