Bluetooth Low Energy: Easy-to-Follow Setup on Android

TD;LR

Bluetooth Low Energy (BLE) is a wireless communication protocol optimized for low power consumption, making it ideal for wearables, healthcare devices, and IoT applications.
BLE differs from Classic Bluetooth primarily in its short-burst communication model and significantly reduced energy usage.
Setting up a BLE Android app involves four core components: initialization, central management, device discovery and connection, and data parsing.
Securing a BLE application requires the right pairing mode (avoid Just Works for sensitive data), encrypted connections, and correct Android 12+ permission handling.
The BluetoothHandler class is the central piece of any Android BLE implementation — it manages connections, pairing, data transfer, and broadcasting measurements.

1. Introduction

Welcome aboard! If you've ever wondered about the incredible potential of Android BLE apps, you're in the right place. Bluetooth Low Energy (BLE) has completely transformed how devices connect and communicate, opening a world of possibilities. 

Why am I diving into this world of Android BLE apps? Because it's not just about technology – it's about the potential impact of this technology in our day-to-day lives. Whether you're driven by curiosity, eager to create the next big thing, or simply want to understand the technology that surrounds you, this blog post should resonate with you. 

Together, we'll unravel the inner workings of Android BLE apps. I'll guide you through BLE's intricacies and show you how to build apps that stand out. From conserving energy to ensuring secure communication, I'll equip you with the tools to craft powerful Android BLE applications.  

2. Understanding Bluetooth Low Energy (BLE)

The world relies on connectivity more than ever, and Bluetooth Low Energy (BLE) has become a key player in enabling seamless communication between devices. But what exactly is BLE, and how does it differ from traditional Bluetooth

2.1. What is Bluetooth Low Energy?

Before we delve into Bluetooth Low Energy, let's briefly touch on the basics of Bluetooth technology. Bluetooth, named after a 10th-century Danish king known for uniting tribes, is a wireless communication protocol that allows devices to exchange data over short distances. It was initially designed to connect peripherals like keyboards, mice, and headsets to computers and mobile devices. 

2.2. BLE vs. Classic Bluetooth: Key Differences

Traditional Bluetooth, often referred to as "Classic" Bluetooth, served its purpose well, but it had its limitations. One of the primary challenges was its relatively high power consumption, making it unsuitable for devices that need to conserve energy. 

Bluetooth Low Energy, often abbreviated as BLE, is a wireless communication technology optimized for low power consumption. Introduced with the Bluetooth 4.0 specification (also known as Bluetooth 4.0 Low Energy), BLE addresses the limitations of classic Bluetooth, particularly its high power usage. This makes BLE ideal for devices that need to conserve battery life, such as wearables, health monitors, and even Bluetooth Low Energy beacons.  

While classic Bluetooth excels in connecting peripherals like keyboards and headsets to computers and phones, its power consumption isn't ideal for battery-powered devices. BLE solves this issue by focusing on: 

  • Short-Burst Communication: BLE devices communicate in brief bursts rather than maintaining a constant connection. This reduces energy use significantly. 

  • Power Efficiency: By minimizing the time spent actively transmitting or receiving data, BLE drastically reduces power consumption, making it perfect for devices needing extended battery life. 

  • Simplified Profiles: Compared to classic Bluetooth, BLE uses a streamlined set of profiles and services. This simplifies development and customization for various functionalities, including those used in Bluetooth low energy audio. 

  • Data Range: BLE is optimized for short-range communication, typically within 10-100 meters. This makes it suitable for applications where devices are in proximity, like using a Bluetooth low energy beacon for indoor navigation. 

2.3. Applications of Bluetooth Low Energy

The development of BLE has opened doors for innovation in various fields: 

  • Wearables and Fitness Trackers: BLE's low power consumption allows wearables to stay connected for extended periods without frequent charging. 

  • Smart Home Devices: BLE plays a role in connecting smart home devices like thermostats and lights, enabling them to communicate with each other and central hubs efficiently. 

  • Healthcare Applications: BLE can be used in medical devices for data transmission, such as monitoring heart rate or blood pressure. 

  • Bluetooth Low Energy Beacons: These small transmitters leverage BLE to broadcast signals for location-based services and proximity marketing. 

3. Setting Up a BLE Android App: Step-by-Step
3.1. Initialization

First, we will create the BluetoothHandler class which is initialized with a Context and an optional OMRON instance. The Context is essential for Bluetooth operations within the Android environment, while OMRON is an external library that enables communication with OMRON health devices. 

internal class BluetoothHandler private constructor(private val context: Context, private val omron: OMRON?) { 

    // ... 

} 
3.2. Bluetooth Central Management

The central aspect of the 'BluetoothHandler' class is the management of BLE central operations. It utilizes the 'BluetoothCentralManager' from the 'com.welie.blessed' library to handle Bluetooth device connections, disconnections, and scanning. 

central = BluetoothCentralManager(context, bluetoothCentralManagerCallback, Handler(Looper.getMainLooper())) 
3.3. Device Discovery and Connection

