Android BLE Gatt客户端与服务器通信空指针异常求助
I've looked at your issue and the stack trace you provided—let's get to the bottom of this:
Root Cause
The NullPointerException happens because when your GattServerCallback calls sendResponse (line 115 in GattServerCallback.java), one of the Integer parameters being passed is null. When the system tries to unbox this Integer to an int (for BluetoothGattServer.sendResponse), it throws the exception. Android's BLE stack responds to unhandled callback exceptions by dropping the GATT connection immediately, which is why you see onConnectionStateChange trigger for disconnection and lose the ability to send messages afterward.
Step-by-Step Fixes
Check the
sendResponsecall inonDescriptorWriteRequest
Head to line 115 ofGattServerCallback.javaand verify you're passing the correct parameters. TherequestIdparameter from the callback is a raw int—you should use it directly, not a null Integer variable. The correct call should look like this:mServerActivity.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);Ensure none of the integer parameters (
requestId,status,offset) are null here—stick to primitive int values.Fix
ServerActivity.sendResponse's method signature
Make sure this method uses primitiveinttypes for requestId, status, and offset instead ofIntegerwrappers. Wrapper types risk unboxing NPEs if they're null. Here's a safe version of the method:public void sendResponse(BluetoothDevice device, int requestId, int status, int offset, byte[] value) { if (mGattServer == null) { Log.w(TAG, "GattServer is null, can't send response"); return; } mGattServer.sendResponse(device, requestId, status, offset, value); }Adding a null check for
mGattServeralso prevents another potential crash.Validate your GATT Descriptor setup
Double-check that the descriptor your client is writing to has the correct UUID and permissions. Invalid configurations can trigger unexpected write requests that lead to parameter errors.
Once you fix the NPE in the sendResponse flow, the BLE stack won't terminate your connection anymore, and your client-server message passing should work as intended.
内容的提问来源于stack exchange,提问作者jmc420

