android.bluetooth.BluetoothGatt#setCharacteristicNotification ( )源码实例Demo

下面列出了android.bluetooth.BluetoothGatt#setCharacteristicNotification ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Android-nRF-Toolbox   文件: BleManager.java
private boolean internalEnableIndications(final BluetoothGattCharacteristic characteristic) {
	final BluetoothGatt gatt = bluetoothGatt;
	if (gatt == null || characteristic == null)
		return false;

	// Check characteristic property
	final int properties = characteristic.getProperties();
	if ((properties & BluetoothGattCharacteristic.PROPERTY_INDICATE) == 0)
		return false;

	gatt.setCharacteristicNotification(characteristic, true);
	final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
	if (descriptor != null) {
		descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
		return internalWriteDescriptorWorkaround(descriptor);
	}
	return false;
}
 
/**
 * Register notification of HeartRateMeasurement Characteristic.
 *
 * @param gatt GATT Service
 * @return true if successful in notification of registration
 */
private boolean callRegisterHeartRateMeasurement(final BluetoothGatt gatt) {
    boolean registered = false;
    BluetoothGattService service = gatt.getService(UUID.fromString(
            BleUtils.SERVICE_HEART_RATE_SERVICE));
    if (service != null) {
        BluetoothGattCharacteristic c = service.getCharacteristic(
                UUID.fromString(BleUtils.CHAR_HEART_RATE_MEASUREMENT));
        if (c != null) {
            registered = gatt.setCharacteristicNotification(c, true);
            if (registered) {
                for (BluetoothGattDescriptor descriptor : c.getDescriptors()) {
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    gatt.writeDescriptor(descriptor);
                }
                mHRDevices.put(gatt, DeviceState.REGISTER_NOTIFY);
            }
        }
    }
    return registered;
}
 
源代码3 项目: EFRConnect-android   文件: BLEUtils.java
/**
 * Set a Notification Setting for The Matching Characteristic of a Service
 *
 * @param gatt               The Bluetooth GATT
 * @param gattService        the service we must find and match
 * @param gattCharacteristic the characteristic we must find and match
 * @param gattDescriptor     the descriptor we must write to we must find and match
 * @param value              The exact setting we are setting
 * @return Whether the instruction to write passed or failed.
 */
public static boolean SetNotificationForCharacteristic(BluetoothGatt gatt, GattService gattService, GattCharacteristic gattCharacteristic, UUID gattDescriptor, Notifications value) {
    boolean written = false;
    List<BluetoothGattService> services = gatt.getServices();
    for (BluetoothGattService service : services) {
        BluetoothGattCharacteristic characteristic = BLEUtils.getCharacteristic(service, gattService, gattCharacteristic);
        if (characteristic != null) {
            gatt.setCharacteristicNotification(characteristic, value.isEnabled());
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(gattDescriptor);
            if (descriptor != null) {
                //writing this descriptor causes the device to send updates
                descriptor.setValue(value.getDescriptorValue());
                written = gatt.writeDescriptor(descriptor);
            }
            return written;
        }
    }

    return false;
}
 
源代码4 项目: EFRConnect-android   文件: BluetoothLEGatt.java
void addCharacteristics(BluetoothGatt gatt, List<BluetoothGattCharacteristic> gattCharacteristics) {
    // Loops through available Characteristics.
    for (BluetoothGattCharacteristic characteristic : gattCharacteristics) {
        if (BuildConfig.DEBUG) {
            String characteristicName = getCharacteristicName(characteristic.getUuid());
            Timber.d("    char: " + characteristicName);
            //Log.d("addCharacteristics"," char: " + characteristicName);
        }

        final int characteristicID = getIdentification(characteristic.getUuid());
        this.gattCharacteristics.put(characteristicID, characteristic);
        this.values.put(characteristicID, null);

        int properties = characteristic.getProperties();
        if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
            gatt.setCharacteristicNotification(characteristic, true);
        }
    }
}
 
