<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ ble - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ ble - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 06 May 2026 16:59:59 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/ble/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How AOSP 16 Bluetooth Scanner Works: The Ultimate Guide ]]>
                </title>
                <description>
                    <![CDATA[ Ah, Bluetooth. The technology we all love to hate. It's like that one friend who's always just about to connect, but then... doesn't. For years, Android developers have been locked in a dramatic, often tragic, romance with Bluetooth. We've wrestled w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-aosp-16-bluetooth-scanner-works-the-ultimate-guide/</link>
                <guid isPermaLink="false">6983ae630a7fef9ac2d90313</guid>
                
                    <category>
                        <![CDATA[ ble ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Bluetooth Low Energy ]]>
                    </category>
                
                    <category>
                        <![CDATA[ bluetooth ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Android ]]>
                    </category>
                
                    <category>
                        <![CDATA[ android app development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ scanner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nikheel Vishwas Savant ]]>
                </dc:creator>
                <pubDate>Wed, 04 Feb 2026 20:38:59 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1770234863523/44a1690e-ab8a-4f6b-a12b-2c2636947d8c.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Ah, Bluetooth. The technology we all love to hate. It's like that one friend who's always just about to connect, but then... doesn't.</p>
<p>For years, Android developers have been locked in a dramatic, often tragic, romance with Bluetooth. We've wrestled with its quirks, begged it to just work, and shed silent tears over its mysterious connection drops.</p>
<p>But what if I told you that things are about to get better? What if I told you that with Android 16, the Bluetooth gods have finally smiled upon us? It's not a dream, my friends. It's the AOSP 16 Bluetooth Scanner, and it's here to bring a new hope to our weary developer souls.</p>
<p>In this handbook, we're going on a journey. A journey into the heart of AOSP 16's new Bluetooth features. We'll laugh, we'll cry (hopefully from joy this time), and we'll learn how to wield these new powers for good. We'll explore the magic of passive scanning, the drama of bond loss reasons, and the sheer convenience of getting service UUIDs without all the usual fuss.</p>
<p>By the end of this epic saga, you'll be able to:</p>
<ul>
<li><p>Build a Bluetooth scanner that's so efficient, it's practically psychic.</p>
</li>
<li><p>Debug connection issues like a seasoned detective.</p>
</li>
<li><p>Impress your friends and colleagues with your newfound Bluetooth mastery.</p>
</li>
</ul>
<h3 id="heading-prerequisites"><strong>Prerequisites:</strong></h3>
<p>Before we dive in, it's a good idea to have a basic understanding of Android development and Kotlin. If you've ever tried to make two devices talk to each other and ended up wanting to throw your computer out the window, you're more than qualified.</p>
<p>So grab your favorite beverage, put on your coding cape, and let's get ready for the Bluetooth awakening!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-a-brief-history-of-bluetooth-in-android">A Brief History of Bluetooth in Android</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-whats-new-in-aosp-16-the-three-musketeers">What's New in AOSP 16: The Three Musketeers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-deep-dive-1-passive-scanning">Deep Dive #1: Passive Scanning</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-the-bluetoothlescanner">Understanding the BluetoothLeScanner</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-hands-on-building-your-first-passive-scanner">Hands-On: Building Your First Passive Scanner</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-deep-dive-2-bluetooth-bond-loss-reasons">Deep Dive #2: Bluetooth Bond Loss Reasons</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-deep-dive-3-service-uuids-from-advertisements">Deep Dive #3: Service UUIDs from Advertisements</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-advanced-topics-leveling-up-your-scanning-game">Advanced Topics: Leveling Up Your Scanning Game</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-real-world-use-cases-where-the-bluetooth-hits-the-road">Real-World Use Cases: Where the Bluetooth Hits the Road</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-api-version-checking-how-to-not-crash-your-app">API Version Checking: How to Not Crash Your App</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-testing-and-debugging-the-fun-part-said-no-one-ever">Testing and Debugging: The Fun Part (Said No One Ever)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-performance-and-best-practices-how-to-be-a-good-bluetooth-citizen">Performance and Best Practices: How to Be a Good Bluetooth Citizen</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion-the-future-is-passive-and-thats-okay">Conclusion: The Future is Passive (and That's Okay)</a></p>
</li>
</ol>
<h2 id="heading-a-brief-history-of-bluetooth-or-how-we-learned-to-stop-worrying-and-love-the-radio-waves">A Brief History of Bluetooth (Or: How We Learned to Stop Worrying and Love the Radio Waves)</h2>
<h3 id="heading-the-dark-ages-classic-bluetooth">The Dark Ages: Classic Bluetooth</h3>
<p>In the beginning, there was Classic Bluetooth. It was the digital equivalent of a loud, boisterous party guest. It could carry a lot of data (like your favorite tunes to a speaker), but it sure was a battery hog. It was great for streaming audio, but for small, infrequent data transfers? It was like using a fire hose to water a houseplant. Overkill, and frankly, a little messy.</p>
<p>Developers in this era spent their days wrestling with BluetoothAdapter, BluetoothDevice, and the dreaded BluetoothSocket. It was a time of great uncertainty, where a simple connection could take seconds, or... well, let's just say you could go make a cup of coffee. And the battery drain? Your users would watch their phone's power level plummet faster than a lead balloon.</p>
<h3 id="heading-the-renaissance-enter-bluetooth-low-energy-ble">The Renaissance: Enter Bluetooth Low Energy (BLE)</h3>
<p>Then, with Android 4.3, a new hero emerged: Bluetooth Low Energy, or BLE. This wasn't your dad’s Bluetooth. BLE was sleek, efficient, and mysterious. It was designed for short bursts of data, sipping power like a fine wine instead of chugging it.</p>
<p>BLE was the cool kid on the block. It introduced us to a whole new world of possibilities: heart-rate monitors, smart watches, and a million and one IoT devices that could run for months on a single coin-cell battery. It was a game-changer.</p>
<p>But with great power came... great complexity. We had to learn a whole new language of GATT, GAP, services, and characteristics. It was like going from writing simple scripts to composing a full-blown opera. The potential was huge, but the learning curve was steep.</p>
<h3 id="heading-the-problem-child-scanning">The Problem Child: Scanning</h3>
<p>And then there was scanning. The act of finding these new, power-sipping devices. In the early days of BLE, scanning was still a bit of a wild west. It was an active, noisy process. Your phone would shout into the void, "IS ANYONE OUT THERE?", and then listen for replies. This worked, but it was still a significant power drain, especially if your app needed to scan for long periods.</p>
<p>It was the classic developer dilemma: you need to find devices, but you don't want to be the reason your user's phone is dead by lunchtime. For years, we walked this tightrope, balancing the need for discovery with the desperate plea for battery life.</p>
<p>This is the world that AOSP 16 was born into. A world crying out for a better way to scan. A world ready for a hero. And that hero, my friends, is passive scanning. But more on that in a bit...</p>
<h2 id="heading-whats-new-in-aosp-16-spoiler-its-actually-cool">What's New in AOSP 16? (Spoiler: It's Actually Cool)</h2>
<p>Alright, let's get to the good stuff. What shiny new toys did the Android team give us in AOSP 16? It turns out, quite a few! But before we unwrap the presents, let's talk about the new delivery schedule, because even that is a little different now.</p>
<h3 id="heading-a-tale-of-two-releases">A Tale of Two Releases</h3>
<p>In a shocking plot twist, Android decided to grace us with two major API releases in 2025. First, we got the main event, Android 16 (codenamed "Baklava," because who doesn't love a good pastry?), which landed in Q2. This is your traditional, big-bang release with all the behavior changes you've come to know and love (or fear).</p>
<p>But then, in Q4, we get a surprise second act: a minor release, which is where our new Bluetooth goodies made their grand entrance. This release is all about new features and APIs, without the scary, app-breaking changes. It's like getting a free dessert after you've already paid the bill.</p>
<h3 id="heading-the-three-musketeers-of-bluetooth">The Three Musketeers of Bluetooth</h3>
<p>So, what did this Q4 release bring to the Bluetooth party? I'm glad you asked. It brought three new heroes, ready to save us from our Bluetooth woes. I call them... The Three Musketeers.</p>
<table><tbody><tr><td><p><strong>Feature</strong></p></td><td><p><strong>The Gist</strong></p></td><td><p><strong>Why You Should Care</strong></p></td></tr><tr><td><p><strong>Passive Scanning</strong></p></td><td><p>The ability to listen for Bluetooth devices without shouting at them.</p></td><td><p>Your app can now be a silent, battery-saving ninja.</p></td></tr><tr><td><p><strong>Bond Loss Reasons</strong></p></td><td><p>Finally, some closure on why your Bluetooth connections break up.</p></td><td><p>You can stop playing the guessing game and actually debug connection issues.</p></td></tr><tr><td><p><strong>Service UUID from Ads</strong></p></td><td><p>Grab a device's vital stats directly from its advertisement.</p></td><td><p>It's like speed dating for Bluetooth devices. Faster, more efficient connections.</p></td></tr></tbody></table>

<p>These aren't just minor tweaks, folks. These are quality-of-life improvements that will fundamentally change how we build and debug Bluetooth-enabled apps. It's as if the Android team actually listened to our collective cries for help. (I know, I'm shocked too.)</p>
<p>In the next few sections, we're going to get up close and personal with each of these new features. We'll dive into the code, explore the use cases, and learn how to harness their power. So, get ready to meet our first musketeer: the strong, silent type known as Passive Scanning.</p>
<h2 id="heading-deep-dive-1-passive-scanning">Deep Dive #1: Passive Scanning</h2>
<p>Imagine you're in a library. You're looking for a friend, but you don't know where they are. You have two options:</p>
<ul>
<li><p><strong>Active Scanning:</strong> You stand in the middle of the library and shout, "HEY, STEVE! ARE YOU HERE?" This is effective, but it's also loud, disruptive, and will get you kicked out by the librarian (who, in this analogy, is your user's battery).</p>
</li>
<li><p><strong>Passive Scanning:</strong> You quietly walk around the library, listening for your friend's distinctive, wheezing laugh. You don't say a word. You just listen. This is stealthy, efficient, and won't drain your social (or actual) battery.</p>
</li>
</ul>
<p>For years, Android's Bluetooth scanning has been the guy shouting in the library. But with AOSP 16, we can finally be the quiet listener. This is the magic of passive scanning.</p>
<h3 id="heading-active-vs-passive-the-technical-showdown">Active vs. Passive: The Technical Showdown</h3>
<p>In the world of BLE, devices send out little packets of information called "advertisements." It's their way of saying, "Hey, I'm here, and this is what I do!"</p>
<ul>
<li><p><strong>Active Scanning:</strong> When your phone performs an active scan, it hears an advertisement and then sends back a SCAN_REQ (Scan Request). It's basically saying, "Tell me more!" The peripheral device then replies with a SCAN_RSP (Scan Response), which contains extra information.</p>
</li>
<li><p><strong>Passive Scanning:</strong> With passive scanning, your phone hears the advertisement... and that's it. It doesn't send anything back. It just takes note of the initial advertisement and moves on. It's a one-way conversation.</p>
</li>
</ul>
<h3 id="heading-why-go-passive-the-power-of-silence">Why Go Passive? The Power of Silence</h3>
<p>So, why is this such a big deal? Two words: power consumption. Every time your phone's radio has to transmit something (like a SCAN_REQ), it uses energy. If your app is scanning for devices all the time, those little transmissions add up, and your user's battery pays the price.</p>
<p>By switching to passive scanning, you're telling the radio to just listen. No talking, just listening. This dramatically reduces the power needed for scanning, making it a perfect solution for apps that need to monitor for nearby devices over long periods.</p>
<h3 id="heading-the-code-how-to-become-a-bluetooth-ninja">The Code: How to Become a Bluetooth Ninja</h3>
<p>So, how do we implement this newfound stealth mode? It's surprisingly simple. It all comes down to the ScanSettings you use when you start your scan.</p>
<p>Previously, you might have done something like this:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> settings = ScanSettings.Builder()
    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
    .build()
</code></pre>
<p>Now, with AOSP 16, we have a new option. To enable passive scanning, you simply set the scan type:</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// This is the magic line!</span>
.setScanMode(ScanSettings.SCAN_TYPE_PASSIVE)
</code></pre>
<p>Wait, that can't be right. The documentation says SCAN_TYPE_PASSIVE is a scan type, not a scan mode. And you're right! My apologies, I got a little too excited. The correct way to do this is by setting the scan mode to passive. Let's try that again.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> settings = ScanSettings.Builder()
    <span class="hljs-comment">// The actual magic line!</span>
    .setScanMode(ScanSettings.SCAN_MODE_OPPORTUNISTIC) <span class="hljs-comment">// This is the closest to passive</span>
    .build()
</code></pre>
<p>Hold on, that's not quite right either. It seems I've gotten my wires crossed. Let's consult the official scrolls... Ah, here it is! The ScanSettings.Builder has a new method in Android 16 QPR2. It's not setScanMode, it's a whole new setting.</p>
<p>Let's get this right once and for all. Here is the correct way to enable passive scanning:</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// Available in Android 16 QPR2 and later</span>
<span class="hljs-keyword">val</span> settings = ScanSettings.Builder()
    <span class="hljs-comment">// This is the REAL magic line, I promise!</span>
    .setScanType(ScanSettings.SCAN_TYPE_PASSIVE) 
    .build()
</code></pre>
<p>And there you have it. With that one line, you've transformed your app from a loud, battery-guzzling tourist to a silent, efficient Bluetooth ninja. Your users' batteries will thank you.</p>
<p>Of course, there's a trade-off. Since you're not sending a SCAN_REQ, you won't get the extra data from the SCAN_RSP. But for many use cases, the initial advertisement is all you need. And the power savings are more than worth it.</p>
<p>Now that we've mastered the art of silent scanning, let's move on to the next piece of the puzzle: understanding the BluetoothLeScanner itself.</p>
<h2 id="heading-understanding-bluetoothlescanner-the-star-of-our-show">Understanding BluetoothLeScanner (The Star of Our Show)</h2>
<p>Before we can truly master the art of Bluetooth scanning, we must first understand our primary weapon: the BluetoothLeScanner. Think of it as the PKE Meter from Ghostbusters. It's the tool we use to detect the invisible energy (in our case, BLE advertisements) floating all around us. But how does this ghost-hunting gadget actually work?</p>
<h3 id="heading-the-architecture-a-peek-behind-the-curtain">The Architecture: A Peek Behind the Curtain</h3>
<p>At a high level, the process is pretty straightforward. Your app, living comfortably in its own little world, decides it wants to find some BLE devices. It grabs an instance of the BluetoothLeScanner and says, "Hey, go look for stuff."</p>
<p>Under the hood, a lot is happening. The BluetoothLeScanner talks to the Android Bluetooth stack (codenamed "Fluoride," which sounds like something your dentist would be very proud of). The stack then communicates with the device's Bluetooth controller, the actual hardware that does the sending and receiving of radio waves. It's a classic case of "it's more complicated than it looks."</p>
<h3 id="heading-the-alphabet-soup-gatt-gap-and-friends">The Alphabet Soup: GATT, GAP, and Friends</h3>
<p>When you venture into the world of BLE, you'll quickly run into a whole bunch of acronyms. Don't panic! They're not as scary as they look. The two most important ones to understand are GAP and GATT.</p>
<ul>
<li><p><strong>GAP (Generic Access Profile):</strong> This is all about how devices discover and connect to each other. Think of GAP as the bouncer at a nightclub. It decides who gets to talk to whom. It manages advertising (the device shouting "I'm here!") and scanning (your app listening for those shouts). Our BluetoothLeScanner is a key player in the GAP-verse.</p>
</li>
<li><p><strong>GATT (Generic Attribute Profile):</strong> Once two devices are connected, GATT takes over. It defines how they exchange data. Think of GATT as the actual conversation happening inside the nightclub. It's all about Services, Characteristics, and Descriptors. A device might have a "Heart Rate Service," which contains a "Heart Rate Measurement Characteristic." Your app reads from or writes to these characteristics to get the data it needs.</p>
</li>
</ul>
<p>For the purpose of scanning, we're mostly living in the world of GAP. We're the ones standing outside the club, listening for interesting advertisements.</p>
<h3 id="heading-the-scanning-lifecycle-a-dramatic-play-in-three-acts">The Scanning Lifecycle: A Dramatic Play in Three Acts</h3>
<p>The life of a Bluetooth scan is a simple, yet elegant, drama.</p>
<ul>
<li><p><strong>Act I:</strong> The Preparation. Your app decides it's time to scan. It gets the BluetoothLeScanner, creates a set of ScanFilters (to only find specific devices) and ScanSettings (to define how to scan, like our new passive mode), and defines a ScanCallback.</p>
</li>
<li><p><strong>Act II:</strong> The Scan. Your app calls startScan(). The Bluetooth radio springs to life, listening for advertisements that match your filters. When it finds one, it reports back to your app via the onScanResult() method in your ScanCallback.</p>
</li>
<li><p><strong>Act III:</strong> The End. When your app has had enough (or, more importantly, when you've found what you're looking for), it calls stopScan(). The radio powers down, and all is quiet once more. It's crucial to always stop your scan when you're done. A rogue scan is the number one cause of "my battery dies in an hour" complaints from users.</p>
</li>
</ul>
<p>And that's the BluetoothLeScanner in a nutshell. It's our gateway to the world of BLE discovery. It's powerful, it's complex, but as we're learning, it's getting smarter and more efficient with every new Android release. Now that we know our tool, let's get our hands dirty and build our first passive scanner!</p>
<h2 id="heading-hands-on-building-your-first-passive-scanner">Hands-On: Building Your First Passive Scanner</h2>
<p>Theory is great, but let's be honest, we're developers. We learn by doing (or by copying pasting from Stack Overflow). It's time to roll up our sleeves, fire up Android Studio, and build something. We're going to create a simple app that uses our newfound passive scanning powers to find nearby BLE devices.</p>
<h3 id="heading-step-1-the-permission-inquisition">Step 1: The Permission Inquisition</h3>
<p>Before we write a single line of Kotlin, we must appease the Android permission gods. This is a sacred and often frustrating ritual. For Bluetooth scanning, the rules have changed a bit over the years.</p>
<p>First, open your <code>AndroidManifest.xml</code> and add the following:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">uses-permission</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.permission.BLUETOOTH"</span> /&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">uses-permission</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.permission.BLUETOOTH_ADMIN"</span> /&gt;</span>

<span class="hljs-comment">&lt;!-- For Android 12 (API 31) and above --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">uses-permission</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.permission.BLUETOOTH_SCAN"</span> /&gt;</span>

<span class="hljs-comment">&lt;!-- For older versions, you needed location permissions --&gt;</span>
<span class="hljs-comment">&lt;!-- You might still need this if you support older devices --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">uses-permission</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.permission.ACCESS_FINE_LOCATION"</span> /&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">uses-permission</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.permission.ACCESS_COARSE_LOCATION"</span> /&gt;</span>
</code></pre>
<p>Looking at the permissions we've declared above, you can see the evolution of Android's Bluetooth permission model playing out in real-time.</p>
<p>The first two permissions, <code>BLUETOOTH</code> and <code>BLUETOOTH_ADMIN</code>, are the old guard. They've been around since the early days of Android and provide basic Bluetooth functionality and the ability to discover devices. Then we have <code>BLUETOOTH_SCAN</code>, which was introduced in Android 12 (API 31) and represents a major shift in how Google thinks about privacy.</p>
<p>Yes, you're seeing that right. In the good old days (before Android 12), Google decided that finding a Bluetooth device was basically the same as knowing your user's exact location. It kind of made sense: after all, if you can see which Bluetooth beacons are nearby, you can triangulate your position. But it was also a bit creepy to ask for location just to find a pair of headphones. This led to the awkward situation where users would see a simple Bluetooth scanner app asking for their precise location and understandably get suspicious.</p>
<p>Thankfully, with Android 12, they introduced the <code>BLUETOOTH_SCAN</code> permission, which is much more sensible. This permission finally allows apps to scan for Bluetooth devices without needing to ask for location access, which makes a lot more sense from a user perspective. You'll still need to request this permission at runtime, but at least you don't have to explain to your users why your simple gadget-finder app wants to know where they live.</p>
<p>However, notice those last two permissions for location access. Those are the remnants of the old system. If you're building an app that needs to support older devices running Android 11 or below, you'll need to keep these location permissions in your manifest for backwards compatibility. On modern devices, the <code>BLUETOOTH_SCAN</code> permission alone will do the job.</p>
<h3 id="heading-step-2-the-code-awakens">Step 2: The Code Awakens</h3>
<p>Alright, let's get to the fun part. Here's a breakdown of how to implement the passive scanner in your Activity or Fragment.</p>
<h4 id="heading-get-the-scanner">Get the Scanner</h4>
<p>First, we need to get an instance of the BluetoothLeScanner.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> bluetoothAdapter: BluetoothAdapter? <span class="hljs-keyword">by</span> lazy {
    <span class="hljs-keyword">val</span> bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) <span class="hljs-keyword">as</span> BluetoothManager
    bluetoothManager.adapter
}

<span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> bleScanner: BluetoothLeScanner? <span class="hljs-keyword">by</span> lazy {
    bluetoothAdapter?.bluetoothLeScanner
}
</code></pre>
<p>Let's break down what's happening in the code above. We're using Kotlin's <code>lazy</code> delegation, which is a fancy way of saying "don't create this object until I actually need it." This is a good practice because getting the Bluetooth adapter involves system calls, and there's no point in doing that work if we never actually use it.</p>
<p>First, we grab the <code>BluetoothManager</code> from the system services. Think of the <code>BluetoothManager</code> as the gatekeeper to all things Bluetooth on your device. From this manager, we get the <code>BluetoothAdapter</code>, which represents your device's physical Bluetooth hardware. Notice that we're declaring it as nullable (<code>BluetoothAdapter?</code>) because, believe it or not, not every Android device has Bluetooth. Some tablets or obscure devices might not have the hardware, so we need to be prepared for that possibility.</p>
<p>Once we have the adapter, we can ask it for the <code>BluetoothLeScanner</code>. This is the actual object we'll use to perform our scans. Again, we're using the safe call operator (<code>?.</code>) because if the adapter is null (no Bluetooth hardware), we definitely can't get a scanner from it. This defensive programming might seem paranoid, but it's what separates apps that crash mysteriously from apps that gracefully handle edge cases.</p>
<h4 id="heading-define-the-callback">Define the Callback</h4>
<p>This is where the magic happens. The ScanCallback is an object that will listen for scan results. We need to override two methods: onScanResult and onScanFailed.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> scanCallback = <span class="hljs-keyword">object</span> : ScanCallback() {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onScanResult</span><span class="hljs-params">(callbackType: <span class="hljs-type">Int</span>, result: <span class="hljs-type">ScanResult</span>)</span></span> {
        <span class="hljs-comment">// We found a device! </span>
        <span class="hljs-comment">// The 'result' object contains the device, RSSI, and advertisement data.</span>
        Log.d(<span class="hljs-string">"BleScanner"</span>, <span class="hljs-string">"Found device: <span class="hljs-subst">${result.device.address}</span>, RSSI: <span class="hljs-subst">${result.rssi}</span>"</span>)
    }

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onScanFailed</span><span class="hljs-params">(errorCode: <span class="hljs-type">Int</span>)</span></span> {
        <span class="hljs-comment">// This is the universe's way of telling you to take a break.</span>
        <span class="hljs-comment">// Or that something went horribly wrong.</span>
        Log.e(<span class="hljs-string">"BleScanner"</span>, <span class="hljs-string">"Scan failed with error code: <span class="hljs-variable">$errorCode</span>"</span>)
    }
}
</code></pre>
<p>The <code>ScanCallback</code> we've defined above is your app's ears in the Bluetooth world. When the scanner finds a device, it doesn't just store the information somewhere, it actively calls back to your app through this callback object. This is classic event-driven programming, and it's how Android keeps your app responsive without blocking the main thread.</p>
<p>The <code>onScanResult</code> method is called every time the scanner discovers a device that matches your filters (or any device if you're not using filters). The <code>result</code> parameter is a treasure trove of information. It contains the <code>BluetoothDevice</code> object (which has the device's MAC address and name), the RSSI value (Received Signal Strength Indicator – basically how close the device is, with higher numbers meaning closer), and the raw advertisement data that the device is broadcasting.</p>
<p>In our simple example above, we're just logging the MAC address and RSSI, but in a real app, you'd probably want to update your UI, add the device to a list, or trigger a connection.</p>
<p>The <code>callbackType</code> parameter tells you <em>why</em> this callback was triggered. It could be <code>CALLBACK_TYPE_ALL_MATCHES</code> (the default, meaning "here's every device we found"), <code>CALLBACK_TYPE_FIRST_MATCH</code> (the first time we saw this device), or <code>CALLBACK_TYPE_MATCH_LOST</code> (we haven't seen this device in a while, so it probably left). We'll dive deeper into these types in the advanced section.</p>
<p>Then there's <code>onScanFailed</code>, the method we all hope never gets called but that we absolutely need to handle. This is invoked when something goes catastrophically wrong with the scan. Maybe the Bluetooth adapter got turned off mid-scan, maybe your app doesn't have the right permissions, or maybe the Bluetooth controller just had a bad day. The <code>errorCode</code> will give you a hint about what went wrong, and you should always log this and handle it gracefully – perhaps by showing a message to the user or attempting to restart the scan after a delay.</p>
<h4 id="heading-configure-the-scan">Configure the Scan</h4>
<p>Now, we create our ScanSettings. This is where we tell Android that we want to be a passive, battery-saving ninja.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> scanSettings = ScanSettings.Builder()
    .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER) <span class="hljs-comment">// Let's be nice to the battery</span>
    .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
    .setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE)
    .setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT) <span class="hljs-comment">// Report each ad once</span>
    .setReportDelay(<span class="hljs-number">0L</span>) <span class="hljs-comment">// Report immediately</span>
    <span class="hljs-comment">// And here's the star of the show!</span>
    .setScanType(ScanSettings.SCAN_TYPE_PASSIVE)
    .build()
