
Android Bluetooth LE Scanner is a powerful tool that allows you to scan and discover nearby Bluetooth Low Energy devices. This technology has become increasingly popular in recent years, especially with the rise of IoT devices.
To use an Android Bluetooth LE Scanner, you'll need a device that supports Bluetooth 4.0 or later. This is because Bluetooth LE is a feature of the Bluetooth 4.0 standard.
The scanner will allow you to see a list of nearby devices, including their names and addresses. You can also use the scanner to scan for specific devices, such as a particular model of smartwatch.
One thing to keep in mind is that the scanner may not work properly if there are physical barriers between your device and the device you're trying to scan.
Expand your knowledge: Le Creuset
Project Setup
Let's get started with setting up our project. Create a new project in Android Studio, choosing Empty Activity, and name it whatever you like.
For apps that utilize the BLE APIs, it's recommended to use Kotlin as the main language. The lowest minimum API level you can support is 21 (Android 5.0 Lollipop), but 29 (Android 10) will do just fine too.
Ensure "Use androidx.* artifacts" is checked in the project wizard, and if you're working on an existing project, make sure you've migrated to AndroidX.
Discover more: How to Use Google Drive on Android
Explore further: Android Studio Hedgehog
Setting Up Your Project
To set up your project, create a new project in Android Studio, choosing Empty Activity, and name it whatever you like.
Select API 31 as the Minimum SDK, which is the latest feature you can experiment with.
If you need to use an earlier version of the SDK, you won't have to change much of the code.
For apps that utilize the BLE APIs, we like to go with Kotlin as the main language, and the lowest minimum API level we support is 21 (Android 5.0 Lollipop).
A minimum API level of 29 (Android 10) will do just fine too.
Ensure “Use androidx.* artifacts” is checked in the project wizard, or you'll need to migrate to AndroidX.
Make sure your compileSdkVersion and targetSdkVersion are up-to-date, with a value of 34 (Android 14).
Related reading: Android Studio Sdk Manager
Setting Up Filters

Passing a null value as a filter will result in receiving all devices that are advertising around you, but this might not be what you want if you're looking for devices with a specific name or services.
You can set up filters to scan for devices with a specific service UUID, which is useful if you're looking for devices from a particular category, such as blood pressure monitors that use the standard 'Blood Pressure Service' with UUID 1810.
Filtering on service UUIDs can help narrow down scan results, but keep in mind that it's not guaranteed that the device actually has the service, even if it advertises it.
You can also scan for devices by their name, but this can be tricky if the device name is generic, like "Polar H7 391BB014". In this case, you'll need to do a substring comparison on the device name yourself.
If you're looking for devices by their MAC address, this is a bit special, as you usually don't know the MAC address unless you've scanned for it before. However, this can be useful if you're trying to reconnect to known devices.
Suggestion: Android Auto Not Working after Update

Here are some common filter criteria you can use:
- Advertised service UUIDs
- Service data for the advertised services
- Name of the advertising BLE device
- MAC address of the advertising BLE device
- Additional manufacturer-specific data
You can create a ScanFilter using the ScanFilter.Builder class and set the filtering criteria before calling build(). This can help you narrow down scan results and ensure that your app only connects to the devices you're interested in.
SDK
When working with Android, it's essential to understand the SDK that underlies your project.
The Android SDK provides a robust set of tools and APIs for building apps, including Bluetooth Low Energy (BLE) functionality.
To start, your app should target a minimum of API 21, which corresponds to Android 5.0, due to the availability of better BLE APIs.
The main classes from the Android SDK used for BLE development include those from the BLE Development Tips article, which we'll be referencing throughout this section.
These classes include BluetoothLeScanner and ScanFilter, which are crucial for efficient BLE scanning and filtering.
In the Android SDK, BLE development is a complex but rewarding process, and understanding the right classes and APIs is key to success.
Readers also liked: Dropbox Android Sdk
Defining Your Settings

Defining your ScanSettings is a crucial step in setting up your project. You can tweak yours accordingly based on what you discussed in the Specifying Scan Settings section.
There are several settings you can adjust, including the desired BLE scan mode. You can choose from low-powered high-latency scans to high-powered low-latency scans. A simple example of a low-latency ScanSetting setup is shown in the Implementing BLE scanning section.
You can also specify the threshold at which an advertisement packet sighting should be surfaced as a scan result. This is useful if you want to be more aggressive in finding devices.
Here's a summary of the different scan settings:
To set up scan filters, you can use the ScanSettings class. If you don't set up filters, you will receive all devices that are advertising around you. This might be what you want, but often you are looking for devices with a specific name or devices that advertise specific services.