源代码5 项目: Android-BLE-Library   文件: BleManagerHandler.java
private boolean internalEnableNotifications(@Nullable final BluetoothGattCharacteristic characteristic) {
	final BluetoothGatt gatt = bluetoothGatt;
	if (gatt == null || characteristic == null || !connected)
		return false;

	final BluetoothGattDescriptor descriptor = getCccd(characteristic, BluetoothGattCharacteristic.PROPERTY_NOTIFY);
	if (descriptor != null) {
		log(Log.DEBUG, "gatt.setCharacteristicNotification(" + characteristic.getUuid() + ", true)");
		gatt.setCharacteristicNotification(characteristic, true);

		descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
		log(Log.VERBOSE, "Enabling notifications for " + characteristic.getUuid());
		log(Log.DEBUG, "gatt.writeDescriptor(" +
				BleManager.CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID + ", value=0x01-00)");
		return internalWriteDescriptorWorkaround(descriptor);
	}
	return false;
}
 
源代码6 项目: Android-BLE-Library   文件: BleManagerHandler.java
private boolean internalEnableIndications(@Nullable final BluetoothGattCharacteristic characteristic) {
	final BluetoothGatt gatt = bluetoothGatt;
	if (gatt == null || characteristic == null || !connected)
		return false;

	final BluetoothGattDescriptor descriptor = getCccd(characteristic, BluetoothGattCharacteristic.PROPERTY_INDICATE);
	if (descriptor != null) {
		log(Log.DEBUG, "gatt.setCharacteristicNotification(" + characteristic.getUuid() + ", true)");
		gatt.setCharacteristicNotification(characteristic, true);

		descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
		log(Log.VERBOSE, "Enabling indications for " + characteristic.getUuid());
		log(Log.DEBUG, "gatt.writeDescriptor(" +
				BleManager.CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID + ", value=0x02-00)");
		return internalWriteDescriptorWorkaround(descriptor);
	}
	return false;
}
 
@Override
  public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
  	BluetoothGattService service = gatt.getService(UUID.fromString(HRUUID)); // Return the HR service
//BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("00002A37-0000-1000-8000-00805F9B34FB"));
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics(); //Get the hart rate value
for (BluetoothGattCharacteristic cc : characteristics)
	{
		for (BluetoothGattDescriptor descriptor : cc.getDescriptors()) {
		    //find descriptor UUID that matches Client Characteristic Configuration (0x2902)
		    // and then call setValue on that descriptor
			
			//Those two line set the value for the disconnection
			H7ConnectThread.descriptor=descriptor;
			H7ConnectThread.cc=cc;
									
			gatt.setCharacteristicNotification(cc,true);//Register to updates
			descriptor.setValue( BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
		    gatt.writeDescriptor(descriptor);
			Log.d("H7ConnectThread", "Connected and regisering to info");
		}
	}
  }
 