</code></pre>
<p>The <code>ScanSettings</code> object we're building above is like a detailed instruction manual for the Bluetooth scanner. Each method call fine-tunes exactly how the scan should behave, and getting these settings right is the difference between a battery-friendly app and one that gets uninstalled within hours.</p>
<p>Let's walk through each setting. First, <code>setScanMode(SCAN_MODE_LOW_POWER)</code> tells the scanner to use a low-power scanning mode, which means it will scan in intervals rather than continuously. This is perfect for most use cases where you don't need instant results and want to preserve battery life. The scanner will wake up, scan for a bit, sleep, and repeat. It's the Bluetooth equivalent of taking power naps.</p>
<p>Next, <code>setCallbackType(CALLBACK_TYPE_ALL_MATCHES)</code> means we want to be notified every time the scanner finds a matching device. This is the default behavior and is what you'll use most of the time. As we mentioned earlier, you can also use <code>CALLBACK_TYPE_FIRST_MATCH</code> or <code>CALLBACK_TYPE_MATCH_LOST</code> for more sophisticated presence detection.</p>
<p>The <code>setMatchMode(MATCH_MODE_AGGRESSIVE)</code> setting controls how aggressively the hardware should try to match devices against your filters. <code>MATCH_MODE_AGGRESSIVE</code> means "report matches quickly, even if you're not 100% certain," while <code>MATCH_MODE_STICKY</code> means "wait until you're really sure before reporting." Aggressive mode gives you faster results but might occasionally give you false positives.</p>
<p>Then we have <code>setNumOfMatches(MATCH_NUM_ONE_ADVERTISEMENT)</code>, which tells the scanner to report a device after seeing just one advertisement from it. The alternative is <code>MATCH_NUM_FEW_ADVERTISEMENT</code>, which waits for multiple advertisements before reporting. Using one advertisement gives you faster discovery, while waiting for a few reduces false positives from devices that are just passing by.</p>
<p>The <code>setReportDelay(0L)</code> setting is crucial. A delay of <code>0</code> means "report results immediately." If you set this to, say, <code>5000</code> milliseconds, the scanner would batch up results and deliver them every 5 seconds. Batching is great for background scanning (as we discussed in the advanced section), but for foreground scanning where the user is actively waiting, immediate reporting is what you want.</p>
<p>And finally, the star of our show: <code>setScanType(SCAN_TYPE_PASSIVE)</code>. This is the new API from Android 16 QPR2 that transforms our scanner into a silent listener. Instead of actively sending scan requests to every device it hears, it just listens to the advertisements floating through the air. This single setting can dramatically reduce your app's battery consumption during scanning. It's the feature we've been waiting for, and it's glorious.</p>
<h4 id="heading-start-and-stop-the-scan">Start and Stop the Scan</h4>
<p>Finally, we need functions to start and stop our scan. Remember: always stop your scan! A forgotten scan is a battery-killing monster.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">startBleScan</span><span class="hljs-params">()</span></span> {
    <span class="hljs-comment">// Don't forget to request permissions first!</span>
    <span class="hljs-keyword">if</span> (bleScanner != <span class="hljs-literal">null</span>) {
        <span class="hljs-comment">// You can add ScanFilters here to search for specific devices</span>
        <span class="hljs-keyword">val</span> scanFilters: List&lt;ScanFilter&gt; = listOf() 
        bleScanner.startScan(scanFilters, scanSettings, scanCallback)
        Log.d(<span class="hljs-string">"BleScanner"</span>, <span class="hljs-string">"Scan started."</span>)
    } <span class="hljs-keyword">else</span> {
        Log.e(<span class="hljs-string">"BleScanner"</span>, <span class="hljs-string">"Bluetooth is not available."</span>)
    }
}

