メインコンテンツまでスキップ

Bluetooth Low Energy Examples

Introduction to Bluetooth Low Energy in Android

Bluetooth Low Energy (BLE) is a wireless communication protocol designed for low power consumption. It is ideal for IoT devices, wearables, and other battery-powered devices. Android provides an easy way to use BLE in your applications. In this article, we will go through the steps to use BLE in Android applications.

Setting up the environment

Before we start, we need to set up our environment. We need to make sure that we have the latest version of Android Studio installed. We also need to add the necessary dependencies to our build.gradle file. Here are the dependencies we need to add:

implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.polidea.rxandroidble2:rxandroidble:1.9.0'

Scanning for BLE devices

The first step in using BLE in Android is to scan for BLE devices. To do this, we need to create an instance of the RxBleClient class. Here's how we can do it:

val rxBleClient = RxBleClient.create(context)

Next, we need to create an instance of the ScanSettings class. We can configure the scan settings according to our requirements. Here's an example:

val scanSettings = ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
.build()

Now, we can start scanning for BLE devices using the scanBleDevices method of the RxBleClient class. We need to pass the scanSettings object and a ScanFilter object to filter the devices we are interested in. Here's an example:

rxBleClient.scanBleDevices(scanSettings, scanFilter)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ scanResult ->
// Handle the scan result
}, { throwable ->
// Handle the error
})

Connecting to a BLE device

Once we have scanned for BLE devices and found the one we want to connect to, we need to connect to it. To do this, we need to create an instance of the RxBleDevice class. Here's how we can do it:

val rxBleDevice = rxBleClient.getBleDevice(deviceAddress)

Next, we can call the connect method of the RxBleDevice class to establish a connection. Here's an example:

rxBleDevice.connect()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ rxBleConnection ->
// Handle the connection
}, { throwable ->
// Handle the error
})

Reading and writing data

Once we have established a connection to the BLE device, we can read and write data to it. To read data, we need to call the readCharacteristic method of the RxBleConnection class. Here's an example:

rxBleConnection.readCharacteristic(characteristicUuid)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ characteristicValue ->
// Handle the read value
}, { throwable ->
// Handle the error
})

To write data, we need to call the writeCharacteristic method of the RxBleConnection class. Here's an example:

rxBleConnection.writeCharacteristic(characteristicUuid, data)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ characteristicValue ->
// Handle the write value
}, { throwable ->
// Handle the error
})

More Examples

Learn about BLE or Bluetooth Low Energy using the following examples.

Example 1: Android Bluetooth Low Energy Example

This is a simple example written in java.

Step 1: Create Project

  1. Open your Android Studio IDE.
  2. In the menu go to File --> Create New Project.
  3. Choose Empty Project template.

Step 2: Add Dependencies

No special dependencies are needed for this project.

Step 3: Design Layouts

Go to your res/layout directory so as to design your user interface.

We have only 1 layout:

  1. activity_main.xml

First create a file known as activity_main.xml and add the following code:

(a). activity_main.xml

Specify the root element as a LinearLayout. Then add buttons, textview and spinner:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">


<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/bluetooth_on"
android:id="@+id/btnbleon"
android:layout_gravity="center_horizontal"
android:padding="@dimen/_10dp"
android:layout_margin="@dimen/_10dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/bluetooth_off"
android:id="@+id/btnbleoff"
android:layout_gravity="center_horizontal"
android:padding="@dimen/_10dp"
android:layout_margin="@dimen/_10dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/bluetooth_dis"
android:id="@+id/btnbledis"
android:layout_gravity="center_horizontal"
android:padding="@dimen/_10dp"
android:layout_margin="@dimen/_10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/available_devices"/>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/spinner">

</Spinner>


</LinearLayout>

Step 4: Write Code

Next create a file known as MainActivity.java and add the following code:

Start by specifying imports including android.bluetooth.BluetoothAdapter and android.bluetooth.BluetoothDevice:

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;

Extend the AppCompatActivity:

public class MainActivity extends AppCompatActivity {

Declare the widgets as well as the BluetoothAdapter:

    private Button mbtnBLEOn,mbtnBLEOff,mbtnBLEDiscover;
private Spinner mspinnerAvailableDev;
private BluetoothAdapter mBluetoothAdapter;

Override the onCreateand initialize the widgets. Initialize the BluetoothAdapter using the getDefaultAdapter() method:

    @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
mbtnBLEOn=findViewById(R.id.btnbleon);
mbtnBLEOff=findViewById(R.id.btnbleoff);
mbtnBLEDiscover=findViewById(R.id.btnbledis);
mspinnerAvailableDev=findViewById(R.id.spinner);

When the On button is clicked, first check that bluetoothAdapter is not enabled. If so then enable it by instantiating an Intent object and passing in the BluetoothAdapter.ACTION_REQUEST_ENABLE,then passing the Intent to the startActivityForResult():

        mbtnBLEOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!mBluetoothAdapter.isEnabled()){
Intent i=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(i,0);
Toast.makeText(MainActivity.this, "Bluetooth turned on!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Bluetooth already on!", Toast.LENGTH_SHORT).show();
}
}
});

If off button is clicked switch off bluetooth by invoking the disable() method:

        mbtnBLEOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBluetoothAdapter.disable();
Toast.makeText(MainActivity.this, "Bluetooth turned off!", Toast.LENGTH_SHORT).show();
}
});

If the discover button is clicked do the following:

        mbtnBLEDiscover.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent i=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(i,1);

ArrayList<String> devices=new ArrayList<>();
for(BluetoothDevice btDevice:mBluetoothAdapter.getBondedDevices()){
devices.add(btDevice.getName());

}
ArrayAdapter<String> adapter=new ArrayAdapter<>(MainActivity.this,R.layout.support_simple_spinner_dropdown_item,devices);
mspinnerAvailableDev.setAdapter(adapter);
}
});

}
}

Here is the full code:

MainActivity.java

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
private Button mbtnBLEOn,mbtnBLEOff,mbtnBLEDiscover;
private Spinner mspinnerAvailableDev;
private BluetoothAdapter mBluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
mbtnBLEOn=findViewById(R.id.btnbleon);
mbtnBLEOff=findViewById(R.id.btnbleoff);
mbtnBLEDiscover=findViewById(R.id.btnbledis);
mspinnerAvailableDev=findViewById(R.id.spinner);
mbtnBLEOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!mBluetoothAdapter.isEnabled()){
Intent i=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(i,0);
Toast.makeText(MainActivity.this, "Bluetooth turned on!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Bluetooth already on!", Toast.LENGTH_SHORT).show();
}
}
});
mbtnBLEOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBluetoothAdapter.disable();
Toast.makeText(MainActivity.this, "Bluetooth turned off!", Toast.LENGTH_SHORT).show();
}
});
mbtnBLEDiscover.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent i=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(i,1);

ArrayList<String> devices=new ArrayList<>();
for(BluetoothDevice btDevice:mBluetoothAdapter.getBondedDevices()){
devices.add(btDevice.getName());

}
ArrayAdapter<String> adapter=new ArrayAdapter<>(MainActivity.this,R.layout.support_simple_spinner_dropdown_item,devices);
mspinnerAvailableDev.setAdapter(adapter);
}
});

}
}

Run

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

NumberLink
1.Download Example
2.Follow code author
3.Code: Apache 2.0 License

Conclusion

In this article, we have gone through the steps to use Bluetooth Low Energy in Android applications. We have seen how to scan for BLE devices, connect to them, and read and write data. With this knowledge, you can start building your own BLE-enabled Android applications.