You can filter on service UUIDs, device name, or mac address. Filtering on service UUIDs is useful if you are looking for devices from a 'category' of devices. For example, you can scan for devices with a specific service UUID like the blood pressure service with UUID 1810.
You can also scan for devices by exact name or mac address. Scanning by device name has 2 main use cases: to look for 1 specific device or to look for 1 specific device model. Scanning by mac address is mainly used to reconnect to known devices.
Related reading: Can You Name a Group Text on Android
Permissions Management
Managing permissions is a crucial step when developing an Android Bluetooth LE scanner. You need to declare the required permissions in the AndroidManifest.xml file.
The minimum required permissions for Bluetooth LE scanning are coarse and fine location access. Yes, you read that right – location access is required to use BLE.
To manage permissions efficiently, create a separate package named permissions, and inside it, create two Kotlin objects: PermissionsUtilities and BleScanRequiredPermissions.
On a similar theme: What Is a Bluetooth Le Device
The BleScanRequiredPermissions object should contain an array of the permissions your app requires. You can also check out a permission management library if you prefer.
Here are the permissions you need to declare in the AndroidManifest.xml file:
- BLUETOOTH: Legacy permission for connecting to Bluetooth devices.
- BLUETOOTH_ADMIN: Legacy permission for scanning and bonding with Bluetooth devices.
- ACCESS_FINE_LOCATION: Required for BLE scan results between Android 6 and Android 11.
- ACCESS_COARSE_LOCATION: Required for BLE scan results on Android 12 and above.
- BLUETOOTH_SCAN: Required for Bluetooth scans on Android 12 and above.
- BLUETOOTH_CONNECT: Required for connecting to Bluetooth peripherals on Android 12 and above.
Remember to check if the user has granted all the required permissions before proceeding with BLE scanning. You can use the normal way to check permissions and prompt the user to grant them if necessary.
Also, don't forget to check if Bluetooth is turned on. If it's not, use an intent to ask the user to turn it on.
Readers also liked: Check Timing
Android Basics
To get started with developing an Android Bluetooth LE scanner, you'll need to understand some key concepts.
BLE development on Android involves keywords like "BLE Basics for Android Developers" which is a good place to start.
You'll also want to familiarize yourself with the Android SDK and the necessary permissions to use Bluetooth LE on your device.
The Android SDK provides tools and APIs to help you build and test your BLE scanner, making it easier to get started.
With these basics under your belt, you'll be well on your way to creating a functional Android Bluetooth LE scanner.
Introduction
The Android platform commands over 70% of the market share worldwide, making it a popular choice for app development. Android apps are in high demand, and with the right tools and knowledge, you can create a successful app.
BLE (Bluetooth Low Energy) is a technology that allows for low-power connectivity between devices, and more and more people are looking to use it in their Android apps. Unfortunately, the Android SDK's BLE API has some undocumented pitfalls.
The Punch Through team has extensive experience working with BLE-connected Android apps, with over 15 years of expertise in custom software development for connected products and mobile-mediated device-to-cloud connectivity.
Additional reading: Remove Ads from Youtube App Android
Basics for Developers
As an Android developer, it's essential to understand the basics of Bluetooth Low Energy (BLE) development. BLE Basics for Android Developers involve getting familiar with keywords and concepts that will help you navigate the Android BLE API.
The Android BLE API provides several classes and methods that you'll need to work with. These include BluetoothAdapter, BluetoothLeScanner, ScanFilter, ScanResult, BluetoothDevice, BluetoothGatt, and BluetoothGattCallback.
To start a BLE scan, you'll need to use the BluetoothLeScanner class, which is provided by the BluetoothAdapter class. You'll also need to request the necessary permissions, such as ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION, depending on the Android version you're targeting.
Here's a brief summary of the BLE classes and methods you'll need to know:
Remember, BLE development on Android can be complex, so it's essential to understand the basics and follow best practices to ensure reliable connections.
Third-Party Libraries
Third-Party Libraries can make Android development a whole lot easier, especially when it comes to BLE (Bluetooth Low Energy) development. If you're new to BLE, you'll likely come across some keywords like "RxJava" and "Kotlin coroutines" - don't worry, they're not as scary as they sound.
If you're looking for reliable open-source third-party BLE libraries, there are several great options out there. Here are a few popular ones:
Each of these libraries has its own strengths and weaknesses, so be sure to do your research and choose the one that best fits your needs.
Mode
Understanding Android's ScanMode is crucial for efficient Bluetooth usage. There are four modes to choose from, each with its own power consumption and scanning time.
SCAN_MODE_LOW_POWER is the most power-efficient option, scanning for 0.5 seconds and pausing for 4.5 seconds. This mode may take longer to find devices, but it's ideal for long scanning times.
The SCAN_MODE_BALANCED mode scans for 2 seconds and waits 3 seconds, offering a compromise between power consumption and scanning time. However, its usefulness is still unclear.
For guaranteed scanning results, use SCAN_MODE_LOW_LATENCY, which scans continuously. This mode uses the most power, but it's perfect for quick scans.
SCAN_MODE_OPPORTUNISTIC is the least desirable option, only providing scan results when other apps are scanning. This mode is unpredictable and may not find devices at all.
Here's a quick summary of the ScanModes:
By choosing the right ScanMode, you can balance power consumption and scanning time to suit your needs.
Bluetooth LE Fundamentals
Bluetooth LE is a low-energy variant of the Bluetooth standard, designed to minimize power consumption while maintaining a reliable connection. This is achieved through the use of a 2 Mbps data rate and a 1 Mbps data rate for advertising packets.
Bluetooth LE devices can operate for up to a year on a single coin cell battery, making them suitable for applications such as fitness trackers and smart home devices.
Bluetooth vs. Classic
BLE is optimized for power efficiency, allowing devices to run on small batteries for weeks, months, or even years.
Bluetooth Classic, on the other hand, is designed for continuous data transmission, making it less suitable for low-power devices.
BLE is far more developer-friendly than Bluetooth Classic, allowing developers to specify custom profiles for various use cases.
The Android Bluetooth API is also more challenging to work with for Bluetooth Classic use cases due to its multicast nature, complexity, and limited profile support.
Bluetooth Classic requires pairing with Android before establishing an RFCOMM connection, whereas BLE does not have this restriction.
Here are some key differences between BLE and Bluetooth Classic:
The Android SDK also requires developers to manage a dedicated Android Thread object to communicate with a Bluetooth Classic device, which can be error-prone.
BLE Central-Peripheral Relationship
The BLE Central-Peripheral Relationship is a fundamental concept in Bluetooth Low Energy (BLE) communication. Your Android device can act as a Central and connect to multiple peripherals simultaneously, but each peripheral can only interact with one Central at a time.
In a typical scenario, when a BLE device is connected to a Central, it stops advertising as a Peripheral. This is because it can no longer be connected to it. The relationship between a BLE Central and Peripheral is also similar to a client-server relationship, where the server (Peripheral) hosts a GATT database that provides information the client (Central) accesses via BLE.
The Central-Peripheral relationship is crucial to understand, especially when working with BLE devices. It's essential to note that your Android device can also behave as a Peripheral, but for now, let's focus on the most common scenario of it acting as a BLE Central.
Here are the three common BLE operations:
- Write: The client (app) writes some bytes to a characteristic or descriptor on the server (BLE device).
- Read: The client (app) reads the value of a characteristic or descriptor on the server (BLE device).
- Notify/Indicate: The client (app) subscribes to a characteristic for Notifications or Indications and is notified by the server when the value of the characteristic changes.
Device Connection
To initiate a BLE connection in your Android app, you have two main options: Automatic Connection and Manual Connection. Automatic Connection is where your app connects to a device based on specific heuristics, such as scanning for devices advertising certain private service UUIDs.
Manual Connection, on the other hand, requires the user to manually select a device to connect to from the list of scan results. This is the approach our example assumes, but regardless of which method you choose, it's essential to stop your BLE scan before connecting to a device. This saves power and increases the reliability of the connection process.
To connect to a BLE device, you first need to scan for it using the BluetoothLeScanner object obtained from the BluetoothAdapter. You'll need to provide filters, scan settings, and a scan callback object to receive found devices. The scanner will then start looking for devices that match your filters and call your scan callback when it finds one.
A unique perspective: Do I Need Onedrive on My Android Phone
Connect to device
Connecting to a BLE device is a crucial step in any Bluetooth Low Energy (BLE) app. You can initiate a connection in two ways: Automatic Connection or Manual Connection.
Automatic Connection happens when your app connects to a device autonomously based on specific heuristics, such as scanning for devices advertising certain private service UUIDs. This approach can save power and increase connection reliability.
Manual Connection requires the user to select a device from a list of scan results. This is the approach our example assumes.
Regardless of the type of connection, it's essential to stop the BLE scan before connecting to a device. This simple step saves power and improves connection reliability.
Here are the two types of BLE connections:
By stopping the BLE scan before connecting, you'll make the connection process more reliable and efficient. This is a best practice that can save you and your users a lot of frustration.
Enqueuing and Executing Operations
To implement a queuing mechanism for BLE operations, you'll need a synchronized function that adds a new operation to the queue and kicks off the added operation if there is no pending operation.
A good approach is to use a ConnectionManager type class that handles all the app's BLE needs, and a queue data structure to hold operations that need to be performed.
Each operation should be represented as a subclass of a parent-sealed class, such as BleOperationType, which has subclasses for Connect, Disconnect, CharacteristicWrite, and other BLE operations.
To execute an operation, you'll need to pop it off the head of the queue, cache it as the pendingOperation property, and then execute the operation depending on its type.