<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">stopBleScan</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">if</span> (bleScanner != <span class="hljs-literal">null</span>) {
        bleScanner.stopScan(scanCallback)
        Log.d(<span class="hljs-string">"BleScanner"</span>, <span class="hljs-string">"Scan stopped."</span>)
    }
}
</code></pre>
<p>These two functions above are the on/off switches for your Bluetooth scanner, and they're deceptively simple for how important they are. Let's break down what's happening in each one.</p>
<p>In <code>startBleScan()</code>, we first check if the <code>bleScanner</code> is not null. This is our safety net: if the device doesn't have Bluetooth hardware or if Bluetooth is disabled, the scanner will be null, and we don't want to crash by trying to call methods on a null object. If the scanner exists, we call <code>startScan()</code> with three parameters: a list of <code>ScanFilter</code> objects, our carefully crafted <code>ScanSettings</code>, and the <code>ScanCallback</code> we defined earlier.</p>
<p>The <code>scanFilters</code> list is currently empty in our example, which means "find all BLE devices." In a real-world app, you'd typically add filters here to narrow down your search.</p>
<p>For instance, if you're building an app that only works with heart rate monitors, you'd create a filter that only matches devices advertising the Heart Rate Service UUID. This is crucial for both performance and battery life: why wake up your app for every random Bluetooth toothbrush when you only care about fitness trackers?</p>
<p>The <code>startScan()</code> method kicks off the scanning process. From this point on, the Bluetooth radio is actively (or in our case, passively) listening for advertisements, and your <code>scanCallback</code> will start receiving results. This is an asynchronous operation, meaning your code doesn't block here waiting for results – rather, it continues executing, and the results come in through the callback whenever they're available.</p>
<p>Now let's talk about <code>stopBleScan()</code>, which might be the most important function you write. When you call <code>stopScan()</code> with your callback, you're telling the Bluetooth radio, "Okay, we're done here, you can go back to sleep." This immediately stops the scanning process and releases the resources.</p>
<p>The critical thing to understand is that if you don't call this, the scan will continue running indefinitely, draining your user's battery like a vampire at an all-you-can-eat blood bank. This is why we emphasize it so much: a forgotten <code>stopScan()</code> call is one of the most common causes of battery drain complaints in Bluetooth apps.</p>
<p>Notice that we're passing the same <code>scanCallback</code> object to <code>stopScan()</code> that we used in <code>startScan()</code>. This is how Android knows which scan to stop – you might theoretically have multiple scans running with different callbacks (though that's rarely a good idea). Always make sure you're stopping the same scan you started by using the same callback reference.</p>
<h3 id="heading-putting-it-all-together">Putting It All Together</h3>
<p>Here's a complete example you can drop into an Activity. Just remember to handle the runtime permissions!</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// In your Activity class</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainActivity</span> : <span class="hljs-type">AppCompatActivity</span></span>() {

    <span class="hljs-comment">// ... (lazy properties for adapter and scanner from above)</span>

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> {
        <span class="hljs-keyword">super</span>.onCreate(savedInstanceState)
        <span class="hljs-comment">// ... your UI setup ...</span>

        <span class="hljs-comment">// Example: Start scan on button click</span>
        <span class="hljs-keyword">val</span> startButton = findViewById&lt;Button&gt;(R.id.startButton)
        startButton.setOnClickListener {
            <span class="hljs-comment">// You MUST request permissions before calling this!</span>
            startBleScan()
        }

        <span class="hljs-comment">// Example: Stop scan on another button click</span>
        <span class="hljs-keyword">val</span> stopButton = findViewById&lt;Button&gt;(R.id.stopButton)
        stopButton.setOnClickListener {
            stopBleScan()
        }
    }

    <span class="hljs-comment">// ... (scanCallback, startBleScan, stopBleScan functions from above)</span>

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onPause</span><span class="hljs-params">()</span></span> {
        <span class="hljs-keyword">super</span>.onPause()
        <span class="hljs-comment">// Always stop scanning when the activity is not visible.</span>
        stopBleScan()
    }
}
</code></pre>
<p>The complete example above shows how all the pieces fit together in a real Activity. This is a minimal but functional Bluetooth scanner that you can actually run. Let's highlight a few important patterns we're using here.</p>
<p>First, notice how we're tying the scan lifecycle to user actions through button clicks. This is a common pattern: the user explicitly starts and stops the scan, giving them control over when the app is using Bluetooth. This is both good UX and good for battery life, as the scan only runs when the user wants it to.</p>
<p>But here's the really important part: the <code>onPause()</code> override. This is a critical safety net. When your Activity goes into the background (maybe the user pressed the home button, or they switched to another app), <code>onPause()</code> is called, and we immediately stop the scan. This is essential because if the user can't see your app, they don't need scan results, and there's no reason to drain their battery. This pattern ensures that even if the user forgets to press the "Stop" button, the scan won't run forever in the background.</p>
<p>You might be wondering, "What about <code>onResume()</code>? Shouldn't we restart the scan when the user comes back?" That's a design decision. In some apps, you might want to automatically restart scanning in <code>onResume()</code>. In others, you might want the user to explicitly press "Start" again. It depends on your use case. For a device-finding app where the user is actively searching, auto-resuming makes sense. For a monitoring app that runs in the background, you might want more explicit control.</p>
<p>One crucial thing we haven't shown in this example is runtime permission handling. Remember those permissions we declared in the manifest? On Android 6.0 and above, you can't just declare them, you have to actually request them from the user at runtime. Before calling <code>startBleScan()</code>, you should check if you have the necessary permissions and, if not, request them using <code>ActivityCompat.requestPermissions()</code>. If you try to start a scan without the proper permissions, it will fail silently (or loudly, depending on the Android version), and you'll be left scratching your head wondering why nothing is working.</p>
<p>And there you have it! You've just built your first AOSP 16 passive Bluetooth scanner. It's lean, it's mean, and it's incredibly power-efficient. The scanner listens silently for BLE advertisements, reports them through your callback, and stops gracefully when it's not needed.</p>
<p>Now, let's move on to our next topic: what to do when things go wrong. It's time to talk about breakups... Bluetooth bond breakups, that is.</p>
<h2 id="heading-deep-dive-2-bluetooth-bond-loss-reasons">Deep Dive #2: Bluetooth Bond Loss Reasons</h2>
<p>Ah, the Bluetooth bond. It's a beautiful, sacred thing. It's the digital equivalent of exchanging friendship bracelets. When you bond your phone with your headphones, you're creating a long-term, trusted relationship. They share secret keys, they remember each other, and they promise to connect automatically, saving you the hassle of pairing every single time. It's a beautiful romance.</p>
<p>Until it's not.</p>
<p>Suddenly, one day, they just... forget each other. The connection is gone. The trust is broken. And your app is left in the middle, trying to play therapist, with no idea what went wrong. You've been ghosted. And until now, Android has been no help. You'd get a notification that the bond state is now BOND_NONE, but that's it. No explanation. No closure. Just the cold, hard silence of a failed connection.</p>
<h3 id="heading-finally-some-closure">Finally, Some Closure!</h3>
<p>But our friends on the Android team have clearly been through some tough breakups, because in AOSP 16, they've given us the gift of closure. Introducing BluetoothDevice.EXTRA_BOND_LOSS_REASON. It's a new extra that comes with the ACTION_BOND_STATE_CHANGED broadcast, and it's here to tell you why the bond was lost. It's like getting a breakup text that actually explains what happened!</p>
<p>Now, when a bond is broken, you can get a specific reason code. Think of them as the classic breakup excuses, but for Bluetooth:</p>
<table><tbody><tr><td><p><strong>Reason Code (Illustrative)</strong></p></td><td><p><strong>What it Actually Means</strong></p></td></tr><tr><td><p>BOND_LOSS_REASON_BREDR_AUTH_FAILURE</p></td><td><p>Indicates that the reason for the bond loss is BREDR authentication failure.</p></td></tr><tr><td><p>BOND_LOSS_REASON_BREDR_INCOMING_PAIRING</p></td><td><p>Indicates that the reason for the bond loss is BREDR pairing failure.</p></td></tr><tr><td><p>BOND_LOSS_REASON_LE_ENCRYPT_FAILURE</p></td><td><p>Indicates that the reason for the bond loss is LE encryption failure.</p></td></tr><tr><td><p>BOND_LOSS_REASON_LE_INCOMING_PAIRING</p></td><td><p>Indicates that the reason for the bond loss is LE pairing failure.</p></td></tr></tbody></table>