The 'BluetoothHandler' class is responsible for discovering nearby BLE health devices and establishing connections. When a peripheral device is discovered, it processes the device information, including its type, and decides whether to connect to it. 

override fun onDiscoveredPeripheral(peripheral: BluetoothPeripheral, scanResult: ScanResult) { 

    // ... 

} 
3.4. Device Pairing and Unpairing

The 'BluetoothHandler' class facilitates the pairing and unpairing of health devices. It responds to pairing and unpairing requests through the 'deviceToPair' and 'deviceToUnpair' subjects.  

deviceToPair.subscribe { 

    central?.apply { 

        startPairingPopupHack() 

        autoConnectPeripheral(getPeripheral(it.mac), peripheralCallback) 

        connectPeripheral(getPeripheral(it.mac), peripheralCallback) 

        createBond(getPeripheral(it.mac), peripheralCallback) 

    } 

}.disposeBy(compositeDisposable) 

 

deviceToUnpair.subscribe { 

    central?.removeBond(it.mac) 

}.disposeBy(compositeDisposable) 

3.5. Data Transfer 

For specific devices like OMRON health devices, data transfer is initiated by the 'BluetoothHandler' class. It ensures that data transfer is performed at the right intervals. 

handler.postDelayed({ 

    omron?.performDataTransfer(peripheralDevice) 

    transferOmronData = true 

}, PERFORM_OMRON_TRANSFER) 
3.5.Data Parsing

The 'BluetoothHandler' class is responsible for parsing the data received from connected devices. It distinguishes between various types of measurements such as blood pressure, temperature, heart rate, pulse oximetry, glucose, and more. 

override fun onCharacteristicUpdate( 

    peripheral: BluetoothPeripheral, value: ByteArray, characteristic: BluetoothGattCharacteristic, status: GattStatus 

) { 

    // ... 

} 
3.6.Broadcasting Measurements

Once data is parsed, the 'BluetoothHandler' class broadcasts these measurements to the application, allowing it to display or store the health data as needed.  

private fun sendMeasurement(intent: Intent, peripheral: BluetoothPeripheral) { 

    if (healthDevices?.contains(peripheral.address) == true || peripheral.bondState == BondState.BONDED) { 

        intent.putExtra(MEASUREMENT_EXTRA_PERIPHERAL, peripheral.address) 

        context.applicationContext.sendBroadcast(intent) 

    } 

} 

4. Securing Your BLE Android Application

BLE communication is inherently wireless, which makes security a critical consideration for any production application. The most common vulnerabilities in BLE apps are man-in-the-middle (MITM) attacks, eavesdropping on unencrypted connections, and unauthorized device access.

4.1. Android BLE Permission Model (Android 12+)

Starting with Android 12 (API level 31), the Bluetooth permission model changed significantly. Instead of relying on location permissions for device scanning, apps now use dedicated Bluetooth permissions:

BLUETOOTH_SCAN — required to discover nearby BLE devices
BLUETOOTH_CONNECT — required to connect to paired devices
BLUETOOTH_ADVERTISE — required if your app advertises as a BLE peripheral

Always request only the permissions your app actually needs, and handle permission denial gracefully in your UI.
 

4.2. Pairing and Bonding Modes

BLE supports several pairing modes, each with different security tradeoffs:

Just Works — no user interaction required, but offers no MITM protection. Suitable only for non-sensitive data.
Passkey Entry — the user enters a PIN displayed on one device. Provides MITM protection.
Numeric Comparison — both devices display a number that the user confirms. The strongest pairing mode for interactive devices.

For healthcare and enterprise applications, Just Works should be avoided. Use Passkey Entry or Numeric Comparison wherever the data being transmitted is sensitive.

4.3. Encrypted Connections

Once a bond is established, Android's BLE stack can automatically encrypt the connection. To ensure encryption is active before reading or writing sensitive characteristics, check the bond state before initiating data transfer:

if (peripheral.bondState == BondState.BONDED) {
   // safe to read/write sensitive characteristics
}

4.4. Common BLE Security Vulnerabilities to Avoid

Unencrypted characteristics — never transmit sensitive data over unencrypted BLE characteristics, even if the connection is bonded.
Open advertisement — avoid broadcasting sensitive device information in BLE advertisement packets.
No input validation — always validate and sanitize data received from BLE peripherals before processing it, as malformed packets can cause crashes or unexpected behavior.
Hardcoded credentials — never embed pairing keys or device credentials directly in your application code.a

5. Conclusions and Next Steps

Exploring the world of Android BLE apps has uncovered the transformative potential of Bluetooth Low Energy. BLE's energy efficiency has revolutionized device connectivity, fueling innovations in wearables, health tech, and IoT. 

The journey through building an Android BLE app showcased the crucial role of the BluetoothHandler class in managing Bluetooth operations, device connections, and data transfer. It highlighted BLE's ability to enable precise health data exchange efficiently. 

This exploration emphasizes how BLE empowers applications to seamlessly interpret device data, providing valuable insights for users. The journey underscores the fusion of technology and purpose, driving the creation of impactful, user-centric applications. 
 
Exploring Bluetooth Low Energy Further 