Here are the properties each BleOperationType subclass needs to execute successfully:
- Connect: BluetoothDevice handle and a Context object
- CharacteristicWrite: BluetoothDevice handle, BluetoothGattCharacteristic, write type, and ByteArray representing the write payload
- DescriptorWrite: BluetoothDevice handle, BluetoothGattDescriptor, write type, and ByteArray representing the write payload
- DescriptorRead: BluetoothDevice handle, BluetoothGattDescriptor
- MtuRequest: BluetoothDevice handle
Each subclass should encapsulate what the operation needs to get executed successfully.
Service Discovery
Service discovery is essential after establishing a BLE connection with a device. It allows us to explore what the device is capable of.
Calling discoverServices() on the BluetoothGatt object is straightforward. Using the BluetoothGatt object we saved from a successful connection attempt, we simply call discoverServices() on it.
Performing service discovery from the main/UI thread is highly recommended to prevent a rare threading issue from causing a deadlock situation. This issue happens very rarely and may have been fixed in recent Android versions, but it's worth it for the peace of mind.
The outcome of service discovery will be delivered via BluetoothGattCallback's onServicesDiscovered() method, which we should override in our BluetoothGattCallback callback body. After the onServicesDiscovered() callback has been delivered, we can safely go through the available services and characteristics using BluetoothGatt's getServices() method.
Discovering Services