<h3 id="heading-the-code-playing-detective">The Code: Playing Detective</h3>
<p>So, how do we get this juicy gossip? We need to set up a BroadcastReceiver to listen for bond state changes.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// Create a BroadcastReceiver to listen for bond state changes</span>
<span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> bondStateReceiver = <span class="hljs-keyword">object</span> : BroadcastReceiver() {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onReceive</span><span class="hljs-params">(context: <span class="hljs-type">Context</span>, intent: <span class="hljs-type">Intent</span>)</span></span> {
        <span class="hljs-keyword">if</span> (intent.action == BluetoothDevice.ACTION_BOND_STATE_CHANGED) {
            <span class="hljs-keyword">val</span> device: BluetoothDevice? = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
            <span class="hljs-keyword">val</span> bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR)
            <span class="hljs-keyword">val</span> previousBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR)

            <span class="hljs-comment">// Check if we went from bonded to not bonded</span>
            <span class="hljs-keyword">if</span> (bondState == BluetoothDevice.BOND_NONE &amp;&amp; previousBondState == BluetoothDevice.BOND_BONDED) {
                Log.d(<span class="hljs-string">"BondBreakup"</span>, <span class="hljs-string">"We got dumped by <span class="hljs-subst">${device?.address}</span>!"</span>)

                <span class="hljs-comment">// Now, let's find out why...</span>
                <span class="hljs-keyword">val</span> reason = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_LOSS_REASON, -<span class="hljs-number">1</span>)

                <span class="hljs-keyword">when</span> (reason) {
                    <span class="hljs-comment">// Note: The actual constant values are in the Android SDK</span>
                    BluetoothDevice.BOND_LOSS_REASON_REMOTE_DEVICE_REMOVED -&gt; {
                        Log.d(<span class="hljs-string">"BondBreakup"</span>, <span class="hljs-string">"Reason: The remote device removed the bond."</span>)
                        <span class="hljs-comment">// You could show a message to the user: "Your headphones seem to have forgotten you. Please try pairing again."</span>
                    }
                    <span class="hljs-comment">// ... handle other reasons ...</span>
                    <span class="hljs-keyword">else</span> -&gt; {
                        Log.d(<span class="hljs-string">"BondBreakup"</span>, <span class="hljs-string">"Reason: It's complicated (Unknown reason code: <span class="hljs-variable">$reason</span>)"</span>)
                    }
                }
            }
        }
    }
}

<span class="hljs-comment">// In your Activity or Service, register the receiver</span>
<span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onResume</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">super</span>.onResume()
    <span class="hljs-keyword">val</span> filter = IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
    registerReceiver(bondStateReceiver, filter)
}

