Posted onEdited onInApp DevelopmentViews: Word count in article: 499Reading time ≈2 mins.
When I was in university, I had developed a BLE based UAV controller based on an open source Android BLE library. The library itself is quite easy to use but I decided to develop an Android BLE app with native Android BLE API, which can connect and communicate with BLE GATT devices.
privatestaticfinalUUIDmServiceUuid= UUID.fromString(SERVICE_UUID); privatestaticfinalintREQUEST_MTU=64; // Get from ScanCallback: result.getDevice(); private BluetoothDevice mDevice;
mDeviceGatt = mDevice.connectGatt(mContext, false, newBluetoothGattCallback() { @Override publicvoidonConnectionStateChange(BluetoothGatt gatt, int status, int newState) { switch (newState) { case BluetoothProfile.STATE_CONNECTED: // If connected we start to discover services provided by device gatt.discoverServices(); break; case BluetoothProfile.STATE_CONNECTING: break; case BluetoothProfile.STATE_DISCONNECTED: default: gatt.close(); } }
@Override publicvoidonServicesDiscovered(BluetoothGatt gatt, int status) { if (gatt.getService(mServiceUuid) != null) { // service found, request for increasing MTU gatt.requestMtu(REQUEST_MTU); } }
@Override publicvoidonMtuChanged(BluetoothGatt gatt, int mtu, int status) { Log.d(TAG, "MTU changed to " + mtu); } });
The default MTU for ATT is 23 bytes. In those 23 bytes, there are 20 bytes for GATT. To send/receive data more than 20 bytes at once, we need to call requestMtu to increase MTU.
Read/Write characteristic
Blow code shows how to read characteristic:
1 2 3 4 5 6 7
// Here we get all available characteristics in this service List<BluetoothGattCharacteristic> characteristics = gatt.getService(mServiceUuid).getCharacteristics();
// Try to read the first characteristic if (!mThing.mDeviceGatt.readCharacteristic(characteristics.get(0))) { Log.e("TAG", "Read characteristic error"); }
characteristic.setValue(); mDeviceGatt.writeCharacteristic("data to write".getBytes());
Once operation is done, onCharacteristicRead / onCharacteristicWrite will be called.
Note: There is only one operation is allowed at a time. If we need to implement a complex logic with a lot of read/write operations, suggestion will be use a message queue.