Service discovery is essential after establishing a BLE connection with a device. It allows us to explore what the device is capable of.
To perform service discovery, we simply call discoverServices() on the BluetoothGatt object we saved from a successful connection attempt. This method is straightforward and allows us to discover the services and characteristics available on a BLE device.
Calling discoverServices() from the main/UI thread is recommended to prevent a rare threading issue from causing a deadlock situation. This issue happens very rarely, but it's still worth taking the precautionary measure.
The outcome of service discovery will be delivered via BluetoothGattCallback's onServicesDiscovered() method, which we should override in our BluetoothGattCallback callback body to ensure we're notified of the event.
Results Filtering
Service discovery is like exploring a mall for the first time - you need to know what's available on each floor, or in this case, what services and characteristics a BLE device has to offer.

To narrow down scan results, you can use the ScanFilter class, which allows you to filter incoming ScanResults based on various criteria, including advertised service UUIDs, service data, device name, MAC address, and manufacturer-specific data.
Creating a ScanFilter is as simple as using the ScanFilter.Builder class and calling its methods to set the filtering criteria before finally calling build(). This is useful if you're developing an app that only connects to a specific type of device, like an environmental sensing device.
If you don't set up filters, you'll receive all devices that are advertising around you, which might not be what you want.
Here are some examples of how to use ScanFilter to filter scan results:
Remember, filtering on service UUIDs is useful for finding devices from a specific category, but it's not a guarantee that the device actually has that service.
You can also use the ScanFilter to look for devices by exact name, but be aware that this can only be used to find specific devices, not all devices of a certain model.
In the next section, we'll explore how to use scan filters to reconnect to known devices.
You might like: Not Receiving Group Text Messages Android
Parse Gatt Characteristic Properties
To parse Gatt characteristic properties, you need to use the getProperties() method, which returns a bitmask of properties represented by BluetoothGattCharacteristic.PROPERTY_* constants.
BluetoothGattCharacteristic properties are determined by a bitmask, allowing you to perform bitwise operations to check for specific properties.
You'll want to check for PROPERTY_READ, PROPERTY_WRITE, and PROPERTY_WRITE_NO_RESPONSE properties, as these are the ones you'll be concerned with for now.
To determine if a characteristic is readable, writable, or both, you'll use extension functions that perform a bitwise AND between getProperties() and a given PROPERTY_* constant.
A characteristic that is both readable and writable will have both PROPERTY_READ and PROPERTY_WRITE properties set.
A characteristic that is writable but not readable will have PROPERTY_WRITE set but not PROPERTY_READ.
Notifications and Data Transfer
To send notifications or indications from a BLE device, you need to ensure the characteristic supports it by checking its PROPERTY_INDICATE and PROPERTY_NOTIFY properties.
The Android Bluetooth stack needs to be informed that your app wants to receive notifications by calling setCharacteristicNotification() on the BluetoothGatt object, and it should return true.
To enable or disable notifications or indications, you need to write to the Client Characteristic Configuration Descriptor (CCCD) with the ENABLE_INDICATION_VALUE or ENABLE_NOTIFICATION_VALUE, or DISABLE_NOTIFICATION_VALUE, respectively.
Verifying Notification Support