源代码8 项目: SimpleBluetoothLeTerminal   文件: SerialSocket.java
private void connectCharacteristics3(BluetoothGatt gatt) {
    int writeProperties = writeCharacteristic.getProperties();
    if((writeProperties & (BluetoothGattCharacteristic.PROPERTY_WRITE +     // Microbit,HM10-clone have WRITE
            BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) ==0) { // HM10,TI uart,Telit have only WRITE_NO_RESPONSE
        onSerialConnectError(new IOException("write characteristic not writable"));
        return;
    }
    if(!gatt.setCharacteristicNotification(readCharacteristic,true)) {
        onSerialConnectError(new IOException("no notification for read characteristic"));
        return;
    }
    BluetoothGattDescriptor readDescriptor = readCharacteristic.getDescriptor(BLUETOOTH_LE_CCCD);
    if(readDescriptor == null) {
        onSerialConnectError(new IOException("no CCCD descriptor for read characteristic"));
        return;
    }
    int readProperties = readCharacteristic.getProperties();
    if((readProperties & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
        Log.d(TAG, "enable read indication");
        readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
    }else if((readProperties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
        Log.d(TAG, "enable read notification");
        readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    } else {
        onSerialConnectError(new IOException("no indication/notification for read characteristic ("+readProperties+")"));
        return;
    }
    Log.d(TAG,"writing read characteristic descriptor");
    if(!gatt.writeDescriptor(readDescriptor)) {
        onSerialConnectError(new IOException("read characteristic CCCD descriptor not writable"));
    }
    // continues asynchronously in onDescriptorWrite()
}
 
源代码9 项目: EFRConnect-android   文件: BLEUtils.java
public static boolean SetNotificationForCharacteristic(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, UUID gattDescriptor, Notifications value) {
    boolean written = false;
    if (characteristic != null) {
        gatt.setCharacteristicNotification(characteristic, value.isEnabled());
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(gattDescriptor);
        if (descriptor != null) {
            //writing this descriptor causes the device to send updates
            descriptor.setValue(value.getDescriptorValue());
            written = gatt.writeDescriptor(descriptor);
        }
        return written;
    }

    return false;
}
 
源代码10 项目: thunderboard-android   文件: BleUtils.java
public static boolean unsetCharacteristicNotification(BluetoothGatt gatt, UUID serviceUuid, UUID characteristicUuid, UUID descriptorUuid, boolean enable) {
    if (gatt == null) {
        return false;
    }
    BluetoothGattService service = gatt.getService(serviceUuid);
    if (service == null) {
        return false;
    }
    BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUuid);

    if (characteristic == null) {
        Timber.d("could not get characteristic: %s for service: %s", characteristicUuid.toString(), serviceUuid.toString());
        return false;
    }

    if (!gatt.setCharacteristicNotification(characteristic, false)) {
        Timber.d("was not able to setCharacteristicNotification");
        return false;
    }

    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(descriptorUuid);
    if (descriptor == null) {
        Timber.d("was not able to getDescriptor");
        return false;
    }

    if (enable) {
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    } else {
        descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
    }

    return gatt.writeDescriptor(descriptor);
}
 
源代码11 项目: JayPS-AndroidApp   文件: Ble.java
/**
     * Enables or disables notification on a give characteristic.
     *
     * @param characteristic Characteristic to act on.
     * @param enabled If true, enable notification.  False otherwise.
     */
    private void setCharacteristicNotification(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
        Log.d(TAG, display(gatt) + " setCharacteristicNotification " + display(characteristic));
        if (mBluetoothAdapter == null || gatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        //if (debug) Log.w(TAG, "setCharacteristicNotification");
        gatt.setCharacteristicNotification(characteristic, enabled);
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        // This is specific to Heart Rate Measurement.
        /*if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())
            || UUID_CSC_MEASUREMENT.equals(characteristic.getUuid())
            || UUID_RSC_MEASUREMENT.equals(characteristic.getUuid())
        ) {*/
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(BLESampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            writeGattDescriptor(gatt, descriptor);
        /*} else {
            if (debug) Log.i(TAG, "unused characteristics2:" + display(gatt, characteristic));
        }*/
    }
 
源代码12 项目: thunderboard-android   文件: BleUtils.java
public static boolean setCharacteristicNotification(BluetoothGatt gatt, UUID serviceUuid, UUID characteristicUuid, UUID descriptorUuid, boolean enable) {
    if (gatt == null) {
        return false;
    }
    BluetoothGattService service = gatt.getService(serviceUuid);
    if (service == null) {
        return false;
    }
    BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUuid);

    if (characteristic == null) {
        Timber.d("could not get characteristic: %s for service: %s", characteristicUuid.toString(), serviceUuid.toString());
        return false;
    }

    if (!gatt.setCharacteristicNotification(characteristic, true)) {
        Timber.d("was not able to setCharacteristicNotification");
        return false;
    }

    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(descriptorUuid);
    if (descriptor == null) {
        Timber.d("was not able to getDescriptor");
        return false;
    }

    if (enable) {
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    } else {
        descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
    }
    return gatt.writeDescriptor(descriptor);
}
 
@Override
public void execute(BluetoothGatt gatt) {
    BluetoothGattCharacteristic characteristic = gatt.getService(mServiceUuid).getCharacteristic(mCharacteristicUuid);
    boolean enable = true;
    gatt.setCharacteristicNotification(characteristic, enable);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(mDescriptorUuid);
    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    gatt.writeDescriptor(descriptor);
}
 
源代码14 项目: xDrip-plus   文件: G5CollectionService.java
private synchronized void doDisconnectMessage(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
       Log.d(TAG, "doDisconnectMessage() start");
       gatt.setCharacteristicNotification(controlCharacteristic, false);
       final DisconnectTxMessage disconnectTx = new DisconnectTxMessage();
       characteristic.setValue(disconnectTx.byteSequence);
       gatt.writeCharacteristic(characteristic);
       gatt.disconnect();
       Log.d(TAG, "doDisconnectMessage() finished");
}
 
源代码15 项目: trigger   文件: NukiCallback.java
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == GATT_SUCCESS) {
        BluetoothGattService service = gatt.getService(this.service_uuid);
        if (service == null) {
            closeConnection(gatt);
            this.listener.onTaskResult(
                setup_id, ReplyCode.REMOTE_ERROR, "Service not found: " + this.service_uuid
            );
            return;
        }

        BluetoothGattCharacteristic characteristic = service.getCharacteristic(this.characteristic_uuid);
        if (characteristic == null) {
            closeConnection(gatt);
            this.listener.onTaskResult(
                setup_id, ReplyCode.REMOTE_ERROR, "Characteristic not found: " + this.characteristic_uuid
            );
            return;
        }

        gatt.setCharacteristicNotification(characteristic, true);
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CCC_DESCRIPTOR_UUID);
        if (descriptor == null) {
            closeConnection(gatt);
            this.listener.onTaskResult(
                setup_id, ReplyCode.REMOTE_ERROR, "Descriptor not found: " + CCC_DESCRIPTOR_UUID
            );
            return;
        }
       
        //Log.i(TAG, "characteristic properties: " + NukiTools.getProperties(characteristic));
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
        boolean ok = gatt.writeDescriptor(descriptor);
        if (!ok) {
            Log.e(TAG, "descriptor write failed");
            closeConnection(gatt);
        }
    } else {
        closeConnection(gatt);
        this.listener.onTaskResult(
            setup_id, ReplyCode.LOCAL_ERROR, "Client not found: " + NukiRequestHandler.getGattStatus(status)
        );
    }
}
 