<span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onPause</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">super</span>.onPause()
    <span class="hljs-comment">// Don't forget to unregister!</span>
    unregisterReceiver(bondStateReceiver)
}
</code></pre>
<p>The code above implements a detective system for Bluetooth bond breakups, and it's more sophisticated than it might first appear. Let's walk through how this broadcast receiver pattern works and why it's so powerful.</p>
<p>First, we're creating a <code>BroadcastReceiver</code>, which is Android's way of letting your app listen for system-wide events. Think of it as subscribing to a notification service, whenever something interesting happens in the Android system (like a bond state change), the system broadcasts an "intent" to all registered listeners. Our receiver is one of those listeners.</p>
<p>In the <code>onReceive()</code> method, we first check if the incoming intent's action is <code>ACTION_BOND_STATE_CHANGED</code>. This is crucial because broadcast receivers can potentially receive many different types of intents, and we only care about bond state changes. Once we've confirmed this is the right type of event, we extract the relevant information from the intent using <code>getParcelableExtra()</code> and <code>getIntExtra()</code>.</p>
<p>The <code>device</code> object tells us which Bluetooth device this event is about. After all, you might be bonded to multiple devices (your headphones, your smartwatch, your car), and we need to know which one just broke up with us. The <code>bondState</code> tells us the current state (are we bonded, bonding, or not bonded?), and <code>previousBondState</code> tells us what the state was before this change occurred.</p>
<p>The key logic happens in our conditional check: <code>if (bondState == BluetoothDevice.BOND_NONE &amp;&amp; previousBondState == BluetoothDevice.BOND_BONDED)</code>. This is checking for the specific transition from "bonded" to "not bonded," which is the digital equivalent of a breakup. We're not interested in the bonding process itself (going from none to bonding to bonded) – we only care about when an existing bond is lost.</p>
<p>Once we've detected a breakup, we extract the new <code>EXTRA_BOND_LOSS_REASON</code> from the intent. This is the star feature from AOSP 16 that finally gives us closure. The reason code tells us exactly why the bond was lost – was it the remote device that ended things? Did the user manually forget the device? Did authentication fail? Each reason code corresponds to a different scenario, and you can handle each one appropriately.</p>
<p>In the example above, we're using a when expression to handle different reason codes. For BOND_LOSS_REASON_BREDR_INCOMING_PAIRING, we know the other device initiated the breakup, so we can show a helpful message like "Your headphones seem to have forgotten you. Please try pairing again." For other reasons, you'd add more branches to handle them specifically.</p>
<p>Now, notice the lifecycle management at the bottom. We register our receiver in <code>onResume()</code> and unregister it in <code>onPause()</code>. This is critical: if you forget to unregister a broadcast receiver, it will continue to receive broadcasts even after your Activity is destroyed, which can cause memory leaks and crashes. The pattern of registering in <code>onResume()</code> and unregistering in <code>onPause()</code> ensures that we only listen for bond changes when our Activity is visible and active.</p>
<p>This is a huge step forward for debugging and for user experience. Instead of just telling the user "Connection failed," you can now give them actionable advice based on the specific reason the bond was lost. It's like being a helpful, informed relationship counselor instead of a confused bystander who can only shrug and say "I don't know what happened."</p>
<p>Now that we've dealt with the emotional baggage of breakups, let's move on to something a little more lighthearted: speed dating for Bluetooth devices.</p>
<h2 id="heading-deep-dive-3-service-uuids-from-advertisements">Deep Dive #3: Service UUIDs from Advertisements</h2>
<p>Let's talk about finding a compatible partner... for your app. In the world of BLE, not all devices are created equal. A heart rate monitor is very different from a smart lightbulb. So how does your app know if it's talking to the right kind of device? The answer is the Service UUID.</p>
<h3 id="heading-what-in-the-world-is-a-service-uuid">What in the World is a Service UUID?</h3>
<p>A Service UUID (Universally Unique Identifier) is like a device's job title. It's a unique, 128-bit number that says, "I am a device that provides a Heart Rate Service" or "I am a device that provides a Battery Service." It's the single most important piece of information for determining what a device can do.</p>
<h3 id="heading-the-old-way-the-awkward-first-date">The Old Way: The Awkward First Date</h3>
<p>Traditionally, finding out a device's services was a whole ordeal. It was like going on a full, three-course dinner date just to find out the other person's job. The process went something like this:</p>
<ol>
<li><p>Scan: Find the device.</p>
</li>
<li><p>Connect: Establish a connection (a slow and power-hungry process).</p>
</li>
<li><p>Discover Services: Ask the device, "So... what do you do for a living?" and wait for it to list all its services.</p>
</li>
<li><p>Evaluate: Check if the list of services contains the one you're interested in.</p>
</li>
<li><p>Disconnect (or stay connected): If it's not the right device, you have to break up (disconnect) and move on. What a waste of time and energy!</p>
</li>
</ol>
<p>This is incredibly inefficient, especially if you're in a crowded room with dozens of BLE devices and you're only looking for one specific type.</p>
<h3 id="heading-the-new-way-the-glorious-name-tag">The New Way: The Glorious Name Tag</h3>
<p>Wouldn't it be great if everyone at a party just wore a name tag with their job title on it? That's exactly what AOSP 16 has given us with BluetoothDevice.EXTRA_UUID_LE. Many BLE devices are already polite enough to include their primary service UUID in their advertisement packets. It's their way of shouting, "I'M A HEART RATE MONITOR!" to the whole room.</p>
<p>Before AOSP 16, getting this information out of the advertisement packet was a messy, manual process of parsing the raw byte array of the scan record. It was doable, but it was the kind of code that you'd write once, pray it worked, and never touch again.</p>
<p>Now, Android does the dirty work for us! The system automatically parses the advertising data and, if it finds any service UUIDs, it conveniently hands them to you in the ScanResult.</p>
<h3 id="heading-the-code-reading-the-name-tag">The Code: Reading the Name Tag</h3>
<p>This new feature makes our ScanCallback even more powerful. We can now check the device's job title the moment we discover it, without ever having to connect.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> scanCallback = <span class="hljs-keyword">object</span> : ScanCallback() {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onScanResult</span><span class="hljs-params">(callbackType: <span class="hljs-type">Int</span>, result: <span class="hljs-type">ScanResult</span>)</span></span> {
        Log.d(<span class="hljs-string">"BleSpeedDating"</span>, <span class="hljs-string">"Found device: <span class="hljs-subst">${result.device.address}</span>"</span>)

        <span class="hljs-comment">// Let's check their name tag!</span>
        <span class="hljs-keyword">val</span> serviceUuids = result.scanRecord?.serviceUuids
        <span class="hljs-keyword">if</span> (serviceUuids.isNullOrEmpty()) {
            Log.d(<span class="hljs-string">"BleSpeedDating"</span>, <span class="hljs-string">"This one is mysterious. No service UUIDs in the ad."</span>)
            <span class="hljs-keyword">return</span>
        }

        <span class="hljs-comment">// Define the UUID we're looking for (e.g., the standard Heart Rate Service UUID)</span>
        <span class="hljs-keyword">val</span> heartRateServiceUuid = ParcelUuid.fromString(<span class="hljs-string">"0000180D-0000-1000-8000-00805F9B34FB"</span>)

        <span class="hljs-keyword">if</span> (serviceUuids.contains(heartRateServiceUuid)) {
            Log.d(<span class="hljs-string">"BleSpeedDating"</span>, <span class="hljs-string">"It's a match! This is a heart rate monitor. Let's connect!"</span>)
            <span class="hljs-comment">// Now you can proceed to connect to result.device, knowing it's the right one.</span>
            stopBleScan() <span class="hljs-comment">// We found what we were looking for</span>
            <span class="hljs-comment">// connectToDevice(result.device)</span>
        } <span class="hljs-keyword">else</span> {
            Log.d(<span class="hljs-string">"BleSpeedDating"</span>, <span class="hljs-string">"Not a match. Moving on."</span>)
        }
    }

    <span class="hljs-comment">// ... onScanFailed ...</span>
}
</code></pre>
<p>The code above demonstrates the power of reading service UUIDs directly from advertisement data, and it's a game-changer for device discovery. Let's break down exactly what's happening and why this is such a significant improvement.</p>
<p>When we receive a scan result in our callback, the <code>result</code> object contains a <code>scanRecord</code> property. This scan record is essentially the raw advertisement packet that the BLE device broadcast into the air.</p>
<p>Before AOSP 16, if you wanted to extract service UUIDs from this data, you'd have to manually parse the byte array, understand the BLE advertisement format, handle different data types, and pray you didn't make an off-by-one error. It was the kind of code that worked once and then you never touched it again out of fear.</p>
<p>Now, with the improvements in AOSP 16, Android does all that messy parsing for us. We can simply call <code>result.scanRecord?.serviceUuids</code> and get back a nice, clean list of <code>ParcelUuid</code> objects. The safe call operator (<code>?.</code>) is important here because not all devices include a scan record in their results, and we need to handle that gracefully.</p>
<p>After retrieving the service UUIDs, we check if the list is null or empty. Some devices don't include service UUIDs in their advertisements. They might be using a proprietary format, or they might just be poorly configured. If there are no UUIDs, we log a message and return early. There's no point in continuing if we can't identify what the device does.</p>
<p>Next, we define the UUID we're looking for. In this example, we're searching for heart rate monitors, so we use the standard Heart Rate Service UUID: <code>0000180D-0000-1000-8000-00805F9B34FB</code>. This is a UUID defined by the Bluetooth SIG (Special Interest Group), and any compliant heart rate monitor will advertise this UUID. You can find a complete list of standard service UUIDs in the Bluetooth specifications, or you can use custom UUIDs if you're building your own BLE peripherals.</p>
<p>The magic happens in the <code>if (serviceUuids.contains(heartRateServiceUuid))</code> check. This is where we're doing our speed dating: we're checking the device's "name tag" to see if it matches what we're looking for.</p>
<p>If it does, we've found our match! We can immediately stop scanning (because why keep looking when we've found what we need?) and proceed to connect to the device. We know, with certainty, that this device is a heart rate monitor, so we won't waste time and battery connecting to random devices only to discover they're not what we need.</p>
<p>If the UUID doesn't match, we simply log "Not a match" and move on. The callback will be called again when the next device is found, and we'll repeat this process until we find our heart rate monitor or the user stops the scan.</p>
<p>This is a massive performance improvement over the old approach. Previously, you'd have to connect to every device you found, perform service discovery (which involves multiple round-trip communications with the device), check if it has the services you need, and then disconnect if it doesn't. Each connection attempt takes time, uses battery, and creates unnecessary radio traffic.</p>
<p>Now, you can filter and identify devices at lightning speed, all at the scanning stage. No more awkward first dates where you connect to a smart lightbulb thinking it might be a fitness tracker. Just efficient, targeted connections.</p>
<p>This is particularly useful for apps that need to find a specific type of sensor or peripheral in a sea of irrelevant devices. Imagine you're in a hospital with hundreds of BLE-enabled medical devices, or in a smart home with dozens of sensors and actuators. Being able to instantly identify the right device from its advertisement is the difference between a responsive, professional app and one that feels sluggish and unreliable.</p>
<p>We've now met all three of our Bluetooth musketeers: passive scanning for battery efficiency, bond loss reasons for better debugging, and service UUIDs from advertisements for faster device identification. But our journey isn't over. It's time to venture into the deep woods of advanced scanning techniques.</p>
<h2 id="heading-advanced-topics-filtering-batching-and-other-sorcery">Advanced Topics: Filtering, Batching, and Other Sorcery</h2>
<p>Alright, you've mastered the basics. You can scan passively, you can get closure on your connection breakups, and you can speed-date devices like a pro. You're no longer a Bluetooth padawan. It's time to become a Jedi Master.</p>
<p>Let's dive into the advanced arts of filtering, batching, and other optimization sorcery that will make your app a true battery-saving champion.</p>
<h3 id="heading-hardware-filtering-your-personal-assistant">Hardware Filtering: Your Personal Assistant</h3>
<p>Imagine you're a celebrity, and you've hired a personal assistant. You don't want to be bothered by every single person who wants an autograph. So, you give your assistant a list: "Only let me know if you see my agent or my mom." Your assistant then stands at the door and only bothers you when someone on the list shows up.</p>
<p>This is exactly what hardware filtering does. Instead of your app's code (the celebrity) being woken up for every single Bluetooth device the radio sees, you can offload the filtering logic to the Bluetooth controller itself (the personal assistant). This is a feature that's been around since Android 6.0, but it's more important than ever.</p>
<p>Why is this so great? Because your app's code can stay asleep. The main processor (the AP) doesn't have to wake up every time a random Bluetooth toothbrush advertises itself. The Bluetooth controller, which is much more power-efficient, handles the filtering. The AP only wakes up when the controller finds a device that matches your criteria.</p>
<h3 id="heading-the-code-building-your-vip-list">The Code: Building Your VIP List</h3>
<p>You implement this using ScanFilter. You can filter by a device's name, its MAC address, or, most usefully, by the Service UUID it's advertising.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// We only want to be bothered if we see a heart rate monitor.</span>
<span class="hljs-keyword">val</span> heartRateServiceUuid = ParcelUuid.fromString(<span class="hljs-string">"0000180D-0000-1000-8000-00805F9B34FB"</span>)

<span class="hljs-keyword">val</span> filter = ScanFilter.Builder()
    .setServiceUuid(heartRateServiceUuid)
    .build()

<span class="hljs-keyword">val</span> scanFilters: List&lt;ScanFilter&gt; = listOf(filter)