With its focus on low power consumption, BLE has become a cornerstone of our interconnected world. If you're interested in delving deeper, you can explore topics like: 

  • Bluetooth Low Energy Devices: Learn about the different types of devices that utilize BLE technology. 

  • Bluetooth Low Energy Communication Protocol: Understand the technical details of how BLE devices communicate with each other. 

  • Bluetooth Low Energy with Arduino: Explore how to integrate BLE functionalities into your Arduino projects (if applicable to your interests). 

In conclusion, Android BLE apps stand as a testament to the boundless opportunities for innovation, shaping a future where efficient connectivity drives technological advancement. 

Frequently Asked Questions

  1. What is the difference between BLE and Classic Bluetooth?
    Classic Bluetooth is designed for continuous, high-bandwidth connections such as audio streaming and file transfer. Bluetooth Low Energy (BLE) is optimized for short-burst communication with minimal power consumption, making it ideal for wearables, health monitors, and IoT devices that need extended battery life.
     
  2. What Android permissions are required for BLE development?
    Starting with Android 12 (API level 31), BLE apps require BLUETOOTH_SCAN to discover devices, BLUETOOTH_CONNECT to connect to paired devices, and BLUETOOTH_ADVERTISE if the app broadcasts as a peripheral. Earlier versions required location permissions for device scanning.
     
  3. How do I secure a BLE application on Android?
    Use Passkey Entry or Numeric Comparison pairing modes instead of Just Works for sensitive data. Ensure connections are encrypted before reading or writing sensitive characteristics, validate all incoming data from peripherals, and never hardcode pairing credentials in your application code.
     
  4. What is a GATT profile in BLE?
    GATT (Generic Attribute Profile) defines how BLE devices exchange data. It organizes data into services and characteristics. A service group relates functionality, and characteristics are the individual data points that can be read, written, or subscribed to for notifications.

Share on:

I have read and understood the ASSIST Software website's Terms of Use and Privacy Policy.

Want to stay on top of everything?

Get updates on industry developments and the software solutions we can now create for a smooth digital transformation.

Frequently Asked Questions

1. Can you integrate AI into an existing software product?

Absolutely. Our team can assess your current system and recommend how artificial intelligence features, such as automation, recommendation engines, or predictive analytics, can be integrated effectively. Whether it's enhancing user experience or streamlining operations, we ensure AI is added where it delivers real value without disrupting your core functionality.

2. What types of AI projects has ASSIST Software delivered?

We’ve developed AI solutions across industries, from natural language processing in customer support platforms to computer vision in manufacturing and agriculture. Our expertise spans recommendation systems, intelligent automation, predictive analytics, and custom machine learning models tailored to specific business needs.

3. What is ASSIST Software's development process?  

The Software Development Life Cycle (SDLC) we employ defines the stages for a software project. Our SDLC phases include planning, requirement gathering, product design, development, testing, deployment, and maintenance.

4. What software development methodology does ASSIST Software use?  

ASSIST Software primarily leverages Agile principles for flexibility and adaptability. This means we break down projects into smaller, manageable sprints, allowing continuous feedback and iteration throughout the development cycle. We also incorporate elements from other methodologies to increase efficiency as needed. For example, we use Scrum for project roles and collaboration, and Kanban boards to see workflow and manage tasks. As per the Waterfall approach, we emphasize precise planning and documentation during the initial stages.

5. I'm considering a custom application. Should I focus on a desktop, mobile or web app?  

We can offer software consultancy services to determine the type of software you need based on your specific requirements. Please explore what type of app development would suit your custom build product.   

  • A web application runs on a web browser and is accessible from any device with an internet connection. (e.g., online store, social media platform)   
  • Mobile app developers design applications mainly for smartphones and tablets, such as games and productivity tools. However, they can be extended to other devices, such as smartwatches.    
  • Desktop applications are installed directly on a computer (e.g., photo editing software, word processors).   
  • Enterprise software manages complex business functions within an organization (e.g., Customer Relationship Management (CRM), Enterprise Resource Planning (ERP)).

6. My software product is complex. Are you familiar with the Scaled Agile methodology?

We have been in the software engineering industry for 30 years. During this time, we have worked on bespoke software that needed creative thinking, innovation, and customized solutions. 

Scaled Agile refers to frameworks and practices that help large organizations adopt Agile methodologies. Traditional Agile is designed for small, self-organizing teams. Scaled Agile addresses the challenges of implementing Agile across multiple teams working on complex projects.  

SAFe provides a structured approach for aligning teams, coordinating work, and delivering value at scale. It focuses on collaboration, communication, and continuous delivery for optimal custom software development services. 

7. How do I choose the best collaboration model with ASSIST Software?  

We offer flexible models. Think about your project and see which model would be right for you.   

  • Dedicated Team: Ideal for complex, long-term projects requiring high continuity and collaboration.   
  • Team Augmentation: Perfect for short-term projects or existing teams needing additional expertise.   
  • Project-Based Model: Best for well-defined projects with clear deliverables and a fixed budget.   

Contact us to discuss the advantages and disadvantages of each model. 

ASSIST Software Team Members