BTLE Example

It is mandatory­­ that you are working with a device supports API 18 or higher.

AndroidManifest.xml
Declare the following permission in manifest file.

uses-feature android:name=”android.hardware.bluetooth_le” android:required=”true”

uses-permission android:name=”android.permission.BLUETOOTH”
uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”
uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION”
uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION”

How to ­­Get BluetoothAdapter and Enable?

BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()){
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
}

How to discover Devices?

It is an Asynchronous Process.
Device discover method are different for Pre Lollipop and Post Lollipop,So In your code you have to handle that.

How to do in Pre Lollipop?

BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter  bluetoothAdapter = bluetoothManager.getAdapter();
This Method will get called whenever a new device is discovered.
BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {

    @Override

    public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
 runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
};

For Starting and cancelling Discovery use

bluetoothAdapter.startLeScan(leScanCallback);
bluetoothAdapter.stopLeScan(leScanCallback);

How to do in Post Lollipop?

BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
 
ScanCallback scanCallback = new ScanCallback() {

    @Override

    public void onScanResult(int callbackType, ScanResult result) {

    }



    @Override

    public void onBatchScanResults(List results) {

            }



    @Override

    public void onScanFailed(int errorCode) {

        Log.i(TAG ,"onScanFailed "+ errorCode);

    }

};
For Starting and cancelling Discovery use
bluetoothLeScanner.startScan(filters,settings,scanCallback);
where  
ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
List filters = new ArrayList();
bluetoothLeScanner.stopScan(scanCallback);

How to Create BluetoothGattCallback?

Once you found expected bluetooth device,It is time to initiate connection using

BluetoothGatt mBluetoothGatt=bluetoothDevice.connectGatt(this,false,mGattCallback);

What is BluetoothGattCallback?

  • Public API for the Bluetooth GATT Profile.
  • This class provides Bluetooth GATT functionality to enable communication between Bluetooth Smart and Bluetooth Smart ready devices.
  • To connect to a remote peripheral device,Create BluetoothGattCallback and call
    bluetoothDevice.connectGatt(this,false,BluetoothGattCallback) to get instance of this class;
BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

    @Override

    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
//Called when a device connects or disconnects.

    }



    @Override

    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
//Called after client initiates BluetoothGatt.discoverServices()

    }



@Override

 public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//Called when client calls //BluetoothGatt.readCharacteristic(BluetoothGattCharacteristic characteristic);


     

 }


    @Override

    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
//Called when you perform a read or write characteristic operation.

    }

};

Discover Services and Characteristics

        • Once the connection success, BluetoothGattCallback.onConnectionStateChange() will be called with the newState argument set to BluetoothProfile.STATE_CONNECTED
    • After this , BluetoothGatt.discoverServices() can be called.When the device responds, you will receive the callback BluetoothGattCallback.onServicesDiscovered()
List services = bluetoothGatt.getServices();
for (BluetoothGattService service : services) {
         List characteristics = service.getCharacteristics();
}

Notes:

It is always recommended to stop the scan once you found expected device because discovery process will drain android device’s battery.

How to Configure Descriptor?

From characteristic,try to get Descriptor using CLIENT_CHARACTERISTIC_CONFIG()
where CLIENT_CHARACTERISTIC_CONFIG = “00002902-0000-1000-8000-00805f9b34fb”;

Example:

BluetoothGattDescriptor bluetoothGattDescriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
bluetoothGattDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(bluetoothGattDescriptor);

Receiver Notification:

Whenever GATT server sends notification to the android device, BluetoothGattCallback.onCharacteristicChanged() will be called,Inside this callback you will of data sent by GATT Server.

How to Disconnect & Close GATT Client?

BluetoothGatt.disconnect();
BluetoothGatt.close();

Example ::

Basic functionalities of BLE is available in this Github code
https://github.com/kavidriod/BluetoothLowEnergy_Basics

Output:

ble

 

BTLE Example

It is mandatory­­ that you are working with a device supports API 18 or higher.

AndroidManifest.xml
Declare the following permission in manifest file.

uses-feature android:name=”android.hardware.bluetooth_le” android:required=”true”

uses-permission android:name=”android.permission.BLUETOOTH”
uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”
uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION”
uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION”

How to ­­Get BluetoothAdapter and Enable?

BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()){
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
}

How to discover Devices?

It is an Asynchronous Process.
Device discover method are different for Pre Lollipop and Post Lollipop,So In your code you have to handle that.

