Getting Started with Bluetooth Low Energy (BLE) in Android

nirav_panchal_e531c758f1d

Nirav Panchal

Posted on June 10, 2024

Getting Started with Bluetooth Low Energy (BLE) in Android

Image descriptionIntroduction
Bluetooth Low Energy (BLE) is a wireless communication technology designed for short-range communication with low power consumption. It’s widely used in various applications, including fitness trackers, smart home devices, and health monitors. In this tutorial, you will learn how to integrate BLE technology into an Android application, from setting up the development environment to creating a simple BLE scanner.

By the end of this guide, you'll be able to:

Understand BLE basics and its use cases.
Set up your Android project to support BLE.
Scan for BLE devices and display their information.
Prerequisites
Before you start, make sure you have:

Basic knowledge of Android development.
Android Studio installed on your machine.
An Android device with BLE support for testing.
Setting Up Your Development Environment
Step 1: Check BLE Support
Before developing a BLE app, you need to ensure that your device and application support BLE.

Check if your device supports BLE:



val hasBLE = packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)
if (!hasBLE) {
    Toast.makeText(this, "BLE not supported", Toast.LENGTH_SHORT).show()
    finish()
}


Enter fullscreen mode Exit fullscreen mode


val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
val bluetoothAdapter = bluetoothManager.adapter

if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled) {
    val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}



Enter fullscreen mode Exit fullscreen mode

`

Sure! Here’s a comprehensive post on how to use Bluetooth Low Energy (BLE) technology in Android development. This post will cover the basics, setup, and a step-by-step guide to creating a simple BLE application. You can use this as a draft for your DEV Community post.

Getting Started with Bluetooth Low Energy (BLE) in Android
Introduction
Bluetooth Low Energy (BLE) is a wireless communication technology designed for short-range communication with low power consumption. It’s widely used in various applications, including fitness trackers, smart home devices, and health monitors. In this tutorial, you will learn how to integrate BLE technology into an Android application, from setting up the development environment to creating a simple BLE scanner.

By the end of this guide, you'll be able to:

Understand BLE basics and its use cases.
Set up your Android project to support BLE.
Scan for BLE devices and display their information.
Prerequisites
Before you start, make sure you have:

Basic knowledge of Android development.
Android Studio installed on your machine.
An Android device with BLE support for testing.
Setting Up Your Development Environment
Step 1: Check BLE Support
Before developing a BLE app, you need to ensure that your device and application support BLE.

Check if your device supports BLE:
kotlin
Copy code
val hasBLE = packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)
if (!hasBLE) {
Toast.makeText(this, "BLE not supported", Toast.LENGTH_SHORT).show()
finish()
}
Request Bluetooth and Location permissions in your AndroidManifest.xml:
xml
Copy code



Add the BLE feature requirement:
xml
Copy code

Step 2: Initialize Bluetooth Adapter
Initialize the Bluetooth adapter in your MainActivity to start working with BLE.

kotlin
Copy code
val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
val bluetoothAdapter = bluetoothManager.adapter

if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
Building a BLE Scanner
Step 1: Create the Layout
Create a simple layout in activity_main.xml to display scanned BLE devices.

xml
Copy code
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<Button
    android:id="@+id/scanButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start Scanning" />

<ListView
    android:id="@+id/deviceListView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="16dp"/>
Enter fullscreen mode Exit fullscreen mode


Step 2: Implement BLE Scanning
In your MainActivity, implement the BLE scanning functionality.

kotlin
Copy code
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.Context
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.ListView

class MainActivity : Activity() {
private lateinit var bluetoothAdapter: BluetoothAdapter
private lateinit var deviceListView: ListView
private lateinit var scanButton: Button
private lateinit var deviceAdapter: ArrayAdapter

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
    bluetoothAdapter = bluetoothManager.adapter

    deviceListView = findViewById(R.id.deviceListView)
    scanButton = findViewById(R.id.scanButton)
    deviceAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1)
    deviceListView.adapter = deviceAdapter

    scanButton.setOnClickListener {
        startBLEScan()
    }
}

private fun startBLEScan() {
    deviceAdapter.clear()
    val scanner = bluetoothAdapter.bluetoothLeScanner
    scanner.startScan(leScanCallback)
}

private val leScanCallback = object : ScanCallback() {
    override fun onScanResult(callbackType: Int, result: ScanResult?) {
        super.onScanResult(callbackType, result)
        result?.device?.let {
            val deviceInfo = "${it.name ?: "Unknown"} - ${it.address}"
            if (!deviceAdapter.contains(deviceInfo)) {
                deviceAdapter.add(deviceInfo)
                deviceAdapter.notifyDataSetChanged()
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

}
Step 3: Handle Permissions (Android 6.0+)
Handle runtime permissions for Bluetooth and Location on Android Marshmallow and above.

kotlin
Copy code
private val REQUEST_PERMISSIONS = 1

override fun onStart() {
super.onStart()
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_PERMISSIONS)
}
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_PERMISSIONS && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startBLEScan()
}
}
Conclusion
Congratulations! You’ve just built a simple BLE scanner app that can discover nearby BLE devices. This app provides a foundation for more advanced BLE functionalities such as connecting to devices, reading characteristics, and even controlling BLE peripherals.

BLE technology opens up a world of possibilities for IoT and wearable devices. By integrating BLE into your Android applications, you can create innovative solutions for various domains like health, fitness, and smart home.

Further Reading and Resources

Android Bluetooth Low Energy Guide

Bluetooth Low Energy in Android: A Step-by-Step Guide
Bluetooth LE Fundamentals
Feel free to leave a comment below with your questions or share your experiences with BLE in Android development. Happy coding!

💖 💪 🙅 🚩
nirav_panchal_e531c758f1d
Nirav Panchal

Posted on June 10, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related