我编写了一个 Android 应用程序 (4.4.2),它在大多数情况下都能正确连接/断开与 BLE 外设的连接。然而,每隔一段时间我就会在 Bluetootgatt.java onClientConnectionState() 中收到 NullPointerException 的 LogCat 警告:
我的BluetoothGattCallback回调如下:
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
{
if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED)
{
gatt.discoverServices(); // triggers onServicesDiscovered() callback
}
else if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_DISCONNECTED)
{
return;
}
else if (status != BluetoothGatt.GATT_SUCCESS)
{
gatt.disconnect();
}
}
应用程序在连接时始终正确地转到 onConnectionStateChange newState==STATE_CONNECTED 回调,但是当它抛出异常时(应用程序断开连接时),它永远不会转到 onConnectionStateChange 回调中的任何位置。我在 2013 Nexus 7 上运行此程序。为什么会出现此异常?
最佳答案
这似乎是由于我在 onPause() 函数中调用disconnect() 然后调用close() 引起的。我删除了disconnect()并且close()可以很好地处理断开连接,并且我不再看到异常。
关于Android 蓝牙Gatt : Unhandled execption in callback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28400740/