Working with Bluetooth(BLE) on Android

Working with Bluetooth(BLE) on Android

Getting Started

Recently finalized a project on an Android application using Bluetooth for communication. I might as well share what I learned on the way. Working with Bluetooth on Android was not the easiest for anyone doing the same you might find something useful. Bluetooth Low Energy(BLE) is a recent version of Bluetooth that consumes less energy.

It’s in the name 😅

Basics

First, what kind of communication are you intending: Unilateral(one-way) or Bilateral(two-way)? An example of unilateral communication would be a sensor that only needs to transmit its data to a receiver. For Bilateral communication, Bluetooth headphones receive music stream data from a phone but also transmit control information like Skipping or play/pause to the phone.

Using these two modes the devices act in different profiles:

  • Central: a device that discovers BLE peripherals and broadcasters with the capability of connecting to peripherals.

  • Peripheral: a device that advertises its existence with the capability of accepting connections from a central.

  • Broadcaster: a device that sends out advertising packets without allowing any connections.

  • Observer: a device that discovers peripherals and broadcasters, but without the capability of accepting connections from a central

Permissions

Bluetooth and location permissions will have to be included in the manifest.

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Advertising

The Ble packet is limited in size, having a 2-byte header and a variable payload of 6–37 bytes. After adding the required flags and data, there will be around 21 bytes left to insert your own data.

UUIDs are also critical for distinguishing your packets from those of other devices. The UUID is 128 bits (16 bytes). You can use a UUID generator to create your own.

public static final ParcelUuid Service_UUID = ParcelUuid
        .fromString("6ef0e30d-7308-4458-b62e-f706c692ca77");

Initialize BLE Advertising

BluetoothLeAdvertiser advertiser = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();Build your packet

Build Packet Data

First, configure your packet data part

AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder();
dataBuilder.addServiceUuid(Constants.Service_UUID);//uuid generated
dataBuilder.setIncludeDeviceName(false);// To save on packet space you may not include some data
String userPacketData = Constants.SERVICE_DATA; // custom data to add
dataBuilder.addServiceData(Constants.Service_UUID, userPacketData.getBytes());
dataBuilder.build();

Build Advertising Settings

Configure the advertising settings

AdvertiseSettings.Builder settingsBuilder = new AdvertiseSettings.Builder();
settingsBuilder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_POWER); // saves on battery power
settingsBuilder.setConnectable(false);// set to true to connect to other ble devices
settingsBuilder.setTimeout(10000); //set to 0 to continously advertise
settingsBuilder.build();

Build the callback

The callback is needed to listen to successes or failures when advertising.

private class SampleAdvertiseCallback extends AdvertiseCallback {

    @Override
    public void onStartFailure(int errorCode) {
        super.onStartFailure(errorCode);

        Log.d(TAG, "Advertising failed");
        sendFailureIntent(errorCode);
        stopSelf();

    }

    @Override
    public void onStartSuccess(AdvertiseSettings settingsInEffect) {
        super.onStartSuccess(settingsInEffect);
        Log.d(TAG, "Advertising successfully started");
    }
}

Start Advertising



if (mAdvertiseCallback == null) {
    AdvertiseSettings settings = buildAdvertiseSettings();
    AdvertiseData data = buildAdvertiseData();
    mAdvertiseCallback = new SampleAdvertiseCallback();

    if (mBluetoothLeAdvertiser != null) {
        mBluetoothLeAdvertiser.startAdvertising(settings, data,
            mAdvertiseCallback);
    }
}

Conclusion

This is how to set up BLE advertising. You will need an actual smartphone as the emulator does not support Bluetooth.

In the next article, we’ll handle the scanning of these packets.