コード例 #1
0
  public void listenToCaliperMeasurements(final BluetoothGattCharacteristic characteristic) {
    if (characteristic == null) {
      Log.e(
          TAG,
          "Haven't discovered this feature yet, please wait until it has connected once, and or try disconnecting and reconnecting.");
      return;
    }

    Log.d(TAG, "Starting to listen to notifications from " + characteristic.getUuid());
    final int charaProp = characteristic.getProperties();
    if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
      // If there is an active notification on a characteristic, clear
      // it first so it doesn't update the data field on the user interface.
      if (mNotifyCharacteristic != null) {
        mBluetoothLeService.setCharacteristicNotification(mNotifyCharacteristic, false);
        mNotifyCharacteristic = null;
      }
      mBluetoothLeService.readCharacteristic(characteristic);
    }
    if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
      mNotifyCharacteristic = characteristic;
      mBluetoothLeService.setCharacteristicNotification(characteristic, true);

      // Set descriptor to enable notifications
      BluetoothGattDescriptor descriptor =
          characteristic.getDescriptor(
              UUID.fromString(SCalEvoBluetoothSpecifications.CLIENT_CHARACTERISTIC_CONFIG));
      if (descriptor == null) {
        Log.e(
            TAG,
            "descriptor "
                + SCalEvoBluetoothSpecifications.CLIENT_CHARACTERISTIC_CONFIG
                + "was null, looking for others.");

        List<BluetoothGattDescriptor> descriptors = characteristic.getDescriptors();
        String uuid;
        for (BluetoothGattDescriptor aDescriptor : descriptors) {
          uuid = aDescriptor.getUuid().toString();
          Log.e(TAG, "BluetoothGattDescriptor " + uuid);
          descriptor = aDescriptor;
        }
        if (descriptor == null) {
          Log.e(
              TAG,
              "Couldn't find any descriptors for this characteristic, cant enable notifications");
          return;
        } else {
          Log.e(TAG, "Trying the last descriptor to enable notifications");
        }
      }
      descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
      mBluetoothLeService.writeDescriptor(descriptor);
      Toast.makeText(this, "Ready", Toast.LENGTH_SHORT).show();
      Log.e(TAG, "Ready to read from characteristic " + characteristic.getUuid());
    }
  }