<span class="hljs-comment">// Now, when you start your scan, pass in this list</span>
bleScanner.startScan(scanFilters, scanSettings, scanCallback)
</code></pre>
<p>The code above shows how to create a hardware-level filter that dramatically improves both battery life and app performance. Let's dive deep into what's happening here and why this is such a powerful technique.</p>
<p>We start by defining the service UUID we're interested in – in this case, the standard Heart Rate Service UUID. This is the same UUID we used in the previous example, but now we're using it in a fundamentally different way. Instead of checking the UUID in our app's code after receiving scan results, we're telling the Bluetooth hardware itself to only report devices that match this UUID.</p>
<p>The <code>ScanFilter.Builder()</code> is our tool for constructing this filter. It's a builder pattern, which means we can chain multiple methods together to configure exactly what we're looking for. In this example, we're calling <code>setServiceUuid(heartRateServiceUuid)</code>, which tells the filter to only match devices that advertise this specific service.</p>
<p>But the builder has many other options you can use:</p>
<ul>
<li><p><code>setDeviceName()</code> – Match devices with a specific name (like "My Heart Monitor")</p>
</li>
<li><p><code>setDeviceAddress()</code> – Match a specific device by its MAC address (useful if you've already paired with a device and want to find it again)</p>
</li>
<li><p><code>setManufacturerData()</code> – Match devices based on manufacturer-specific data in their advertisements</p>
</li>
<li><p><code>setServiceData()</code> – Match based on service data included in the advertisement</p>
</li>
</ul>
<p>You can even combine multiple criteria in a single filter. For example, you could create a filter that matches devices with a specific service UUID <em>and</em> a specific manufacturer ID. The more specific your filter, the fewer false positives you'll get.</p>
<p>After building our filter, we create a list containing it. Why a list? Because you can have multiple filters, and a device will match if it satisfies <em>any</em> of the filters in the list. For instance, you might create one filter for heart rate monitors and another for blood pressure monitors, and your scan will report devices that match either one. This is an OR operation: the device doesn't need to match all filters, just one of them.</p>
<p>Finally, we pass this list of filters to <code>startScan()</code> along with our scan settings and callback. This is where the magic happens. When you provide filters, Android doesn't just filter the results in your app's code. It pushes these filters down to the Bluetooth controller hardware itself. This means the filtering happens at the lowest level, before your app is even notified.</p>
<p>Here's why this is so powerful: without filters, every time the Bluetooth radio hears an advertisement from <em>any</em> device (your neighbor's smart toaster, someone's fitness tracker walking by, the Bluetooth speaker three rooms away), it has to wake up your app's process, deliver the scan result, and let your code decide if it cares about this device. Each of these wake-ups costs battery and processing time.</p>
<p>With hardware filters, the Bluetooth controller silently ignores all the devices that don't match your criteria. Your app stays asleep. The main processor stays asleep. Only when a heart rate monitor is detected does the hardware wake up your app and deliver the result. It's like having a bouncer at a club who only lets in people on the VIP list. Everyone else is turned away at the door, and you never even know they were there.</p>
<p>By using a <code>ScanFilter</code>, you're telling the hardware, "Don't wake me up unless you see a heart rate monitor." It's the ultimate power-saving move for background scanning. Combined with passive scanning and batch reporting, you can create a Bluetooth scanning system that runs for hours or even days with minimal battery impact. This is how professional-grade apps handle long-term device monitoring without destroying battery life.</p>
<h3 id="heading-batch-scanning-the-daily-report">Batch Scanning: The Daily Report</h3>
<p>Let's go back to our celebrity analogy. Sometimes, you don't need to be interrupted the moment your mom shows up. You'd rather just get a report at the end of the day: "Today, your mom stopped by twice, and your agent called once." This is batch scanning.</p>
<p>Instead of delivering scan results to your app in real-time, the Bluetooth controller can collect them and deliver them in a big batch. This is another incredible power-saving feature. Your app can sleep for long periods, then wake up, process a whole bunch of results at once, and go back to sleep.</p>
<p>You enable this with the setReportDelay() method in your ScanSettings.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> scanSettings = ScanSettings.Builder()
    <span class="hljs-comment">// ... other settings ...</span>
    <span class="hljs-comment">// Deliver results every 5 seconds (5000 milliseconds)</span>
    .setReportDelay(<span class="hljs-number">5000</span>)
    .build()
</code></pre>
<p>When you use a report delay, your onScanResult callback will be replaced by onBatchScanResults, which gives you a List&lt;ScanResult&gt;.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> scanCallback = <span class="hljs-keyword">object</span> : ScanCallback() {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onBatchScanResults</span><span class="hljs-params">(results: <span class="hljs-type">List</span>&lt;<span class="hljs-type">ScanResult</span>&gt;)</span></span> {
        Log.d(<span class="hljs-string">"BatchScanner"</span>, <span class="hljs-string">"Here's your daily report! Found <span class="hljs-subst">${results.size}</span> devices."</span>)
        <span class="hljs-keyword">for</span> (result <span class="hljs-keyword">in</span> results) {
            <span class="hljs-comment">// Process each result</span>
        }
    }

    <span class="hljs-comment">// ... onScanFailed ...</span>
}
</code></pre>
<p>The batch scanning mechanism shown above is one of the most underutilized power-saving features in Android Bluetooth, and understanding how it works can transform your app's battery profile. Let's break down exactly what's happening under the hood and when you should use this technique.</p>
<p>When you set a report delay of 5000 milliseconds (5 seconds) in the code above, you're fundamentally changing how the scanning pipeline works. Instead of the Bluetooth controller immediately waking up your app every time it sees a device, it acts like a diligent assistant taking notes. For those 5 seconds, the controller silently collects every scan result it encounters, storing them in its own internal buffer. Your app remains completely asleep during this time – no CPU cycles wasted, no battery drained by context switches or process wake-ups.</p>
<p>After the 5-second delay expires, the controller delivers all the accumulated results in one batch to your <code>onBatchScanResults()</code> callback. This is where the power savings come from: instead of waking up your app 50 times if 50 devices were detected, it wakes up once and hands you all 50 results at the same time. Your app can then efficiently process this batch – maybe updating a UI list, logging the data, or checking for specific devices – and then go back to sleep until the next batch arrives.</p>
<p>The <code>results</code> parameter in <code>onBatchScanResults()</code> is a <code>List&lt;ScanResult&gt;</code>, and each <code>ScanResult</code> in the list represents a single advertisement that was heard during the batching period. It's important to note that if the same device advertises multiple times during the delay period, you might receive multiple results for that device in the batch. The list isn't automatically deduplicated – that's your job if you need it.</p>
<p>In the example above, we're simply logging the number of devices found and then iterating through each result. In a real application, you might want to do more sophisticated processing. For instance, you could build a map of devices keyed by MAC address to track how many times each device advertised, calculate average RSSI values to estimate distance, or filter the batch to only process devices that meet certain criteria.</p>
<p><strong>Warning:</strong> Batch scanning is a powerful tool, but it's not for every situation. If you need to react to a device's presence immediately (for example, if you're building a "find my keys" app where the user is actively searching), a report delay is not your friend. The user doesn't want to wait 5 seconds to see results – they want instant feedback. In these cases, set <code>setReportDelay(0)</code> for immediate reporting.</p>
<p>But for long-term monitoring or data collection scenarios, batch scanning is a battery's best friend. Consider these use cases:</p>
<ul>
<li><p><strong>Background presence monitoring</strong>: Your app checks every minute to see if the user's smartwatch is still in range, but doesn't need second-by-second updates.</p>
</li>
<li><p><strong>Environmental sensing</strong>: You're collecting data from temperature sensors throughout a building and only need to update your dashboard every 30 seconds.</p>
</li>
<li><p><strong>Beacon analytics</strong>: You're tracking how many people pass by a retail location based on their phone's BLE advertisements, and you aggregate the data every 10 seconds.</p>
</li>
</ul>
<p>The sweet spot for report delay depends on your use case. Too short (like 1 second), and you're not getting much benefit, you're still waking up frequently. Too long (like 60 seconds), and your app might feel unresponsive or miss time-sensitive events. For most background monitoring tasks, delays between 5 and 30 seconds work well.</p>
<p>One more thing to be aware of: batch scanning has limits. The Bluetooth controller has a finite buffer for storing scan results. If you set a very long delay and you're in an environment with hundreds of BLE devices, the buffer might fill up before the delay expires. When this happens, the oldest results get dropped. Android doesn't give you a warning when this occurs, so if you're missing data, consider reducing your report delay or using more aggressive filters to reduce the number of results being collected.</p>
<h3 id="heading-onfoundonlost-the-drama-of-presence">OnFound/OnLost: The Drama of Presence</h3>
<p>Since Android 8.0, scanning has gotten even more dramatic. You can now ask the hardware to not only tell you when it finds a device, but also when it loses one. This is done using the CALLBACK_TYPE_FIRST_MATCH and CALLBACK_TYPE_MATCH_LOST flags in your ScanSettings.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> scanSettings = ScanSettings.Builder()
    .setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH or ScanSettings.CALLBACK_TYPE_MATCH_LOST)
    .build()
</code></pre>
<p>Now, in your ScanCallback, the callbackType parameter in onScanResult will tell you what happened.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onScanResult</span><span class="hljs-params">(callbackType: <span class="hljs-type">Int</span>, result: <span class="hljs-type">ScanResult</span>)</span></span> {
    <span class="hljs-keyword">when</span> (callbackType) {
        ScanSettings.CALLBACK_TYPE_FIRST_MATCH -&gt; {
            Log.d(<span class="hljs-string">"PresenceDetector"</span>, <span class="hljs-string">"Found them! <span class="hljs-subst">${result.device.address}</span> has entered the building."</span>)
        }
        ScanSettings.CALLBACK_TYPE_MATCH_LOST -&gt; {
            Log.d(<span class="hljs-string">"PresenceDetector"</span>, <span class="hljs-string">"They're gone! <span class="hljs-subst">${result.device.address}</span> has left the building."</span>)
        }
    }
}
</code></pre>
<p>The presence detection mechanism shown above represents a fundamental shift in how we think about Bluetooth scanning. Instead of treating scanning as a continuous stream of "here's what I see right now," we're now working with events: "this device appeared" and "this device disappeared." Let's dive deep into how this works and why it's so powerful.</p>
<p>When you set the callback type using the bitwise OR operator (<code>or</code> in Kotlin, <code>|</code> in Java), you're telling the Bluetooth hardware to track the presence state of devices over time. The code <code>CALLBACK_TYPE_FIRST_MATCH or CALLBACK_TYPE_MATCH_LOST</code> combines both flags, meaning you want to be notified both when a device first appears and when it disappears. You can use these flags individually if you only care about one type of event, but using both together gives you complete presence awareness.</p>
<p>Let's understand what "first match" and "match lost" actually mean. When the Bluetooth controller hears an advertisement from a device that matches your filters for the first time, it triggers a <code>CALLBACK_TYPE_FIRST_MATCH</code> event. This is different from <code>CALLBACK_TYPE_ALL_MATCHES</code> (the default), which would trigger every single time the device advertises. A device might advertise multiple times per second, so the difference is significant. With <code>FIRST_MATCH</code>, you get one notification when the device enters your scanning range, not a flood of notifications as it continues to advertise.</p>
<p>The <code>CALLBACK_TYPE_MATCH_LOST</code> event is even more interesting. The Bluetooth controller keeps track of when it last heard from each device. If a device stops advertising (because it moved out of range, was turned off, or its battery died), the controller notices the absence and triggers a <code>MATCH_LOST</code> event. This happens automatically: you don't have to manually track timestamps or implement timeout logic in your app. The hardware does it for you.</p>
<p>But how does the hardware know when a device is "lost"? It uses an internal timeout. If the controller hasn't heard from a device for a certain period (typically a few seconds, though the exact duration is implementation-dependent and not exposed to apps), it considers the device lost. This means there's a slight delay between when a device actually leaves range and when you get the <code>MATCH_LOST</code> callback, but this delay is usually acceptable for presence detection use cases.</p>
<p>In the code example above, we're using a <code>when</code> expression to handle the different callback types. When we receive a <code>FIRST_MATCH</code>, we know the device has just entered our scanning range, so we log "Found them!" This is perfect for triggering actions like unlocking a door when your phone comes near, or starting to sync data when your fitness tracker is detected.</p>
<p>When we receive a <code>MATCH_LOST</code>, we know the device has left our scanning range or stopped advertising, so we log "They're gone!" This is ideal for triggering cleanup actions like locking the door when your phone leaves, or stopping a data sync when your tracker disconnects.</p>
<p>This is incredibly useful for presence detection scenarios. Is your smart lock in range? Is your fitness tracker still connected? Is the user's phone nearby? Now you can know, with hardware-level certainty, and you can react to changes in presence without constantly polling or maintaining complex state machines in your app code.</p>
<p>Here's a practical example of how you might use this in a smart home app:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> presenceCallback = <span class="hljs-keyword">object</span> : ScanCallback() {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onScanResult</span><span class="hljs-params">(callbackType: <span class="hljs-type">Int</span>, result: <span class="hljs-type">ScanResult</span>)</span></span> {
        <span class="hljs-keyword">when</span> (callbackType) {
            ScanSettings.CALLBACK_TYPE_FIRST_MATCH -&gt; {
                <span class="hljs-comment">// User's phone detected - they're home!</span>
                Log.d(<span class="hljs-string">"SmartHome"</span>, <span class="hljs-string">"Welcome home! Unlocking door and turning on lights."</span>)
                unlockFrontDoor()
                turnOnLights()
                adjustThermostat(COMFORTABLE_TEMP)
            }
            ScanSettings.CALLBACK_TYPE_MATCH_LOST -&gt; {
                <span class="hljs-comment">// User's phone is gone - they left!</span>
                Log.d(<span class="hljs-string">"SmartHome"</span>, <span class="hljs-string">"Goodbye! Locking door and entering away mode."</span>)
                lockFrontDoor()
                turnOffLights()
                adjustThermostat(ENERGY_SAVING_TEMP)
                armSecuritySystem()
            }
        }
    }

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onScanFailed</span><span class="hljs-params">(errorCode: <span class="hljs-type">Int</span>)</span></span> {
        Log.e(<span class="hljs-string">"SmartHome"</span>, <span class="hljs-string">"Presence detection failed: <span class="hljs-variable">$errorCode</span>"</span>)
    }
}
</code></pre>
<p>One important consideration: <code>FIRST_MATCH</code> and <code>MATCH_LOST</code> are mutually exclusive with <code>CALLBACK_TYPE_ALL_MATCHES</code>. If you combine them with <code>ALL_MATCHES</code>, the behavior becomes undefined and varies by device. Stick to either <code>ALL_MATCHES</code> for continuous reporting, or <code>FIRST_MATCH</code>/<code>MATCH_LOST</code> for presence detection – don't try to use both at once.</p>
<p>Also, be aware that presence detection works best when combined with hardware filtering. If you're scanning for all devices without filters, the controller has to track the presence state of every single BLE device in range, which can overwhelm its internal tracking tables. Always use <code>ScanFilter</code> to narrow down which devices you care about when using presence detection.</p>
<p>By combining these advanced techniques – hardware filtering, batch scanning, and presence detection – you can build incredibly sophisticated and power-efficient Bluetooth applications. You're not just a developer anymore. You're a Bluetooth wizard, wielding the power to create apps that are aware of their surroundings, responsive to changes, and respectful of battery life.</p>
<p>Now, let's see where we can apply these magical powers in the real world.</p>
<h2 id="heading-real-world-use-cases-where-the-bluetooth-hits-the-road">Real-World Use Cases: Where the Bluetooth Hits the Road</h2>
<p>Okay, we've learned a ton of cool new tricks. We're basically Bluetooth black belts at this point. But what's the use of all this power if we don't use it for good (or at least for a cool app)? Let's explore some real-world scenarios where the new features in AOSP 16 can turn a good app into a great one.</p>
<h3 id="heading-1-the-find-my-everything-app">1. The "Find My Everything" App</h3>
<p>We've all been there. You're late for work, and your keys have decided to play a game of hide-and-seek in another dimension. This is the classic use case for a BLE tracker.</p>
<ul>
<li><p><strong>The Old Way:</strong> Your app would be constantly doing active scans, draining your battery while you frantically search. It would connect to every tracker in your house just to see if it's the right one.</p>
</li>
<li><p><strong>The AOSP 16 Way:</strong> Your app runs a passive scan in the background with a hardware filter for your tracker's specific Service UUID. The battery impact is minimal. When you open the app to find your keys, it already knows they're in the house because it's been listening silently. You hit the "Find" button, the app connects, and your keys start screaming from inside the couch cushions. And if the connection fails? Bond loss reason tells you if the tracker's battery died, so you're not looking for a dead device.</p>
</li>
</ul>
<h3 id="heading-2-the-smart-supermarket">2. The Smart Supermarket</h3>
<p>Imagine an app that gives you coupons for products as you walk past them in the store. This is the dream of proximity marketing, a dream that has been historically thwarted by, you guessed it, battery drain.</p>
<ul>
<li><p><strong>The Old Way:</strong> The app would need to constantly scan for beacons, turning the user's phone into a hot potato and a dead battery by the time they reach the checkout line.</p>
</li>
<li><p><strong>The AOSP 16 Way:</strong> The supermarket places BLE beacons in each aisle. Your app uses a passive, batched scan. It wakes up every minute or so, gets a list of all the beacons it has seen, and then goes back to sleep. When it sees you've been loitering in the cookie aisle for five minutes (it knows, it always knows), it uses the Service UUID from the advertisement to identify the "Cookie Aisle Beacon" and sends you a coupon for Oreos. It's targeted, it's efficient, and it doesn't kill your battery before you can pay.</p>
</li>
</ul>
<h3 id="heading-3-the-overly-attached-smart-home">3. The Overly-Attached Smart Home</h3>
<p>Your smart home should be, well, smart. It should know when you're home and when you've left. It should lock the door behind you and turn on the lights when you arrive.</p>
<ul>
<li><p><strong>The Old Way:</strong> You'd have to rely on GPS (a notorious battery hog) or Wi-Fi connections, which can be unreliable. BLE was an option, but constant scanning was a problem.</p>
</li>
<li><p><strong>The AOSP 16 Way:</strong> Your phone is the key. Your smart hub (acting as a central device) runs a continuous, low-power passive scan. When it sees your phone's BLE advertisement, it knows you're home. But what if you just walk by the house? This is where the OnFound/OnLost feature comes in. The hub can be configured to only trigger the "Welcome Home" sequence after it has seen your device consistently for a minute (OnFound), and to trigger the "Goodbye" sequence only after it hasn't seen you for five minutes (OnLost). It's a smarter, more reliable presence detection system that finally makes the smart home feel... smart.</p>
</li>
</ul>
<h3 id="heading-4-the-corporate-asset-tracker">4. The Corporate Asset Tracker</h3>
<p>In a large hospital or warehouse, keeping track of expensive, mobile equipment (like IV pumps or forklifts) is a huge challenge. BLE tags are the solution.</p>
<ul>
<li><p><strong>The Old Way:</strong> Employees would have to walk around with a tablet, doing active scans to take inventory. It's slow, manual, and inefficient.</p>
</li>
<li><p><strong>The AOSP 16 Way:</strong> A network of fixed BLE gateways is installed throughout the building. Each gateway is a simple device (like a Raspberry Pi) running a continuous passive scan. They collect all the advertisement data from the asset tags and send it to a central server. The server can now see, in real-time, that IV Pump #34 is in Room 201, and Forklift #3 is currently in the loading bay. No manual scanning required. It's a low-cost, low-power, real-time location system, all thanks to the efficiency of passive scanning.</p>
</li>
</ul>
<p>These are just a few examples. From fitness trackers to industrial sensors, the new Bluetooth features in AOSP 16 open up a world of possibilities for building apps that are not only powerful but also polite to your user's battery. Now, let's talk about how to make sure our shiny new app works on all devices, not just the new ones.</p>
<h2 id="heading-api-version-checking-how-to-not-crash-your-app">API Version Checking: How to Not Crash Your App</h2>
<p>So, you've built a beautiful, battery-sipping app using all the new hotness from AOSP 16's Q4 release. You're ready to ship it, become a millionaire, and retire to a private island. But then, a bug report comes in. Your app is crashing on a brand new Android 16 device. What gives?!</p>
<p>Welcome, my friend, to the wonderful world of API version checking. With Android's new release schedule, this has become more important (and slightly more complicated) than ever.</p>
<h3 id="heading-the-problem-a-tale-of-two-android-16s">The Problem: A Tale of Two Android 16s</h3>
<p>As we discussed, 2025 gave us two Android 16 releases:</p>
<ul>
<li><p><strong>The Q2 Release:</strong> The main "Baklava" release. Let's call this API level 36.0.</p>
</li>
<li><p><strong>The Q4 Release:</strong> The minor, feature-drop release. This is where our new Bluetooth toys live. Let's call this API level 36.1.</p>
</li>
</ul>
<p>Our new passive scanning API, setScanType(), only exists on 36.1 and later. If you try to call it on a device that's running the initial Q2 release (36.0), your app will crash with a NoSuchMethodError. It's the digital equivalent of asking for a menu item that was only added last night. The chef (your app) just gets confused and has a meltdown.</p>
<h3 id="heading-the-old-guard-sdkint">The Old Guard: SDK_INT</h3>
<p>For years, our trusty friend for checking API levels has been Build.VERSION.SDK_INT. It's simple and effective.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">if</span> (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.S) {
    <span class="hljs-comment">// Use an API from Android 12 (S) or higher</span>
}
</code></pre>
<p>But SDK_INT only knows about major releases. For both Android 16 Q2 and Q4, SDK_INT will just report 36. It has no idea about the minor version. It's like asking someone their age, and they just say "thirties." Not very specific.</p>
<h3 id="heading-the-new-hotness-sdkintfull">The New Hotness: SDK_INT_FULL</h3>
<p>To solve this, the Android team has given us a new, more precise tool: <code>Build.VERSION.SDK_INT_FULL</code>. This constant knows about both the major and minor version numbers. And to go with it, we have a new set of version codes: <code>Build.VERSION_CODES_FULL</code>.</p>
<p>So, to safely call our new passive scanning API, we need to do a more specific check:</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// Let's build our ScanSettings</span>
<span class="hljs-keyword">val</span> scanSettingsBuilder = ScanSettings.Builder()
    .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)