How to do in Pre Lollipop?

BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter  bluetoothAdapter = bluetoothManager.getAdapter();
This Method will get called whenever a new device is discovered.
BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {

    @Override

    public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
 runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
};

For Starting and cancelling Discovery use

bluetoothAdapter.startLeScan(leScanCallback);
bluetoothAdapter.stopLeScan(leScanCallback);

How to do in Post Lollipop?

BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
 
ScanCallback scanCallback = new ScanCallback() {

    @Override

    public void onScanResult(int callbackType, ScanResult result) {

    }



    @Override

    public void onBatchScanResults(List results) {

            }



    @Override

    public void onScanFailed(int errorCode) {

        Log.i(TAG ,"onScanFailed "+ errorCode);

    }

};
For Starting and cancelling Discovery use
bluetoothLeScanner.startScan(filters,settings,scanCallback);
where  
ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
List filters = new ArrayList();
bluetoothLeScanner.stopScan(scanCallback);

How to Create BluetoothGattCallback?

Once you found expected bluetooth device,It is time to initiate connection using

BluetoothGatt mBluetoothGatt=bluetoothDevice.connectGatt(this,false,mGattCallback);

What is BluetoothGattCallback?

  • Public API for the Bluetooth GATT Profile.
  • This class provides Bluetooth GATT functionality to enable communication between Bluetooth Smart and Bluetooth Smart ready devices.
  • To connect to a remote peripheral device,Create BluetoothGattCallback and call
    bluetoothDevice.connectGatt(this,false,BluetoothGattCallback) to get instance of this class;
BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

    @Override

    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
//Called when a device connects or disconnects.

    }



    @Override

    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
//Called after client initiates BluetoothGatt.discoverServices()

    }



@Override

 public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//Called when client calls //BluetoothGatt.readCharacteristic(BluetoothGattCharacteristic characteristic);


     

 }


    @Override

    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
//Called when you perform a read or write characteristic operation.

    }

};

Discover Services and Characteristics

        • Once the connection success, BluetoothGattCallback.onConnectionStateChange() will be called with the newState argument set to BluetoothProfile.STATE_CONNECTED
    • After this , BluetoothGatt.discoverServices() can be called.When the device responds, you will receive the callback BluetoothGattCallback.onServicesDiscovered()
List services = bluetoothGatt.getServices();
for (BluetoothGattService service : services) {
         List characteristics = service.getCharacteristics();
}

Notes:

It is always recommended to stop the scan once you found expected device because discovery process will drain android device’s battery.

How to Configure Descriptor?

From characteristic,try to get Descriptor using CLIENT_CHARACTERISTIC_CONFIG()
where CLIENT_CHARACTERISTIC_CONFIG = “00002902-0000-1000-8000-00805f9b34fb”;

Example:

BluetoothGattDescriptor bluetoothGattDescriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
bluetoothGattDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(bluetoothGattDescriptor);

Receiver Notification:

Whenever GATT server sends notification to the android device, BluetoothGattCallback.onCharacteristicChanged() will be called,Inside this callback you will of data sent by GATT Server.

How to Disconnect & Close GATT Client?

BluetoothGatt.disconnect();
BluetoothGatt.close();

Example ::

Basic functionalities of BLE is available in this Github code
https://github.com/kavidriod/BluetoothLowEnergy_Basics

Bluetooth LowEnergy

In July 2013, the Android API 18 release introduced support for Bluetooth Low Energy (BTLE).
Bluetooth Low Energy was designed to provide a similar communication range as compared to Bluetooth Classic while using significantly less power.
BTLE devices will go into sleep mode and wake only for connection attempts or events.

Client:

  • The client is the device that initiates GATT Commands and accept responses.
  • For our example,the Android device will act  as the client .However Android BTLE API does allow the Android device to act as the server.

Server:

  • The Server is the device that receives GATT commands or requests and return responses.
  • For example Heartrate monitors,Nonin devices

Characteristic:

  • A Characteristic is a data value transferred between the client and server.
  • For example, in addition to the heart rate measurement, a heart rate monitor can also report its current battery voltage, device name, or serial number.

Service :

  • A service is a group of  Characteristic
  • Many devices implement the Device Information Service.  This service is made up of characteristics such as manufacturer name, model number, serial number, and firmware revision.

Descriptor:

  • A Descriptor provides additional information about a Characteristic.
  • For instance, a temperature value characteristic may have an indication of its units (Celsius or Fahrenheit) or the valid range, the upper and lower values which the sensor can measure.