源代码16 项目: RxCentralBle   文件: CorePeripheral.java
@Nullable
private PeripheralError setCharacteristicNotification(
    BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic characteristic, boolean enable) {

  BluetoothGattDescriptor cccd = characteristic.getDescriptor(CCCD_UUID);
  if (cccd == null) {
    return new PeripheralError(PeripheralError.Code.SET_CHARACTERISTIC_NOTIFICATION_CCCD_MISSING);
  }

  if (!bluetoothGatt.setCharacteristicNotification(characteristic, enable)) {
    return new PeripheralError(PeripheralError.Code.SET_CHARACTERISTIC_NOTIFICATION_FAILED);
  }

  int properties = characteristic.getProperties();
  byte[] value;

  if (enable) {
    if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY)
        == BluetoothGattCharacteristic.PROPERTY_NOTIFY) {
      value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
    } else if ((properties & BluetoothGattCharacteristic.PROPERTY_INDICATE)
        == BluetoothGattCharacteristic.PROPERTY_INDICATE) {
      value = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE;
    } else {
      return new PeripheralError(PeripheralError.Code.SET_CHARACTERISTIC_NOTIFICATION_MISSING_PROPERTY);
    }
  } else {
    value = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;
  }

  characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);

  if (!cccd.setValue(value)) {
    return new PeripheralError(CHARACTERISTIC_SET_VALUE_FAILED);
  }

  if (!bluetoothGatt.writeDescriptor(cccd)) {
    return new PeripheralError(PeripheralError.Code.WRITE_DESCRIPTOR_FAILED, ERROR_STATUS_CALL_FAILED);
  }

  return null;
}
 