<span class="hljs-comment">// Now, let's check if we can go passive</span>
<span class="hljs-keyword">if</span> (Build.VERSION.SDK_INT_FULL &gt;= Build.VERSION_CODES_FULL.BAKLAVA_1) {
    Log.d(<span class="hljs-string">"ApiCheck"</span>, <span class="hljs-string">"This device is cool. Going passive."</span>)
    <span class="hljs-comment">// This is the new API from the Q4 release (36.1)</span>
    scanSettingsBuilder.setScanType(ScanSettings.SCAN_TYPE_PASSIVE)
} <span class="hljs-keyword">else</span> {
    Log.d(<span class="hljs-string">"ApiCheck"</span>, <span class="hljs-string">"This device is old school. Sticking to active scanning."</span>)
    <span class="hljs-comment">// Fallback for devices that don't have the new API</span>
    <span class="hljs-comment">// We don't need to do anything here, as active is the default</span>
}

<span class="hljs-keyword">val</span> scanSettings = scanSettingsBuilder.build()
</code></pre>
<h3 id="heading-graceful-degradation-the-art-of-falling-with-style">Graceful Degradation: The Art of Falling with Style</h3>
<p>This brings us to a crucial concept: graceful degradation. It means your app should still work on older devices, even if it can't use the latest and greatest features. It should fall back gracefully.</p>
<p>In our example above, if the setScanType method isn't available, we just... don't call it. The app will default to a normal, active scan. It won't be as battery-efficient, but it will still work. The user on the older device gets a functional app, and the user on the newer device gets a more optimized experience. Everybody wins.</p>
<p>Here's a table to help you remember when to use which check:</p>
<table><tbody><tr><td><p><strong>If you're using an API from...</strong></p></td><td><p><strong>Use this check...</strong></p></td></tr><tr><td><p>A major Android release (for example, Android 16 Q2)</p></td><td><p>if (SDK_INT &gt;= VERSION_CODES.BAKLAVA)</p></td></tr><tr><td><p>A minor, feature-drop release (for example, Android 16 Q4)</p></td><td><p>if (SDK_INT_FULL &gt;= VERSION_CODES_FULL.BAKLAVA_1)</p></td></tr></tbody></table>

