You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android BLE Gatt客户端与服务器通信空指针异常求助

Fixing Android BLE GATT Server NPE on sendResponse & Connection Drop

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

  1. Check the sendResponse call in onDescriptorWriteRequest
    Head to line 115 of GattServerCallback.java and verify you're passing the correct parameters. The requestId parameter 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.

  2. Fix ServerActivity.sendResponse's method signature
    Make sure this method uses primitive int types for requestId, status, and offset instead of Integer wrappers. 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 mGattServer also prevents another potential crash.

  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:16:05