发现 BLE 服务的正确方法

Proper method for discovering BLE services

我一直收到错误消息:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.UUID android.bluetooth.BluetoothGattService.getUuid()' on a null object reference

尝试 'get' 使用 UUID 的已知服务和特征时。文档说我需要先发现服务,但我想我做错了吗?这是我的连接方法:

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void Connect(View view){

    Device=Adapter.getRemoteDevice("3C:A3:08:94:C3:11");

    Gatt=Device.connectGatt(this,true,GattCallback);

    Gatt.discoverServices();

    Service=Gatt.getService(UUID.fromString("0000FFE0-0000-1000-8000-00805F9B34FB"));

    ErrorID.setText(Service.getUuid().toString());

    Characteristic=Service.getCharacteristic(UUID.fromString("0000FFE1-0000-1000-8000-00805F9B34FB"));

    threadStatus=true;

    //connected indicator

}

textView 用于确认已找到该服务。我试过在 discoverServices() 之后添加延迟,但这没有用。之后使用 onServicesDiscovered() 也没有用。我是 Java 和 Android 的新手,如果我的问题很愚蠢,请见谅,谢谢!

调用后

Gatt=Device.connectGatt(this,true,GattCallback);

您必须等待 GattCallbackonConnectionStateChange method 被调用(具有适当的状态),然后再做任何其他事情。

一旦发生这种情况,您将需要调用要调用的 GattCallbackdiscoverServices on your Gatt instance, and wait once more for the onServicesDiscovered 方法。

只有在调用 onServicesDiscovered 之后,您才能调用 Gatt.getService 并期望收到非 null 结果。即使您知道您希望设备上存在哪些服务,也是如此。

您需要 GattCallback 在其中重写回调方法。你需要定义你的 GattCallback 类似下面的代码。当您收到回调时,执行适当的操作。

private final BluetoothGattCallback GattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String intentAction;
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // This is where you call to discover services. 
                Gatt.discoverServices();

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                // This is where you will call the method to get the service
                Service=Gatt.getService(UUID.fromString("0000FFE0-0000-1000-8000-00805F9B34FB"));
            } else {
            }
        }

    };