源代码17 项目: android-ponewheel   文件: BluetoothUtilImpl.java
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic c, int status) {
    String characteristic_uuid = c.getUuid().toString();
    Timber.d( "BluetoothGattCallback.onCharacteristicRead: CharacteristicUuid=" +
            characteristic_uuid +
            ",status=" + status +
            ",isGemini=" + isGemini);
    if (characteristicReadQueue.size() > 0) {
        characteristicReadQueue.remove();
    }

    // Stability Step 2: In OnCharacteristicRead, if the value is of the char firmware version, parse it's value.
    // If its >= 4034, JUST write the descriptor for the Serial Read characteristic to Enable notifications,
    // and set notify to true with gatt. Otherwise its Andromeda or lower and we can call the method to
    // read & notify all the characteristics we want. (Although I learned doing this that some android devices
    // have a max of 12 notify characteristics at once for some reason. At least I'm pretty sure.)
    // I also set a class-wide boolean value isGemini to true here so I don't have to keep checking if its Andromeda
    // or Gemini later on.
    if (characteristic_uuid.equals(OWDevice.OnewheelCharacteristicFirmwareRevision)) {
        Timber.d("We have the firmware revision! Checking version.");
        if (unsignedShort(c.getValue()) >= 4034) {
            Timber.d("It's Gemini!");
            isGemini = true;
            Timber.d("Stability Step 2.1: JUST write the descriptor for the Serial Read characteristic to Enable notifications");
            BluetoothGattCharacteristic gC = owGatService.getCharacteristic(UUID.fromString(OWDevice.OnewheelCharacteristicUartSerialRead));
            gatt.setCharacteristicNotification(gC, true);
            Timber.d("and set notify to true with gatt...");
            BluetoothGattDescriptor descriptor = gC.getDescriptor(UUID.fromString(OWDevice.OnewheelConfigUUID));
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            gatt.writeDescriptor(descriptor);
        } else {
            Timber.d("It's before Gemini, likely Andromeda - calling read and notify characteristics");
            isGemini = false;
            whenActuallyConnected();
        }
    } else if (characteristic_uuid.equals(OWDevice.OnewheelCharacteristicRidingMode)) {
         Timber.d( "Got ride mode from the main UI thread:" + c.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1));
    }

    //else if (characteristic_uuid.equals(OWDevice.OnewheelCharacteristicUartSerialRead)) {
    //    Timber.d("Got OnewheelCharacteristicUartSerialRead, calling unlockKeyGemini! ");
     //   unlockKeyGemini(gatt, c.getValue());
   // }



    if (BuildConfig.DEBUG) {
        byte[] v_bytes = c.getValue();
        StringBuilder sb = new StringBuilder();
        for (byte b : c.getValue()) {
            sb.append(String.format("%02x", b));
        }
        Timber.d( "HEX %02x: " + sb);
        Timber.d( "Arrays.toString() value: " + Arrays.toString(v_bytes));
        Timber.d( "String value: " + c.getStringValue(0));
        Timber.d( "Unsigned short: " + unsignedShort(v_bytes));
        Timber.d( "getIntValue(FORMAT_UINT8,0) " + c.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0));
        Timber.d( "getIntValue(FORMAT_UINT8,1) " + c.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1));
    }

    mOWDevice.processUUID(c);

    mOWDevice.setBatteryRemaining(mainActivity);

    // Callback to make sure the queue is drained

    if (characteristicReadQueue.size() > 0) {
        gatt.readCharacteristic(characteristicReadQueue.element());
    }

}
 
源代码18 项目: FastBle   文件: BleConnector.java
/**
 * indicate setting
 */