Attributes:

  • Services, characteristics, and descriptors are collectively referred to as attributes
  • Identified by UUIDs(126 bit number)
  • Format : xxxxXXXX-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  • *Developer always have to concentrate on Highlighted 4 digits.
  • This digits are defined by the Bluetooth Special Interest Group(SIG)

GATT Operations:

  • Discover  UUIDs  for  all  primary  services. : This operation can be used to find if a device supports Device Information Service.
  • Discover all characteristics for a given service : Some BP devices also include battery measurement characteristic.

Read and write descriptors for a particular characteristic :

  • one of the most descriptors used is the “Client Characteristic Configuration Descriptor”.
  • This allows the client to set the notifications to Indicate or notify for a particular Characteristic.
  • It the client sets the notification enabled bit,the server sends a value to the client whenever information becomes available.
  • Setting Indication Enabled bit will also enable the server to send notification when information is available.Only difference is Indicate mode requires a response from the client.

Read and write to a characteristic:

  • A client may read characteristic from BLE device
  • A client may write to a characteristic while upgrading  the firmware of the remote device.

 

Classic

Android provides Bluetooth API to perform several tasks such as:

  • Scanning bluetooth devices.
  • Display list of paired devices.
  • Enable Bluetooth on a device.
  • connect and transfer data from and to other devices.

How to enable Bluetooth in device?

public final static int REQUEST_BLUETOOTH = 1; Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBTIntent,REQUEST_BLUETOOTH);


How to get  Bluetooth Adapter class to communicate with Bluetooth?

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();


How to get List of Paired Bluetooth in Android?

Set bluetoothDevices = bluetoothAdapters.getBondedDevices();


List of important predefined constants in Bluetooth API?

String ACTION_REQUEST_ENABLE : Show a system activity that allows the user to turn on Bluetooth.
String ACTION_REQUEST_DISCOVERABLE : To make android device as Discoverable mode.
String ACTION_DISCOVERY_STARTED : The local Bluetooth adapter has started the remote device discovery process.
String ACTION_DISCOVERY_FINISHED : The local Bluetooth adapter has finished the device discovery process.
String ACTION_STATE_CHANGED : notify that Bluetooth state has been changed
String  ACTION_FOUND : Sent when a remote device is found during discovery

What are all the permissions needed ?

Connect,Disconnect,Transfer Data
uses-permission android:name=“android.permission.BLUETOOTH” />

Disover new devices,Change BT settings
uses-permission android:name=“android.permission.BLUETOOTH_ADMIN” />

Example ::

All above explained functionalities are  available in this Github code
https://github.com/kavidriod/Bluetooth_Basics

Output Screen :

bt_basics

 

bt_basics1

 

————————————————————————————

How to do Scanning?

  • For Discovering nearby devices,invoke startDiscovery() method.
  • For Stopping Discovery ,invoke cancelDiscovery()
  • Discovery takes up lot of resources,If you want to connect to other bluetooth devices,You must stop discovery before connecting.

Role of Broadcast Receiver in Scanning?

  • You have to register receiver when you call startDiscovery()
  • Unregister that when you call cancelDiscovery()
  • Whenever we found Bluetooth device, BluetoothDevice.ACTION_FOUND action will be called.we can handle this action Inside onReceive() of BroadcastReceiver.

BroadcastReceiver scanBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.i(TAG,” action “+intent.getAction()); if (BluetoothDevice.ACTION_FOUND.equals(action)){ BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); } };


Example ::

All Scanning related  functionalities are  available in this Github code
https://github.com/kavidriod/Bluetooth_Scanning

Output Screen :

bt_scan_demo

 

Bluetooth

Bluetooth is a wireless technology standard for exchanging data over short distances

Bluetooth is managed by the Bluetooth Special Interest Group (SIG), which has more than 30,000 member companies in the areas of telecommunication, computing, networking, and consumer electronics

The development of the “short-link” radio technology, later named Bluetooth,

It was initiated in 1989 by Nils Rydbeck, CTO at Ericsson Mobile in Lund, Sweden, and by Johan Ullman

Categories of bluetooth devices

a. ‘Bluetooth Classic’
b. ‘Bluetooth Smart’.

1.Up to and including Bluetooth Version 3, there was only one standard for Bluetooth Radio devices.
2.Bluetooth Version 4 introduced a new standard to sit along-side the original. The new standard is called ‘Bluetooth Low Energy’ or Bluetooth Smart