You need to ensure a characteristic supports sending notifications or indications before you can subscribe to its value changes. This is done by checking the characteristic's properties against BluetoothGattCharacteristic's PROPERTY_INDICATE and PROPERTY_NOTIFY.
The Android Bluetooth stack needs to be informed that your app intends to opt in or opt out from notifications of a characteristic's value changes. You do this by calling setCharacteristicNotification() on your BluetoothGatt object and making sure it returns true.
To enable or disable notifications or indications on a BLE device, you need to write to the Client Characteristic Configuration Descriptor (CCCD). The CCCD's value should be set to either ENABLE_INDICATION_VALUE or ENABLE_NOTIFICATION_VALUE to enable notifications or indications, or DISABLE_NOTIFICATION_VALUE to disable them.
Writing to the CCCD is necessary to inform the BLE device about your app's notification preferences.
If this caught your attention, see: Enable Bluetooth
Show Results to User
To show results to the user, you'll want to display BLE devices in your vicinity on the UI using a RecyclerView. This Android component allows you to display a collection of items in a scrollable interface.

You'll need to implement your RecyclerView.Adapter class and layout XML for each scan result. You can find an example implementation in the open-source GitHub Repo.
To keep the UI updated with the latest RSSI readings, you'll want to check if your scanResultList already has a scan result whose MAC address is identical to the new incoming scan result. If so, you'll replace the older entry with the newer one.
This involves modifying your scanCallback property's onScanResult callback and implementing the onScanFailed method so any errors will get logged to Logcat. You'll also want to clear the list of its contents before starting each BLE scan.
You should see your RecyclerView being populated by scan results representing BLE devices in your vicinity. They should update themselves every time a new scan result comes in.
Notable
Notable issues can arise while performing BLE scans, and it's essential to be aware of them. The most common error is the "App is scanning too frequently" error, which doesn't trigger an error callback, but instead, an obscure entry in Logcat.

This error occurs when your app exceeds the internal limit of five startScan(…) method calls every 30 seconds per app on a BluetoothLeScanner object. You'll only see this Logcat entry if you don't have any filtering active in your Logcat window.
To resolve this issue, call stopScan() followed by startScan(...) again after 30 seconds have elapsed. This will allow your app to start receiving scan results again.
Device Bonding and Operations
Device bonding is a crucial step in establishing a secure connection between your Android app and a BLE device. It's not the same as pairing, which is the exchange of temporary encryption keys that allows for the bonding process to take place. Think of pairing as setting up a temporary, encrypted channel between devices.
To bond with a BLE device, you can use Android-initiated bonding, which is the most reliable method for most Android devices. This involves triggering the bonding process by including an encrypted characteristic that the app reads as part of the connection process.
You can also check a device's bond state on demand using the BluetoothDevice's getBondState() method, which returns the current bond state as one of three possible constants: BOND_NONE, BOND_BONDING, or BOND_BONDED.
Device Bonding