<p>Mastering this new API checking is non-negotiable. It's the key to writing modern Android apps that are both innovative and stable. Now that we know how to build a robust app, let's talk about how to fix it when it inevitably breaks.</p>
<h2 id="heading-testing-and-debugging-the-fun-part-said-no-one-ever">Testing and Debugging: The Fun Part (Said No One Ever)</h2>
<p>There are two universal truths in software development:</p>
<ul>
<li><p>It works on my machine, and</p>
</li>
<li><p>It will break in the most spectacular way possible during a live demo.</p>
</li>
</ul>
<p>Bluetooth development, in particular, seems to delight in this second truth. It's a fickle, invisible force that seems to have a personal vendetta against developers.</p>
<p>So, how do we fight back? With a solid testing and debugging strategy. It's not glamorous, but it's the only way to stay sane.</p>
<h3 id="heading-the-emulator-a-land-of-make-believe">The Emulator: A Land of Make-Believe</h3>
<p>Android Studio's emulator is a fantastic tool. It's fast, it's convenient, and it can simulate all sorts of devices. And for Bluetooth? It can... sort of help. The emulator does have virtual Bluetooth support. You can enable it, and your app will think it has a Bluetooth adapter. It's great for testing your UI and making sure your app doesn't crash when it tries to get the BluetoothLeScanner.</p>
<p>But here's the catch: it's not real. The emulator can't actually interact with the radio waves in your room. You can't use it to find your real-life BLE headphones. For that, you need to venture into the real world.</p>
<h3 id="heading-the-real-world-where-the-bugs-live">The Real World: Where the Bugs Live</h3>
<p>There is no substitute for testing on real, physical devices. Every phone manufacturer has its own special flavor of Bluetooth stack, its own quirky antenna design, and its own unique way of making your life difficult. A scan that works perfectly on a Google Pixel might fail miserably on another brand. The only way to know is to test.</p>
<p>Your testing arsenal should include:</p>
<ul>
<li><p><strong>A variety of phones:</strong> Different brands, different Android versions. The more, the better.</p>
</li>
<li><p><strong>A variety of BLE peripherals:</strong> Don't just test with one type of device. Get a few different beacons, sensors, or wearables. You'll be amazed at how differently they behave.</p>
</li>
</ul>
<h3 id="heading-common-errors-the-usual-suspects">Common Errors: The Usual Suspects</h3>
<p>When your scan inevitably fails, it will give you an error code. Here are a few of the most common culprits:</p>
<table><tbody><tr><td><p><strong>Error Code</strong></p></td><td><p><strong>The Problem</strong></p></td><td><p><strong>How to Fix It</strong></p></td></tr><tr><td><p>SCAN_FAILED_ALREADY_STARTED</p></td><td><p>You tried to start a scan that was already running.</p></td><td><p>You got too excited. Make sure you're not calling startScan() multiple times without calling stopScan() in between.</p></td></tr><tr><td><p>SCAN_FAILED_APPLICATION_REGISTRATION_FAILED</p></td><td><p>Something is fundamentally wrong with your app's setup.</p></td><td><p>This is a vague and unhelpful error. It usually means you have a problem with your permissions or the system is just having a bad day. Try restarting Bluetooth.</p></td></tr><tr><td><p>SCAN_FAILED_INTERNAL_ERROR</p></td><td><p>The Bluetooth stack had a panic attack.</p></td><td><p>This is the classic "it's not you, it's me" error. It's an internal issue with the device's Bluetooth controller. There's not much you can do except try again later.</p></td></tr><tr><td><p>SCAN_FAILED_FEATURE_UNSUPPORTED</p></td><td><p>You tried to use a feature the hardware doesn't support.</p></td><td><p>You might be trying to use batch scanning on a device that doesn't support it. Use your API version checks!</p></td></tr></tbody></table>

<h3 id="heading-debugging-tools-your-ghost-hunting-kit">Debugging Tools: Your Ghost-Hunting Kit</h3>
<p>When things go wrong, you need the right tools to see what's happening in the invisible world of Bluetooth.</p>
<ul>
<li><p><strong>logcat:</strong> This is your best friend. Be generous with your log statements. Log when you start a scan, when you stop a scan, when you find a device, and when a scan fails. Create a filter for your app's tag so you can see the signal through the noise.</p>
</li>
<li><p><strong>Android's Bluetooth HCI Snoop Log:</strong> This is the holy grail of Bluetooth debugging. It's a developer option that records every single Bluetooth packet that goes in or out of your device. It's incredibly detailed and can be overwhelming, but it's the ultimate source of truth. You can open the generated log file in a tool like Wireshark to see the raw, unfiltered conversation between your phone and the BLE device. It's like having a wiretap on the radio waves.</p>
</li>
<li><p><strong>nRF Connect for Mobile:</strong> This is a free app from Nordic Semiconductor, and it's an essential tool for any BLE developer. It lets you scan for devices, see their advertising data, connect to them, and explore their GATT services. If your app can't find a device, the first thing you should do is see if nRF Connect can. If it can't, the problem is likely with the peripheral, not your app.</p>
</li>
</ul>
<p>Testing and debugging Bluetooth is a marathon, not a sprint. It requires patience, a methodical approach, and a healthy dose of self-deprecating humor. But with the right tools and techniques, you can tame the beast.</p>
<p>Now, let's talk about how to make sure our well-behaved app is also a good citizen when it comes to performance.</p>
<h2 id="heading-performance-and-best-practices-how-to-be-a-good-bluetooth-citizen">Performance and Best Practices: How to Be a Good Bluetooth Citizen</h2>
<p>Writing code that works is one thing. Writing code that works well, is efficient, and doesn't make your users want to throw their phone against a wall is another thing entirely. When it comes to Bluetooth, being a good citizen is all about one thing: battery, battery, battery.</p>
<p>The Bluetooth radio is a powerful piece of hardware, but it's also a thirsty one. Every moment it's active, it's sipping power. Your job is to make sure it's only sipping when absolutely necessary. Here are the golden rules of being a good Bluetooth citizen.</p>
<h3 id="heading-1-dont-scan-if-you-dont-have-to">1. Don't Scan If You Don't Have To</h3>
<p>This sounds obvious, but it's the most common mistake. Before you even think about starting a scan, ask yourself: "Do I really need to do this right now?" If the user is not on the screen that needs scan results, don't scan. If the app is in the background, be extra critical. Background scanning is a huge drain on battery and is heavily restricted by Android for that very reason.</p>
<h3 id="heading-2-stop-your-scan">2. Stop Your Scan!</h3>
<p>I'm going to say it again because it's that important: always stop your scan when you're done. A scan that's left running is like a leaky faucet for your battery. It will drain and drain until there's nothing left. The best practice is to tie your scan lifecycle to your UI lifecycle.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onPause</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">super</span>.onPause()
    <span class="hljs-comment">// The user can't see the screen, so they don't need the results.</span>
    stopBleScan()
}

<span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onResume</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">super</span>.onResume()
    <span class="hljs-comment">// The user is back on the screen, let's start scanning again.</span>
    startBleScan()
}
</code></pre>
<p>If you find the device you're looking for, stop the scan immediately. There's no need to keep looking.</p>
<h3 id="heading-3-choose-the-right-scan-mode">3. Choose the Right Scan Mode</h3>
<p>ScanSettings gives you a few different modes. Choose wisely.</p>
<ul>
<li><p><strong>SCAN_MODE_LOW_POWER:</strong> This is your default, everyday mode. It scans in intervals, balancing discovery speed and battery life. Use this for most foreground scanning.</p>
</li>
<li><p><strong>SCAN_MODE_BALANCED:</strong> A middle ground. It scans more frequently than low power mode.</p>
</li>
<li><p><strong>SCAN_MODE_LOW_LATENCY:</strong> This is the "I need to find it NOW" mode. It scans continuously. This will find devices the fastest, but it will also drain your battery the fastest. Only use this for short, critical operations.</p>
</li>
<li><p><strong>SCAN_MODE_OPPORTUNISTIC:</strong> This is the ultimate passive mode. Your app doesn't trigger a scan at all. It just gets results if another app happens to be scanning. It uses zero extra battery, but you have no guarantee of getting results. Use this for non-critical background updates.</p>
</li>
</ul>
<p>And of course, if you're on AOSP 16 QPR2 or later, use setScanType(SCAN_TYPE_PASSIVE) whenever you don't need the scan response data. It's the new king of power efficiency.</p>
<h3 id="heading-4-use-hardware-filtering-and-batching">4. Use Hardware Filtering and Batching</h3>
<p>We covered this in the advanced section, but it's a best practice that's worth repeating. If you're looking for a specific device, use a ScanFilter. If you're doing a long-running scan, use setReportDelay() to batch your results. These two techniques offload the work to the power-efficient Bluetooth controller and let your app's code sleep, which is the number one way to save battery.</p>
<h3 id="heading-5-be-mindful-of-memory">5. Be Mindful of Memory</h3>
<p>Every ScanResult object that your app receives takes up memory. If you're in a crowded area with hundreds of BLE devices, and you're not using filters, your app can quickly get overwhelmed and run out of memory. This is another reason why filtering is so important. Only get the results you actually care about.</p>
<p>By following these rules, you can build a Bluetooth app that is not only powerful and feature-rich but also respectful of your user's device. You'll be a true Bluetooth sensei. Now, let's wrap things up and look to the future.</p>
<h2 id="heading-conclusion-the-future-is-passive-and-thats-okay">Conclusion: The Future is Passive (and That's Okay)</h2>
<p>We've been on quite a journey, haven't we? We've traveled back in time to the dark ages of Classic Bluetooth, witnessed the renaissance of BLE, and emerged into the brave new world of AOSP 16. We've learned to be silent ninjas with passive scanning, played detective with bond loss reasons, and mastered the art of speed dating with service UUIDs from advertisements.</p>
<p>If there's one big takeaway from all of this, it's that the future of Bluetooth on Android is smarter, more efficient, and a whole lot less frustrating. The Android team is clearly listening to the pain points of developers and giving us the tools we need to build better, more battery-friendly apps. The introduction of passive scanning isn't just a new feature – it's a change in philosophy. It's an acknowledgment that sometimes, the best way to communicate is to just listen.</p>
<p>As developers, these new tools empower us to move beyond the simple "connect and stream" use cases. We can now build sophisticated, context-aware applications that are constantly aware of their surroundings without turning our users' phones into expensive paperweights. The dream of a truly smart, seamlessly connected world is a little bit closer, and it's going to be built on the back of these power-efficient technologies.</p>
<p>So, what's next? The world of Bluetooth is always evolving. We have Bluetooth 5.4 with Auracast, mesh networking, and even more precise location-finding on the horizon. The one thing we can be sure of is that the tools will continue to get better, and the challenges will continue to get more interesting.</p>
<p>For now, take a moment to appreciate the progress we've made. The next time you start a Bluetooth scan and it just works, take a moment to thank the hardworking engineers who made it possible. And the next time your app's battery graph is a beautiful, flat line instead of a terrifying ski slope, give a little nod to the power of passive scanning.</p>
<p>The Bluetooth beast may never be fully tamed, but with AOSP 16, we've been given a much stronger leash. Now go forth and build amazing things. And for the love of all that is holy, remember to stop your scan.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