private boolean setCharacteristicIndication(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic,
                                            boolean useCharacteristicDescriptor,
                                            boolean enable,
                                            BleIndicateCallback bleIndicateCallback) {
    if (gatt == null || characteristic == null) {
        indicateMsgInit();
        if (bleIndicateCallback != null)
            bleIndicateCallback.onIndicateFailure(new OtherException("gatt or characteristic equal null"));
        return false;
    }

    boolean success1 = gatt.setCharacteristicNotification(characteristic, enable);
    if (!success1) {
        indicateMsgInit();
        if (bleIndicateCallback != null)
            bleIndicateCallback.onIndicateFailure(new OtherException("gatt setCharacteristicNotification fail"));
        return false;
    }

    BluetoothGattDescriptor descriptor;
    if (useCharacteristicDescriptor) {
        descriptor = characteristic.getDescriptor(characteristic.getUuid());
    } else {
        descriptor = characteristic.getDescriptor(formUUID(UUID_CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR));
    }
    if (descriptor == null) {
        indicateMsgInit();
        if (bleIndicateCallback != null)
            bleIndicateCallback.onIndicateFailure(new OtherException("descriptor equals null"));
        return false;
    } else {
        descriptor.setValue(enable ? BluetoothGattDescriptor.ENABLE_INDICATION_VALUE :
                BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
        boolean success2 = gatt.writeDescriptor(descriptor);
        if (!success2) {
            indicateMsgInit();
            if (bleIndicateCallback != null)
                bleIndicateCallback.onIndicateFailure(new OtherException("gatt writeDescriptor fail"));
        }
        return success2;
    }
}
 
源代码19 项目: microbit   文件: DfuBaseService.java
/**
 * Enables or disables the notifications for given characteristic. This method is SYNCHRONOUS and wait until the
 * {@link android.bluetooth.BluetoothGattCallback#onDescriptorWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattDescriptor, int)} will be called or the connection state will change from {@link #STATE_CONNECTED_AND_READY}. If
 * connection state will change, or an error will occur, an exception will be thrown.
 *
 * @param gatt           the GATT device
 * @param characteristic the characteristic to enable or disable notifications for
 * @param type           {@link #NOTIFICATIONS} or {@link #INDICATIONS}
 * @throws DfuException
 * @throws UploadAbortedException
 */
private void enableCCCD(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int type) throws DeviceDisconnectedException, DfuException, UploadAbortedException {
    final String debugString = type == NOTIFICATIONS ? "notifications" : "indications";
    if (mConnectionState != STATE_CONNECTED_AND_READY)
        throw new DeviceDisconnectedException("Unable to set " + debugString + " state", mConnectionState);

    mReceivedData = null;
    mError = 0;
    if ((type == NOTIFICATIONS && mNotificationsEnabled) || (type == INDICATIONS && mServiceChangedIndicationsEnabled))
        return;

    logi("Enabling " + debugString + "...");
    sendLogBroadcast(LOG_LEVEL_VERBOSE, "Enabling " + debugString + " for " + characteristic.getUuid());

    // enable notifications locally
    gatt.setCharacteristicNotification(characteristic, true);

    // enable notifications on the device
    final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG);
    descriptor.setValue(type == NOTIFICATIONS ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
    sendLogBroadcast(LOG_LEVEL_DEBUG, "gatt.writeDescriptor(" + descriptor.getUuid() + (type == NOTIFICATIONS ? ", value=0x01-00)" : ", value=0x02-00)"));
    gatt.writeDescriptor(descriptor);

    // We have to wait until device receives a response or an error occur
    try {
        synchronized (mLock) {
            while ((((type == NOTIFICATIONS && !mNotificationsEnabled) || (type == INDICATIONS && !mServiceChangedIndicationsEnabled))
                    && mConnectionState == STATE_CONNECTED_AND_READY && mError == 0 && !mAborted) || mPaused)
                mLock.wait();
        }
    } catch (final InterruptedException e) {
        loge("Sleeping interrupted", e);
    }

    if (mAborted)
        throw new UploadAbortedException();

    if (mError != 0)
        throw new DfuException("Unable to set " + debugString + " state", mError);

    if (mConnectionState != STATE_CONNECTED_AND_READY)
        throw new DeviceDisconnectedException("Unable to set " + debugString + " state", mConnectionState);
}
 
源代码20 项目: FastBle   文件: BleConnector.java
/**
 * notify setting
 */
private boolean setCharacteristicNotification(BluetoothGatt gatt,
                                              BluetoothGattCharacteristic characteristic,
                                              boolean useCharacteristicDescriptor,
                                              boolean enable,
                                              BleNotifyCallback bleNotifyCallback) {
    if (gatt == null || characteristic == null) {
        notifyMsgInit();
        if (bleNotifyCallback != null)
            bleNotifyCallback.onNotifyFailure(new OtherException("gatt or characteristic equal null"));
        return false;
    }

    boolean success1 = gatt.setCharacteristicNotification(characteristic, enable);
    if (!success1) {
        notifyMsgInit();
        if (bleNotifyCallback != null)
            bleNotifyCallback.onNotifyFailure(new OtherException("gatt setCharacteristicNotification fail"));
        return false;
    }

    BluetoothGattDescriptor descriptor;
    if (useCharacteristicDescriptor) {
        descriptor = characteristic.getDescriptor(characteristic.getUuid());
    } else {
        descriptor = characteristic.getDescriptor(formUUID(UUID_CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR));
    }
    if (descriptor == null) {
        notifyMsgInit();
        if (bleNotifyCallback != null)
            bleNotifyCallback.onNotifyFailure(new OtherException("descriptor equals null"));
        return false;
    } else {
        descriptor.setValue(enable ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE :
                BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
        boolean success2 = gatt.writeDescriptor(descriptor);
        if (!success2) {
            notifyMsgInit();
            if (bleNotifyCallback != null)
                bleNotifyCallback.onNotifyFailure(new OtherException("gatt writeDescriptor fail"));
        }
        return success2;
    }
}