Bonding is a crucial step in establishing a secure connection between your app and a BLE device. It's often confused with pairing, but they're not the same thing.
Pairing is the exchange of temporary encryption keys that allows for the exchange of long-term encryption keys, which is then followed by the bonding process. Think of it like exchanging a secret handshake with a friend in a public venue, but only inside a tent.
Android developers only care about bonding with a BLE device, as the Bluetooth stack takes care of the pairing process for us. In fact, the only thing we need to focus on is bonding with a BLE device.
Android can initiate bonding on its own without any action required by developers, usually when an Insufficient Authentication error code is received. This is the most reliable method for most Android devices and is even recommended by Apple in their Accessory Design Guidelines document.

Peripheral-initiated bonding is rare and not recommended, but it can be used as a last resort if the other methods fail. However, some OEMs' Android devices might reject this request to bond.
To check a device's bond state on demand, you can use the BluetoothDevice's getBondState() method, which returns the current bond state as BOND_NONE, BOND_BONDING, or BOND_BONDED.
Abstraction for Operations
Creating an abstraction for BLE operations is crucial for a robust and maintainable device bonding system. This abstraction should be represented as a sealed class with subclasses for each type of BLE operation.
A good example of this is the BleOperationType sealed class, which has subclasses for Connect, Disconnect, CharacteristicWrite, CharacteristicRead, DescriptorWrite, DescriptorRead, and MtuRequest. Each subclass encapsulates the necessary properties for the operation to be executed successfully.
The BleOperationType class also contains an abstract property for the BluetoothDevice handle, which is overridden by its subclasses. This provides a clear and consistent way to handle BluetoothDevice objects across different operations.

Here's a breakdown of the properties needed for each operation:
- Connect: BluetoothDevice handle and Context object
- Disconnect: BluetoothDevice handle
- CharacteristicWrite: BluetoothDevice handle, BluetoothGattCharacteristic, write type, and ByteArray
- CharacteristicRead: BluetoothDevice handle and BluetoothGattCharacteristic
- DescriptorWrite: BluetoothDevice handle, BluetoothGattCharacteristic, and ByteArray
- DescriptorRead: BluetoothDevice handle and BluetoothGattCharacteristic
- MtuRequest: BluetoothDevice handle
By using this abstraction, you can easily add or remove operations without affecting the rest of the system, making it a scalable and maintainable solution.
Reliable App Connections
To ensure a reliable BLE connection, it's essential to stop your BLE scan before connecting to a device. This simple step saves power and increases the reliability of the connection process.
Automatic and manual connections are the two main types of BLE connections in apps. However, for a manual connection, the user must peruse the list of scan results and manually select a device to connect to.
To avoid any issues, your BLE logic should live outside of your Activity stack and user-facing elements. This means using a singleton called ConnectionManager to handle all the app's BLE needs, rather than relying on Activities and Fragments to manage the connection.
Reliable App Connections
To initiate a reliable BLE connection, it's essential to stop your BLE scan before connecting to a BLE device. This simple step saves power and increases the connection process reliability.

There are two types of BLE connection flows: Automatic Connection and Manual Connection. Our example assumes a use case of manual connection, where the user manually selects a device to connect to from the list of scan results.
Manual connections require the user to peruse the list of scan results and make a conscious decision, which can be a more reliable option than automatic connections.
Automatic connections, on the other hand, rely on specific heuristics, such as scanning for devices advertising certain private service UUIDs. However, this approach can lead to issues if there are multiple devices advertising the same UUID.
To ensure reliable BLE connections, it's crucial to keep your BLE logic separate from your user-facing elements. This means that your Activities and Fragments shouldn't make any assumptions about the state of the BLE connection.
Instead, they should rely on a central entity, such as a singleton called ConnectionManager, which handles all the app's BLE needs. This approach helps prevent issues when the user swipes away your app while your foreground service is running.
Here are some best practices to keep in mind:
- Stop your BLE scan before connecting to a BLE device.
- Use a central entity, such as a singleton called ConnectionManager, to handle all your app's BLE needs.
- Keep your BLE logic separate from your user-facing elements.
Reliable Libraries

