Essential Android Bluetooth Low Energy (LE) edit forum

Writing and Reading from Characteristics

Once you are connected to a Gatt Server, you’re going to be interacting with it by writing and reading from the server’s characteristics. To do this, first you have to discover what services are available on this server and which characteristics are avaiable in each service:

@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
       int newState) {
   if (newState == BluetoothProfile.STATE_CONNECTED) {
       Log.i(TAG, "Connected to GATT server.");
       gatt.discoverServices();

   }
. . .

@Override
   public void onServicesDiscovered(BluetoothGatt gatt, int status) {
       if (status == BluetoothGatt.GATT_SUCCESS) {
            List<BluetoothGattService> services = gatt.getServices();
               for (BluetoothGattService service : services) {
                   List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
                   for (BluetoothGattCharacteristic characteristic : characteristics) { 
                       ///Once you have a characteristic object, you can perform read/write
                       //operations with it         
                   }
                }
             }
           }

A basic write operation goes like this:

characteristic.setValue(newValue);
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
gatt.writeCharacteristic(characteristic);

When the write process has finished, the onCharacteristicWrite method of your BluetoothGattCallback will be called:

@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicWrite(gatt, characteristic, status);
    Log.d(TAG, "Characteristic " + characteristic.getUuid() + " written);
}

A basic write operation goes like this:

gatt.readCharacteristic(characteristic);

When the write process has finished, the onCharacteristicRead method of your BluetoothGattCallback will be called:

@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
  super.onCharacteristicRead(gatt, characteristic, status);
  byte[] value = characteristic.getValue();
  }

Table Of Contents
39 ACRA
64 Menu
112 Loader
119 Xposed
132 Colors
135 Fresco
140 AdMob
147 Button
156 Vk SDK
170 XMPP
176 OpenCV
200 FileIO
203 Moshi
217 Paint
231 AIDL
241 JCodec
243 Okio
248 Bluetooth Low Energy (LE)
255 Looper
  ↑ ↓ to navigate     ↵ to select     Esc to close