If you're looking for a reliable way to connect to BLE devices in your Android app, you have several options to choose from.
The Android SDK provides a solid foundation for BLE development, but sometimes it's helpful to have a third-party library to simplify the process.
One such library is RxAndroidBle, which is based on RxJava and has a big, active community. It's a great fit if your project follows the Rx paradigm.
Another option is the Nordic Android BLE Library, which is a great abstraction of the complexities of the official Android BLE SDK. It's used by many developers and has a responsive community.
If you're comfortable with Kotlin coroutines, you might want to consider BleGattCoroutines.
If you're a beginner, SweetBlue might be a good starting point, despite not being free or open-source anymore. It's based on conventional Java-style callback interfaces, making it easy to work with.
Here are some reliable open-source third-party BLE libraries to consider:
Always in the Background

Android has made it increasingly difficult for apps to scan continuously in the background, as this is a power-consuming operation. You should not scan continuously because it is a very power-consuming operation. Your users value their battery life a lot!
As of Android 8.1, scans without any filters are blocked when the screen is off. This is another attempt at power saving from Google. If you're not using any ScanFilters, Android will pause your scan when the screen is off and resume it when the screen is on again.
Android 7 introduces further limitations, including the ability to only scan for 30 minutes continuously. After that, Android changes your ScanSettings to SCAN_MODE_OPPORTUNISTIC. To work around this, you can scan for periods < 30 minutes, then stop the scan and start it again.
Starting and stopping scans more than 5 times in a window of 30 seconds will temporarily disable scanning, as of Android 7. This is another measure to conserve power.
Discover more: Youtube Play with Screen off Android

Here are some key points to keep in mind:
These limitations are in place to conserve power and ensure a better user experience.
Limitations and Alternatives
Using a foreground service isn't a foolproof solution, especially on Android versions 9 and above, where the Adaptive Battery feature can sometimes limit the uptime of app processes with running foreground services. This can happen randomly, so it's essential to inform your users about this limitation.
To work around this, you can request that your users turn off battery optimization for your app, which is an option buried deep inside the Settings app. A helpful resource is https://dontkillmyapp.com/, which provides well-written instructions that you can share with your users.
Other Android background processing techniques, like relying on AlarmManager and WorkManager, are viable alternatives. However, these methods won't provide instantaneous connection events, and you may miss BLE notifications or indications if your app isn't running when those events occur.
Here are some key differences between these alternatives:
BLE on Android is doable with care and attention to detail, but it's not always easy. To make it more manageable, consider using a well-tested library or framework that provides a higher abstraction level.
Starting and Stopping
To start a BLE scan, you can use the StartScan(ScanCallback) method, which begins a scan with default parameters and no filters, using a callback to deliver scan results.
The BluetoothLeScanner has a stopScan() method that lets you stop an ongoing scan. It's a simple way to pause the scanning process.
You can also keep track of the scanner's state by adding a boolean property, like isScanning, which gets updated when the scan is started or stopped.
To update the scan button's behavior, you can override the setter for the isScanning property, so that it updates the button text to reflect the current scan status.
When you start a scan, set the isScanning property to true, and when you stop a scan, set it to false. This way, you can easily determine whether a scan is ongoing or not.
This approach helps you manage the scan process and respond accordingly, whether it's starting or stopping the scan.
Broaden your view: How Do You Stop Group Text on Android
Results and Callbacks
A ScanResult object gets surfaced as part of ScanCallback’s onScanResult(...) method, and generally the things we care about in a ScanResult are the MAC address of the device, its name, RSSI or signal strength, and the BluetoothDevice handle.
There are three possible callback types to control how many times Android will tell you about a device that matches the filters: CALLBACK_TYPE_ALL_MATCHES, CALLBACK_TYPE_FIRST_MATCH, and CALLBACK_TYPE_MATCH_LOST.
CALLBACK_TYPE_ALL_MATCHES will get you a callback every time an advertisement packet that matches is received, while CALLBACK_TYPE_FIRST_MATCH will only get you a callback once for a device. CALLBACK_TYPE_MATCH_LOST gets you a callback when no more advertisement packets are found after a first packet was found.
You can control how many times Android will tell you about a device that matches the filters by specifying the callback type in your ScanSettings. If you don’t know what to choose, take CALLBACK_TYPE_ALL_MATCHES since that will give you more control when receiving callbacks.
The callback type determines how many times you'll get callbacks for a device that matches the filters. Here are the three possible callback types with a brief description of each:
To keep the UI updated with the latest RSSI readings, you can check if your scanResultList already has a scan result whose MAC address is identical to the new incoming scan result, and replace the older entry with the newer one.
Featured Images: pexels.com

