<?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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dinesh Kumar on Medium]]></title>
        <description><![CDATA[Stories by Dinesh Kumar on Medium]]></description>
        <link>https://medium.com/@dine9936?source=rss-c9ff6785d3e4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YhLj2cFrjFeEZ3NV.jpg</url>
            <title>Stories by Dinesh Kumar on Medium</title>
            <link>https://medium.com/@dine9936?source=rss-c9ff6785d3e4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 16:47:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dine9936/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Multiple BLE Connections to the Same Device — Problems, Solutions & My Approach]]></title>
            <link>https://dine9936.medium.com/multiple-ble-connections-to-the-same-device-problems-solutions-my-approach-3f0896dc65e9?source=rss-c9ff6785d3e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f0896dc65e9</guid>
            <category><![CDATA[bluetooth-low-energy]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[hardware]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Dinesh Kumar]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 23:36:56 GMT</pubDate>
            <atom:updated>2026-10-11T23:36:56.476Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XaK2w8W0VqfqlKtg2vvVkw.png" /></figure><p>What Happens When an Android App Connects to the Same BLE Device Multiple Times?</p><p>Understanding duplicate GATT connections, connection ownership, concurrency, and how I’m addressing these challenges in RamaBleManager.</p><p>While building</p><pre>val connection1 = bleClient.connect(device)<br>val connection2 = bleClient.connect(device)<br>val connection3 = bleClient.connect(device)</pre><p>If the library does not manage existing connections, each request may create another BluetoothGatt client.</p><p>Conceptually:</p><pre>Android Application<br>                     |<br>          +----------+----------+<br>          |          |          |<br>       Connect 1  Connect 2  Connect 3<br>          |          |          |<br>        GATT 1     GATT 2     GATT 3<br>          |          |          |<br>          +----------+----------+<br>                     |<br>              Android BLE Stack<br>                     |<br>               BLE Peripheral</pre><p>An important distinction: <strong>three GATT clients do not necessarily mean three physical Bluetooth connections.</strong></p><p>Android may manage multiple GATT clients over the same physical BLE link.</p><p>However, each client has its own callbacks and lifecycle, and the application must manage them correctly.</p><h3>2. Why can this become a serious problem?</h3><h3>Problem A: Conflicting GATT operations</h3><p>Suppose two independent connections send commands to the same IoT device.</p><p>Connection A sends a command to read data.</p><p>Connection B sends a command to update a configuration.</p><p>Even if both individual operations succeed, the peripheral’s application protocol might not support concurrent command processing.</p><p>The result could be unexpected command ordering, incorrect response matching, or duplicate execution.</p><h3>Problem B: Incorrect connection state</h3><p>Imagine:</p><pre>GATT 1 → CONNECTED<br>GATT 2 → CONNECTED<br>GATT 1 → DISCONNECTED</pre><p>If the application maintains only one shared connection-state variable, it may report that the device is disconnected even though another GATT client remains connected.</p><h3>Problem C: Resource leaks</h3><p>Every additional BluetoothGatt client requires lifecycle management.</p><p>If the library loses track of one of them, it may never call close().</p><p>Repeated connection attempts can gradually consume Bluetooth resources and make future connections unreliable.</p><h3>Problem D: Race conditions</h3><p>BLE connections are asynchronous.</p><p>Consider:</p><pre>T1 → Connect request A<br>T2 → Connect request B<br>T3 → Request B succeeds<br>T4 → Request A completes later<br>T5 → Old callback overwrites current state</pre><p>Without session ownership, callbacks may modify the wrong connection state.</p><p>These issues are particularly important in IoT applications where reliability matters more than simply establishing a connection.</p><h3>3. What are the possible solutions?</h3><p>There isn’t one universal policy. Different libraries and applications make different architectural choices.</p><p>ApproachBehaviorAdvantageTrade-offReject duplicateReturn an error if the device is already connecting or connectedSimple and predictableCaller must handle the errorReuse existing connectionReturn the existing managed sessionConvenient for shared accessRequires ownership managementAwait existing connectionConcurrent callers wait for one connection attemptAvoids duplicate workCancellation and waiter behavior become more complexReplace existing connectionClose old session and create a new oneUseful for explicit reconnectCan interrupt active operationsReference-counted sharingShare one connection among multiple ownersSupports complex applicationsMore complex lifecycle management</p><p>These are design choices, not interchangeable implementations.</p><p>For example, <strong>Nordic’s Android BLE Library</strong> uses a BleManager instance to manage one peripheral, while allowing multiple managers for different devices. <a href="https://github.com/nordicsemi/Android-BLE-Library/blob/main/USAGE.md?utm_source=chatgpt.com">GitHub</a></p><h3>4. My approach in RamaBleManager</h3><p>For the current version of RamaBleManager, I’m choosing:</p><p><strong>One managed connection per device, with explicit duplicate rejection.</strong></p><p>The intended behavior is:</p><pre>connect(Device A) → Allowed</pre><pre>connect(Device A) while connecting<br>                  → AlreadyConnecting</pre><pre>connect(Device A) while connected<br>                  → AlreadyConnected</pre><pre>connect(Device B) → Allowed</pre><pre>disconnect(Device A)<br>                  → Cleanup</pre><pre>connect(Device A) → Allowed again</pre><p>Why this approach?</p><p>Because it offers predictable ownership without introducing reference counting or shared-session cancellation rules too early.</p><p>My implementation uses three main ideas.</p><p><strong>1. Atomic device reservation</strong></p><p>Before calling Android’s connectGatt(), the connector reserves the device in an internal registry.</p><p>Two concurrent requests cannot both reserve the same device.</p><p><strong>2. Typed connection errors</strong></p><p>Instead of returning generic strings, the library uses structured errors:</p><pre>sealed class BleError {</pre><pre>    data class AlreadyConnecting(<br>        val deviceAddress: String<br>    ) : BleError()</pre><pre>    data class AlreadyConnected(<br>        val deviceAddress: String<br>    ) : BleError()<br>}</pre><p>This snippet illustrates the error contract; the actual library retains its existing BleError hierarchy.</p><p>The application can handle errors using Kotlin’s when expression without parsing exception messages.</p><p><strong>3. Session-aware cleanup</strong></p><p>Each reservation has a unique session token.</p><p>When a connection ends, only the session that owns the reservation can remove it.</p><p>This protects newer connection attempts from stale cleanup callbacks belonging to older sessions.</p><h3>5. Why not simply use a Mutex?</h3><p>A Mutex can prevent two coroutines from modifying a connection registry simultaneously.</p><p>But that alone is not enough.</p><p>The library must also know which session owns the reservation, when the reservation should be released, and whether a callback belongs to an obsolete session.</p><p>A more complete design combines:</p><pre>Atomic Reservation<br>        +<br>Session Ownership<br>        +<br>Connection State Tracking<br>        +<br>GATT Resource Cleanup<br>        =<br>Predictable Connection Management</pre><h3>6. How I’m testing it</h3><p>I’ve also been working on a connection-testing screen in the RamaBleManager sample application.</p><p>The idea is simple: scan for a device, select it, enter the number of simultaneous connection attempts, and execute them.</p><p>For example, entering 5 launches five concurrent requests to the same peripheral.</p><p>With duplicate protection operating correctly, the expected outcome is:</p><pre>Attempt 1 → CONNECTING<br>Attempt 2 → ALREADY_CONNECTING<br>Attempt 3 → ALREADY_CONNECTING<br>Attempt 4 → ALREADY_CONNECTING<br>Attempt 5 → ALREADY_CONNECTING</pre><pre>Attempt 1 → CONNECTED</pre><p>The actual ordering depends on scheduling. Only one request should initiate a new GATT session.</p><p>This is useful for verifying concurrent behavior that might be missed during ordinary manual testing.</p><h3>7. Lessons from building a BLE library</h3><p>One thing I’ve learned while developing RamaBleManager is that <strong>a successful BLE connection is only the beginning of reliable communication</strong>.</p><p>Connection management also requires careful consideration of:</p><ul><li>Concurrency and state transitions</li><li>Connection ownership</li><li>Coroutine cancellation</li><li>Unexpected disconnections</li><li>GATT resource cleanup</li><li>Stale asynchronous callbacks</li></ul><p>I’m continuing to improve RamaBleManager one connection-lifecycle problem at a time.</p><p><strong>GitHub:</strong> <a href="https://github.com/dinesh9936/rama-ble-manager-library">https://github.com/dinesh9936/rama-ble-manager-library</a></p><p>I’d be interested to hear how other Android and IoT developers manage repeated connection requests.</p><p>Do you prefer rejecting duplicate requests, reusing the existing connection, or allowing callers to await the same connection attempt?</p><p>#AndroidDevelopment #BluetoothLowEnergy #BLE #Kotlin #AndroidIoT #Coroutines #OpenSource #SoftwareArchitecture</p><p><strong>Publishing note:</strong> The article describes your implementation approach and intended behavior. The duplicate-protection code was proposed in our previous discussion; I have not independently verified that the final implementation has been committed, compiled, or passed concurrent-connection tests. Once those checks pass, you can change “I’m choosing” to “I’ve implemented.”</p><h3>Suggested LinkedIn caption</h3><p><strong>Can calling </strong><strong>connect() multiple times to the same BLE device cause problems? 🔵</strong></p><p>While developing RamaBleManager, I explored how duplicate Android GATT connections can affect connection state, resource management, and communication reliability.</p><p>I compared several strategies: rejecting duplicates, reusing an active connection, waiting for an existing attempt, and reference-counted sharing.</p><p>For RamaBleManager, I chose a simpler starting point: <strong>atomic device reservation, one managed session per device, typed errors, and session-aware cleanup</strong>.</p><p>The infographic explains the problem and illustrates the proposed connection flow.</p><p>Read the full article above, and explore the project:</p><p>🔗 <a href="https://github.com/dinesh9936/rama-ble-manager-library">RamaBleManager on GitHub</a></p><p><strong>Question for Android developers:</strong> Would you reject duplicate connection requests or return the existing connection?</p><p>#AndroidDev #BluetoothLE #BLE #Kotlin #AndroidIoT #OpenSource</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f0896dc65e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Bluetooth Low Energy (BLE) Advertising and Scanning Work Internally on Android]]></title>
            <link>https://dine9936.medium.com/how-bluetooth-low-energy-ble-advertising-and-scanning-work-internally-on-android-1f122cacb3c1?source=rss-c9ff6785d3e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f122cacb3c1</guid>
            <dc:creator><![CDATA[Dinesh Kumar]]></dc:creator>
            <pubDate>Thu, 08 Oct 2026 01:29:30 GMT</pubDate>
            <atom:updated>2026-10-08T01:29:30.538Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Radio Signals to Android Scan Results — A Developer’s Guide</h3><p><strong>Topics:</strong> Android | Kotlin | Bluetooth Low Energy | BLE Advertising | GATT | Wireless Communication</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p5Ei2wuzWLKhfZ6DPCowKA.png" /></figure><p>Bluetooth Low Energy (BLE) is widely used in smartwatches, fitness bands, smart meters, medical devices, and IoT products.</p><p>As Android developers, we often write code like this:</p><pre>bluetoothLeScanner.startScan(scanCallback)</pre><p>A few seconds later, nearby Bluetooth devices start appearing in our application.</p><p>But have you ever wondered:</p><ul><li>How does a Bluetooth device announce its presence?</li><li>What information does it transmit through the air?</li><li>How frequently does it broadcast this information?</li><li>How does Android receive these signals?</li><li>Does scanning automatically establish a connection?</li><li>Why do some devices appear immediately while others take several seconds?</li><li>Why does Android sometimes report “Scanning too frequently”?</li></ul><p>Let’s understand the complete process, starting from the basics and gradually moving toward Android’s internal implementation.</p><h3>1. Understanding BLE Advertising Through a Real-Life Example</h3><p>Imagine you’re walking through a shopping mall.</p><p>Several shopkeepers are standing outside their shops and repeatedly announcing:</p><p>“Hello! My shop is called Smart Electronics. We sell mobile phones.”</p><p>You can hear these announcements without entering any shop or speaking to the shopkeeper.</p><p>This is similar to <strong>BLE advertising</strong>.</p><p>A Bluetooth device repeatedly broadcasts small packets of information into the surrounding area.</p><p>Your Android phone listens for these packets.</p><p>When it receives one, it can display the device in a list.</p><p>There are two important roles here.</p><p><strong>Advertiser:</strong> A device broadcasting information.</p><p>Examples:</p><ul><li>Smartwatch</li><li>Smart meter</li><li>Temperature sensor</li><li>Fitness tracker</li></ul><p><strong>Scanner:</strong> A device listening for advertising packets.</p><p>Examples:</p><ul><li>Android smartphone</li><li>BLE gateway</li><li>Laptop</li><li>Another BLE-capable device</li></ul><p>Consider this scenario:</p><pre>SMART METER<br>       (Advertiser)<br>            |<br>            |<br>       Radio signals<br>            |<br>            v<br>       ANDROID PHONE<br>         (Scanner)<br>            |<br>            v<br>       Your Android App</pre><p>The smart meter broadcasts its presence.</p><p>The Android phone receives the advertisement.</p><p>Your application displays the device.</p><p><strong>Important:</strong> At this stage, the Android phone doesn’t necessarily have a Bluetooth connection with the smart meter.</p><p>It is simply listening.</p><h3>2. What Exactly Is a BLE Advertisement?</h3><p>A BLE advertisement is a small wireless message transmitted by a Bluetooth device.</p><p>It can contain information that helps other devices discover or identify it.</p><p>For example, imagine a smart meter transmitting:</p><pre>Device Name   : Maxwell_Meter_001<br>Service UUID  : 6E400001-B5A3-F393-E0A9-E50E24DCCA9E<br>Manufacturer  : 0x004C<br>Battery       : 85% (custom manufacturer data)</pre><p>This is an illustrative payload. Actual fields depend on the device’s firmware.</p><p>The Bluetooth device does not necessarily transmit all these fields.</p><p>A manufacturer decides what information to include.</p><p>Common advertising information includes:</p><p>InformationPurposeDevice nameHuman-readable device identificationService UUIDIndicates supported Bluetooth servicesManufacturer dataCustom manufacturer-defined bytesService dataCustom data associated with a serviceFlagsIndicates capabilities and discoverabilityTX powerAdvertised transmission power information</p><p>One interesting fact:</p><p><strong>A device can advertise even when nobody is listening.</strong></p><p>Advertising is generally a broadcast mechanism. It doesn’t require an established connection.</p><p>The Bluetooth specification supports both legacy advertising and extended advertising.</p><p>Legacy advertising has a maximum advertisement-data payload of <strong>31 bytes</strong>, while Bluetooth 5 extended advertising supports larger payloads. <a href="https://www.bluetooth.com/bluetooth-le-primer/?utm_source=chatgpt.com">Bluetooth® Technology Website</a></p><p>That limited space is one reason BLE devices transmit small pieces of information rather than large amounts of data.</p><h3>3. How Does a BLE Device Send Information Through the Air?</h3><p>BLE operates in the <strong>2.4 GHz frequency band</strong>.</p><p>This is the same general frequency band used by technologies such as 2.4 GHz Wi-Fi.</p><p>BLE divides its radio spectrum into <strong>40 channels</strong>.</p><p>For traditional BLE communication:</p><ul><li>3 primary channels are used for advertising.</li><li>37 channels are used for connection-oriented data communication.</li></ul><p>The primary advertising channels are:</p><p>ChannelFrequencyChannel 372402 MHzChannel 382426 MHzChannel 392480 MHz</p><p>These channels are distributed across the 2.4 GHz band to help devices communicate in environments with other wireless signals. <a href="https://dev.ti.com/tirex/explore/content/simplelink_academy_for_cc23xx_8_40_01_00/_build_simplelink_academy_for_cc23xx_8_40_01_00/source/ble/cc2340rx_02_ble_scan_adv_basic.html?utm_source=chatgpt.com">TI Developer Zone</a></p><h3>What happens when a smart meter advertises?</h3><p>Suppose its advertising interval is 100 milliseconds.</p><p>A simplified representation is:</p><pre>Smart Meter<br>    |<br>    | Advertisement Event<br>    |<br>    +---- Channel 37 ----&gt; Advertising Packet<br>    |<br>    +---- Channel 38 ----&gt; Advertising Packet<br>    |<br>    +---- Channel 39 ----&gt; Advertising Packet<br>    |<br>    | Wait ~100 ms<br>    |<br>    +---- Channel 37 ----&gt; Advertising Packet<br>    |<br>    +---- Channel 38 ----&gt; Advertising Packet<br>    |<br>    +---- Channel 39 ----&gt; Advertising Packet</pre><p>Each advertising event can transmit packets on one, two, or all three primary advertising channels.</p><p>This improves the chance that a scanning device receives an advertisement.</p><p>The three channels aren’t used simultaneously; the radio transmits on them sequentially.</p><p>A scanner only needs to receive a suitable packet on one channel to discover the advertiser.</p><h3>4. What Is an Advertising Interval?</h3><p>The <strong>advertising interval</strong> controls how frequently a BLE device broadcasts advertising events.</p><p>For example:</p><pre>Advertising interval = 100 milliseconds</pre><p>This means the device schedules advertising events approximately every 100 milliseconds, with some additional timing variation.</p><p>Let’s visualize it:</p><pre>Time ------------------------------------------------&gt;</pre><pre>0 ms       100 ms      200 ms      300 ms<br> |           |           |           |<br> ADV         ADV         ADV         ADV</pre><p>In a common legacy advertising configuration, supported intervals range from approximately <strong>20 milliseconds to 10.24 seconds</strong>.</p><p>There is also a small random advertising delay, typically between 0 and 10 milliseconds, to help reduce repeated packet collisions. Some advertising procedures follow different timing rules. <a href="https://docs.silabs.com/bluetooth/10.0.0/bluetooth-le-fundamentals/04-link-layer?utm_source=chatgpt.com">docs.silabs.com</a></p><h3>Why not advertise every millisecond?</h3><p>Because radio transmission consumes energy.</p><p>Consider two devices.</p><p><strong>Device A:</strong></p><pre>Advertising interval: 100 ms</pre><p>It broadcasts approximately 10 advertising events per second.</p><p><strong>Device B:</strong></p><pre>Advertising interval: 1000 ms</pre><p>It broadcasts approximately one event per second.</p><p>Device A generally provides faster discovery opportunities but requires more radio activity.</p><p>Device B saves energy but may take longer to discover.</p><p>This is a fundamental BLE engineering trade-off:</p><p><strong>Faster discovery vs. lower power consumption.</strong></p><p>For battery-powered sensors, firmware developers often choose longer advertising intervals to conserve energy.</p><h3>5. How Does Android Receive BLE Advertisements?</h3><p>Now let’s move to the Android side.</p><p>When an application starts scanning, several components become involved.</p><pre>Android Application<br>        |<br>        v<br>BluetoothLeScanner<br>        |<br>        v<br>Android Bluetooth Framework<br>        |<br>        v<br>Bluetooth System Service<br>        |<br>        v<br>Bluetooth Controller / Firmware<br>        |<br>        v<br>Bluetooth Radio Hardware<br>        |<br>        |<br>   Receives RF Signals<br>        |<br>        v<br>Advertising Packets</pre><p>This diagram is simplified, but it shows the basic flow.</p><p>Your Kotlin application doesn’t directly read radio-frequency signals.</p><p>Instead, Android’s Bluetooth framework communicates with the Bluetooth controller, which handles low-level radio operations.</p><p>When a suitable advertisement is received, information travels back through the Bluetooth stack.</p><p>Eventually, Android invokes your application’s scan callback.</p><pre>override fun onScanResult(<br>    callbackType: Int,<br>    result: ScanResult<br>) {<br>    Log.d(<br>        &quot;BLE&quot;,<br>        &quot;Device found: ${result.device.address}&quot;<br>    )<br>}</pre><p>The callback contains information about the discovered advertisement.</p><h3>Does Android create a connection during scanning?</h3><p>No.</p><p>Scanning and connecting are different operations.</p><pre>SCAN<br>  |<br>  v<br>Discover device<br>  |<br>  v<br>Read advertising information<br>  |<br>  v<br>Decide whether to connect<br>  |<br>  v<br>CONNECT<br>  |<br>  v<br>Discover GATT services<br>  |<br>  v<br>Read / Write / Subscribe</pre><p>A BLE device doesn’t need to support connections for its advertisements to be useful.</p><p>For example, a BLE beacon may broadcast information continuously without accepting connections.</p><h3>6. What Information Does Android Receive During Scanning?</h3><p>Let’s understand the ScanResult object.</p><p>Android provides:</p><pre>override fun onScanResult(<br>    callbackType: Int,<br>    result: ScanResult<br>) {<br>    val device = result.device<br>    val scanRecord = result.scanRecord</pre><pre>    val address = device.address<br>    val name = scanRecord?.deviceName<br>    val rssi = result.rssi<br>    val serviceUuids = scanRecord?.serviceUuids</pre><pre>    Log.d(&quot;BLE&quot;, &quot;Address: $address&quot;)<br>    Log.d(&quot;BLE&quot;, &quot;Name: $name&quot;)<br>    Log.d(&quot;BLE&quot;, &quot;RSSI: $rssi&quot;)<br>    Log.d(&quot;BLE&quot;, &quot;Services: $serviceUuids&quot;)<br>}</pre><p>This assumes the application has the required Bluetooth permissions.</p><p>Let’s understand each field.</p><h3>Device address</h3><p>Example:</p><pre>F4:12:FA:3C:9D:01</pre><p>The Bluetooth address helps Android identify a device.</p><p>However, not every BLE device uses a permanent public address. Some devices use private addresses that change periodically for privacy.</p><p>Therefore, developers should not always assume that a BLE device’s address is permanent.</p><h3>Device name</h3><p>Example:</p><pre>Maxwell_Meter_001</pre><p>A device may advertise its name so applications can display it.</p><p>However, the name is optional.</p><p>A BLE device may be advertising correctly without transmitting any device name.</p><p>This is why some devices appear as:</p><pre>Unknown Device</pre><h3>RSSI</h3><p>RSSI stands for <strong>Received Signal Strength Indicator</strong>.</p><p>It indicates how strong the received Bluetooth radio signal is.</p><p>Example:</p><pre>RSSI = -45 dBm</pre><p>A simplified interpretation:</p><p>RSSIGeneral interpretation-40 dBmVery strong-60 dBmGood-75 dBmModerate-90 dBmWeak</p><p>These are illustrative values, not universal thresholds.</p><p>RSSI is affected by distance, walls, interference, antenna orientation, and the environment.</p><p><strong>RSSI is not a direct measurement of distance.</strong></p><p>For example, a device behind a wall might report a weaker signal than another device at a greater distance.</p><p>Also, RSSI is measured by the receiver. It is not normally a value that the peripheral explicitly broadcasts inside its advertising data.</p><h3>7. What Is a Scan Response?</h3><p>This is another important BLE concept.</p><p>Sometimes, a device cannot fit all its information inside the primary advertisement.</p><p>For example, it might want to advertise:</p><pre>Device Name<br>Service UUID<br>Manufacturer Data<br>Additional Information</pre><p>Since legacy advertisement payloads are limited, a device can provide additional information through a <strong>scan response</strong>.</p><p>This is where active scanning becomes useful.</p><p>Consider the following communication:</p><pre>BLE PERIPHERAL                   ANDROID PHONE<br>      |                               |<br>      | -------- Advertisement -----&gt; |<br>      |                               |<br>      | &lt;-------- Scan Request ------ |<br>      |                               |<br>      | -------- Scan Response -----&gt; |<br>      |                               |<br>      |                          Process data<br>      |                               |</pre><p>The sequence is:</p><ol><li>The peripheral transmits a scannable advertisement.</li><li>The Android Bluetooth controller receives it.</li><li>During active scanning, the controller may send a scan request.</li><li>The peripheral returns additional advertising information.</li><li>Android can provide the received information to the application.</li></ol><p>The peripheral must support the appropriate scannable advertising procedure for this exchange.</p><h3>Active scanning vs. passive scanning</h3><p><strong>Passive scanning:</strong> The scanner listens for advertisements but does not request additional information.</p><p><strong>Active scanning:</strong> The scanner can request additional information from scannable advertisers.</p><p>A simple analogy:</p><p>Passive scanning:</p><blockquote><em>Someone tells you their shop’s name, and you listen.</em></blockquote><p>Active scanning:</p><blockquote><em>Someone tells you their shop’s name, and you ask what products they sell.</em></blockquote><p>Android manages the low-level scan-request exchange. An ordinary application generally doesn’t manually construct these radio-level requests.</p><p>One important distinction: Android’s SCAN_MODE_LOW_POWER, SCAN_MODE_BALANCED, and SCAN_MODE_LOW_LATENCY settings are about scan duty and power behavior. They are not equivalent to directly selecting passive or active scanning.</p><h3>8. How Often Does Android Listen for Advertisements?</h3><p>Now we understand how often the peripheral broadcasts.</p><p>But what about the scanner?</p><p>A BLE scanner doesn’t necessarily listen continuously.</p><p>Its Bluetooth controller can alternate between listening and sleeping.</p><p>Two important concepts are:</p><p><strong>Scan interval:</strong> How frequently a scanning window begins.</p><p><strong>Scan window:</strong> How long the scanner listens during that interval.</p><p>Imagine this configuration:</p><pre>Scan Interval = 100 ms<br>Scan Window   = 50 ms</pre><p>A simplified timeline:</p><pre>Time -----------------------------------------&gt;</pre><pre>0        50       100      150      200 ms<br>|--------|--------|--------|--------|<br> LISTEN    SLEEP   LISTEN    SLEEP</pre><p>In this example, the scanner listens for approximately 50% of the time.</p><p>This percentage is called the <strong>scan duty cycle</strong>.</p><p>The formula is:</p><pre>Scan Duty Cycle = (Scan Window / Scan Interval) × 100</pre><p>For the example above:</p><pre>Scan Duty Cycle = (50 / 100) × 100 = 50%</pre><h3>Why does this matter?</h3><p>Imagine a BLE device advertising every 1000 ms.</p><p>If Android only listens during short scanning windows, it might miss several advertisements.</p><p>This is one reason devices don’t always appear immediately.</p><h3>How do Android scan modes affect this?</h3><p>Android provides three common scan modes:</p><p>ModeGeneral behaviorBattery consumptionLOW_POWERLess frequent listeningLowerBALANCEDBalance between discovery and powerMediumLOW_LATENCYMore aggressive scanningHigher</p><p>Actual scan intervals and windows are managed by Android and Bluetooth hardware. The public API doesn’t guarantee specific timing values for these modes.</p><p>For an application where the user explicitly requests nearby devices, LOW_LATENCY can provide faster discovery.</p><p>For longer-running discovery, lower-power scanning may be more appropriate.</p><h3>9. Let’s Implement BLE Scanning in Android Using Kotlin</h3><p>Now that we understand the concepts, let’s write some code.</p><p>First, ensure the application has the necessary permissions.</p><p>For Android 12 and later, BLE scanning generally requires:</p><pre>&lt;uses-permission<br>    android:name=&quot;android.permission.BLUETOOTH_SCAN&quot; /&gt;<br><br>&lt;uses-permission<br>    android:name=&quot;android.permission.BLUETOOTH_CONNECT&quot; /&gt;</pre><p>For older Android versions, location permissions may be required for BLE discovery. Android 12+ also requires these Bluetooth permissions to be requested at runtime.</p><p>The precise manifest configuration depends on your minimum SDK and whether your application uses scan results to determine physical location.</p><p>Now let’s implement a scanner.</p><pre>@SuppressLint(&quot;MissingPermission&quot;)<br>class SimpleBleScanner(<br>    private val bluetoothAdapter: BluetoothAdapter<br>) {</pre><pre>    private val scanner: BluetoothLeScanner?<br>        get() = bluetoothAdapter.bluetoothLeScanner</pre><pre>    private val scanCallback = object : ScanCallback() {</pre><pre>        override fun onScanResult(<br>            callbackType: Int,<br>            result: ScanResult<br>        ) {<br>            val name = result.scanRecord?.deviceName<br>            val address = result.device.address<br>            val rssi = result.rssi</pre><pre>            Log.d(<br>                &quot;BLE&quot;,<br>                &quot;Found: $name | $address | RSSI: $rssi&quot;<br>            )<br>        }</pre><pre>        override fun onScanFailed(errorCode: Int) {<br>            Log.e(<br>                &quot;BLE&quot;,<br>                &quot;Scanning failed: $errorCode&quot;<br>            )<br>        }<br>    }</pre><pre>    fun startScanning() {</pre><pre>        val settings = ScanSettings.Builder()<br>            .setScanMode(<br>                ScanSettings.SCAN_MODE_LOW_LATENCY<br>            )<br>            .build()</pre><pre>        scanner?.startScan(<br>            emptyList(),<br>            settings,<br>            scanCallback<br>        )<br>    }</pre><pre>    fun stopScanning() {<br>        scanner?.stopScan(scanCallback)<br>    }<br>}</pre><p>This is intentionally a simplified example. A production implementation should check Bluetooth availability, runtime permissions, active scan state, and errors before scanning.</p><h3>What happens after startScanning()?</h3><p>Let’s follow the execution:</p><pre>startScanning()<br>      |<br>      v<br>BluetoothLeScanner.startScan()<br>      |<br>      v<br>Android Bluetooth Framework<br>      |<br>      v<br>Bluetooth Controller<br>      |<br>      v<br>Listen for advertising packets<br>      |<br>      v<br>Receive matching advertisement<br>      |<br>      v<br>ScanCallback.onScanResult()<br>      |<br>      v<br>Display device in application</pre><p>Android also allows applications to filter advertisements by properties such as service UUID, device address, and device name.</p><p>Filtering is useful when an application is interested in specific peripherals rather than every nearby BLE device.</p><h3>10. Why Do Some BLE Devices Appear Late or Not at All?</h3><p>This is one of the most common problems developers encounter.</p><p>Suppose you’re building an Android smart-meter application.</p><p>The meter is powered on, but your application cannot discover it.</p><p>There could be several reasons.</p><p><strong>Reason 1: Long advertising interval</strong></p><p>The meter might advertise only once per second or even less frequently.</p><p><strong>Reason 2: Low-power scanning</strong></p><p>Android may not be listening continuously.</p><p><strong>Reason 3: Radio interference</strong></p><p>Wi-Fi, other Bluetooth devices, and physical obstacles can interfere with reception.</p><p><strong>Reason 4: Device not advertising</strong></p><p>The peripheral might stop advertising after connecting to another device.</p><p><strong>Reason 5: Advertising filters</strong></p><p>Your application might filter by a service UUID that the device doesn’t include in its advertisement.</p><p><strong>Reason 6: Android permissions</strong></p><p>Missing Bluetooth permissions or relevant location settings can prevent discovery.</p><p><strong>Reason 7: Duplicate filtering</strong></p><p>Your application may intentionally show each device only once, even though it receives multiple advertisements.</p><p>The main lesson:</p><p><strong>A missing scan result doesn’t necessarily mean the peripheral is disconnected, powered off, or malfunctioning.</strong></p><p>It simply means your application hasn’t received a matching scan result.</p><h3>11. Why Does Android Report “Scanning Too Frequently”?</h3><p>While developing my open-source Android BLE library, <strong>RamaBleManager</strong>, I encountered this Android Bluetooth log:</p><pre>GattService:<br>App &#39;com.rama.ramablemanager&#39; is scanning too frequently</pre><p>Let’s understand what happened.</p><p>Suppose an application repeatedly starts and stops scanning:</p><pre>0 seconds  -&gt; Start scan<br>2 seconds  -&gt; Stop scan<br>5 seconds  -&gt; Start scan<br>7 seconds  -&gt; Stop scan<br>10 seconds -&gt; Start scan<br>12 seconds -&gt; Stop scan<br>15 seconds -&gt; Start scan<br>17 seconds -&gt; Stop scan<br>20 seconds -&gt; Start scan<br>22 seconds -&gt; Stop scan<br>25 seconds -&gt; Start scan again</pre><p>Although every individual scan is valid, repeatedly starting new scan sessions can trigger Android’s scanning restrictions.</p><p>Android provides a scan failure code for this condition:</p><pre>ScanCallback.SCAN_FAILED_SCANNING_TOO_FREQUENTLY</pre><p>Its numeric value is:</p><pre>6</pre><p>The constant is publicly available starting with API level 33. <a href="https://developer.android.com/reference/android/bluetooth/le/ScanCallback?utm_source=chatgpt.com">Android Developers</a></p><p>In practice, developers often encounter throttling after approximately five scan starts in a 30-second period on certain Android implementations.</p><p>However, this should not be treated as a universal, guaranteed limit across every device and Android version.</p><p>Android may also silently suppress new scans rather than notifying the application through onScanFailed().</p><h3>How did I address it in RamaBleManager?</h3><p>I added a custom scan rate limiter.</p><p>The library tracks how many times scanning has been started within a rolling 30-second window.</p><p>For example:</p><pre>Maximum scan starts: 4<br>Time window: 30 seconds</pre><p>If a new scan request exceeds that policy, the library returns:</p><pre>BleError.ScanTooFrequently(<br>    retryAfterMs = retryAfterMs<br>)</pre><p>The application can then inform the user when scanning can be retried.</p><p>This is a proactive library safeguard, not a way to read Android’s exact internal scan quota.</p><p>I also added configurable scan timeouts to ensure scans don’t continue longer than intended.</p><p>Google’s Android documentation recommends stopping scanning once the desired device is found, avoiding scan loops, and setting a time limit. <a href="https://developer.android.com/develop/connectivity/bluetooth/ble/find-ble-devices?utm_source=chatgpt.com">Android Developers</a></p><h3>12. Advertising Interval vs. Scan Interval vs. Scan Duration</h3><p>These three terms are often confused.</p><p>Let’s compare them.</p><p>ConceptControlled byMeaningAdvertising intervalPeripheralHow frequently advertising events occurScan intervalScanner/controllerHow frequently scanning windows beginScan windowScanner/controllerHow long the controller listensScan durationApplication/libraryHow long a scan session runs</p><p>Consider this example:</p><pre>Smart Meter:<br>Advertising Interval = 500 ms<br><br>Android Phone:<br>Scan Interval = 100 ms<br>Scan Window   = 50 ms<br><br>Android Application:<br>Scan Duration = 10 seconds</pre><p>In this example, the meter advertises roughly twice per second.</p><p>The phone listens for portions of time.</p><p>The application stops scanning after 10 seconds.</p><p>These parameters influence discovery behavior, but they serve different purposes.</p><p>Also remember that normal Android applications don’t directly configure arbitrary scan windows or intervals through BluetoothLeScanner.</p><p>They generally select a scan mode, while the Bluetooth stack handles low-level timing.</p><h3>13. Can We Receive Data Without Connecting to a BLE Device?</h3><p>Yes.</p><p>This is one of the most interesting features of BLE advertising.</p><p>Imagine a temperature sensor periodically broadcasting:</p><pre>Device ID: SENSOR_001<br>Temperature: 28°C<br>Battery: 75%</pre><p>If its firmware includes this information in the advertisement or scan response, Android can receive it without establishing a GATT connection.</p><pre>Temperature Sensor<br>        |<br>        | Advertises temperature data<br>        |<br>        v<br>Android Phone<br>        |<br>        v<br>ScanResult<br>        |<br>        v<br>Extract manufacturer/service data<br>        |<br>        v<br>Display temperature</pre><p>This approach is useful for beacon systems, proximity detection, sensor broadcasting, and some IoT applications.</p><p>For example, Android can access manufacturer-specific data using:</p><pre>val manufacturerData =<br>    result.scanRecord<br>        ?.getManufacturerSpecificData(manufacturerId)</pre><p>The meaning of these bytes depends on the manufacturer’s protocol.</p><p>However, if you need to send commands to a device or read GATT characteristics, you usually need to establish a connection.</p><p>For example, consider a prepaid electricity meter.</p><p>Discovering the meter may only require scanning.</p><p>But operations such as reading meter registers, transmitting commands, or writing recharge tokens may require a GATT connection and the relevant service and characteristic access.</p><h3>14. What Should Developers Remember About BLE Advertising?</h3><p>Let’s finish with a few practical engineering principles.</p><p><strong>Advertising is not connecting.</strong> A Bluetooth device can broadcast information without having an active connection.</p><p><strong>Advertising interval is not scan duration.</strong> One is controlled by the peripheral; the other determines how long your application scans.</p><p><strong>A discovered device doesn’t necessarily support connections.</strong> Some BLE devices are designed only to broadcast information.</p><p><strong>A missing device name doesn’t mean a missing device.</strong> Names are optional advertising fields.</p><p><strong>RSSI isn’t an accurate distance measurement.</strong> Radio strength changes with the environment.</p><p><strong>Frequent scan restarts are problematic.</strong> Repeatedly starting and stopping scans can trigger Android throttling.</p><p><strong>BLE is designed around power efficiency.</strong> Both peripheral advertising and scanner listening behavior involve trade-offs between discovery speed and energy consumption.</p><h3>Final Thoughts</h3><p>When I started working with BLE in Android, most examples focused on calling startScan() and displaying nearby devices.</p><p>But understanding the actual flow is far more useful.</p><p>A peripheral broadcasts small packets over radio channels.</p><p>The Android Bluetooth controller listens for those packets.</p><p>The Bluetooth stack processes the results and delivers them to our application.</p><p>Only after discovering a suitable device do we decide whether a GATT connection is necessary.</p><p>Understanding advertising intervals, scanning windows, scan responses, and Android scan restrictions makes it easier to design reliable Bluetooth applications.</p><p>These concepts have also influenced the design of my open-source Android BLE library, <strong>RamaBleManager</strong>, where I’m working on scanning, connection management, GATT communication, timeouts, and structured error handling.</p><p><strong>GitHub:</strong> <a href="https://github.com/dinesh9936/RamaBleManager">https://github.com/dinesh9936/RamaBleManager</a></p><p>If you’re working with BLE, here’s a question worth exploring:</p><p><strong>What happens internally after Android discovers a BLE device and calls </strong><strong>BluetoothGatt.connectGatt()?</strong></p><p>That’s where the next part of the Bluetooth communication journey begins.</p><p><em>References: </em><a href="https://www.bluetooth.com/bluetooth-le-primer/?utm_source=chatgpt.com"><em>Bluetooth SIG — Bluetooth LE Primer</em></a><em>, </em><a href="https://developer.android.com/develop/connectivity/bluetooth/ble/find-ble-devices?utm_source=chatgpt.com"><em>Android Developers — Find BLE Devices</em></a><em>, </em><a href="https://developer.android.com/reference/android/bluetooth/le/ScanCallback?utm_source=chatgpt.com"><em>Android ScanCallback API</em></a><em>, and </em><a href="https://docs.silabs.com/bluetooth/10.0.0/bluetooth-le-fundamentals/04-link-layer?utm_source=chatgpt.com"><em>Silicon Labs — Bluetooth LE Fundamentals</em></a><em>.</em></p><p><strong>Suggested LinkedIn hashtags:</strong></p><p>#AndroidDevelopment #BluetoothLowEnergy #BLE #Kotlin #IoT #AndroidEngineering #WirelessCommunication #OpenSource</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f122cacb3c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How BLE scanning works ?]]></title>
            <link>https://dine9936.medium.com/how-ble-scanning-works-3f4c8de62fc5?source=rss-c9ff6785d3e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f4c8de62fc5</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ble]]></category>
            <category><![CDATA[hardware]]></category>
            <dc:creator><![CDATA[Dinesh Kumar]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 00:38:13 GMT</pubDate>
            <atom:updated>2026-09-29T00:38:13.228Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0d-ExHihxpAUTcnJtf66Q.png" /><figcaption>BLE Advertising and Scanning: A peripheral periodically broadcasts advertising packets, while a central device scans the advertising channels to discover nearby BLE devices.</figcaption></figure><h3>Peripheral</h3><p>A <strong>Peripheral</strong> is a BLE device that advertises its presence by broadcasting small packets of information over the air.</p><p>It is basically saying:</p><p><strong>“Hey, I am here, and this is some basic information about me.”</strong></p><p>Examples of BLE peripherals include:</p><ul><li>Temperature sensors</li><li>Smartwatches</li><li>Fitness bands</li><li>Heart-rate monitors</li><li>BLE modules</li></ul><p>A peripheral can advertise information such as its device name, service UUIDs, manufacturer data, and other small pieces of data.</p><h3>Central</h3><p>A <strong>Central</strong> is a device that scans for nearby BLE peripherals.</p><p>When it finds a peripheral it is interested in, it can initiate a connection with that device.</p><p>For example, your smartphone may scan nearby BLE devices, find a smartwatch, and then connect to it.</p><p>So, in simple words:</p><p><strong>Peripheral = Advertises</strong></p><p><strong>Central = Scans and connects</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f4c8de62fc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is BLE and How Does It Work?]]></title>
            <link>https://dine9936.medium.com/what-is-ble-and-how-does-it-work-91d94d161ec8?source=rss-c9ff6785d3e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/91d94d161ec8</guid>
            <dc:creator><![CDATA[Dinesh Kumar]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 10:42:05 GMT</pubDate>
            <atom:updated>2026-09-28T10:44:55.609Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZTfDA7PFJHSs_lazP9XRw.png" /></figure><p>What is BLE and How Does It Work?<br>Bluetooth is something we use almost every day. We connect our phones to earphones, smartwatches, fitness bands, speakers, and many other devices.</p><p>But there is another type of Bluetooth called Bluetooth Low Energy, commonly known as BLE.</p><p>BLE is designed for devices that need to communicate while using very little power.</p><p>What is BLE?<br>BLE stands for Bluetooth Low Energy.</p><p>It was designed for devices that usually send small amounts of data and need to run for a long time on limited battery power.</p><p>For example:</p><p>Fitness bands</p><p>Smartwatches</p><p>Temperature sensors</p><p>Smart meters</p><p>Medical devices</p><p>Beacons</p><p>IoT devices</p><p>A small BLE sensor can sometimes work for months or even years using a small battery.</p><p>BLE vs Classic Bluetooth<br>Classic Bluetooth is commonly used when we need continuous data transfer.</p><p>For example:</p><p>Phone → Bluetooth Speaker<br>Audio is continuously transferred from the phone to the speaker.</p><p>BLE works differently.</p><p>It is mainly designed for small and occasional data communication.</p><p>For example:</p><p>Temperature Sensor<br> ↓<br>Temperature = 26°C<br> ↓<br> Phone<br>The sensor may send only a small amount of information and then remain idle.</p><p>This helps reduce power consumption.</p><p>How Does BLE Communication Start?<br>Before two BLE devices communicate, one device normally advertises itself.</p><p>Suppose we have a smart temperature sensor.</p><p>The sensor may continuously send small advertising packets.</p><p>BLE Sensor</p><p>))) ))) )))</p><p>Advertising packets<br>These packets can contain information such as:</p><p>Device name<br>Device identifier<br>Supported services<br>Manufacturer information<br>A smartphone can scan for these advertisements.</p><p>BLE Sensor<br> ↓<br>Advertisement<br> ↓<br>Android Phone<br>The phone first discovers the device without establishing a full connection.</p><p>BLE Scanning<br>The Android phone scans nearby BLE devices.</p><p>The flow looks like this:</p><p>BLE Device<br> ↓<br>Advertising<br> ↓<br>Android BLE Scanner<br> ↓<br>Device Found<br>In Android, we can use the Bluetooth LE APIs to scan for nearby BLE devices.</p><p>Once a device is found, the application can decide whether it wants to connect.</p><p>BLE Connection<br>After finding the device, the Android application can connect to it.</p><p>Android Phone<br> ↓<br> Connect<br> ↓<br> BLE Device<br>Once the connection is established, the phone can discover the services available on the BLE device.</p><p>Services and Characteristics<br>This is one of the most important concepts in BLE.</p><p>BLE devices organize their data using:</p><p>Service<br> ↓<br>Characteristic<br>A service represents a group of related functionality.</p><p>A characteristic represents actual data or an operation.</p><p>For example, imagine a smart meter.</p><p>Smart Meter Service<br> │<br> ├── Voltage Characteristic<br> │<br> ├── Current Characteristic<br> │<br> └── Energy Characteristic<br>The Android application can read these characteristics.</p><p>For example:</p><p>Voltage Characteristic<br> ↓<br> 230V<br>Reading Data<br>The phone can request data from a characteristic.</p><p>Android App<br> ↓<br>Read Voltage<br> ↓<br>BLE Device<br> ↓<br>230V<br>The BLE device returns the requested value.</p><p>Writing Data<br>BLE also allows the phone to send information to the device.</p><p>For example, suppose an IoT device contains a relay.</p><p>The Android application may send:</p><p>TURN_ON<br>The communication might look like this:</p><p>Android App<br> ↓<br>Write Command<br> ↓<br>Relay Characteristic<br> ↓<br>BLE Device<br> ↓<br>Relay ON<br>Notifications<br>Sometimes the phone should not continuously ask the device for new data.</p><p>Instead, BLE supports notifications.</p><p>The phone subscribes to a characteristic.</p><p>Android Phone<br> ↓<br>Subscribe<br> ↓<br>BLE Characteristic<br>Now whenever the value changes, the BLE device automatically sends the new value.</p><p>For example:</p><p>Voltage = 230V<br> ↓<br>Voltage = 228V<br> ↓<br>BLE Notification<br> ↓<br>Android App<br>This is useful for real-time sensor data.</p><p>Complete BLE Flow<br>A simplified BLE communication flow looks like this:</p><p>BLE Device<br> ↓<br>Advertise<br> ↓<br>Android scans<br> ↓<br>Device discovered<br> ↓<br>Connect<br> ↓<br>Discover services<br> ↓<br>Discover characteristics<br> ↓<br>Read / Write / Subscribe<br> ↓<br>Exchange data<br>Why Is BLE Useful?<br>BLE is popular because it provides:</p><p>Low power consumption</p><p>Wireless communication</p><p>Support in almost every modern smartphone</p><p>Easy integration with sensors</p><p>Good support for IoT devices</p><p>Small data communication with low energy usage</p><p>This makes BLE very useful for smart devices.</p><p>Real Example<br>Imagine a prepaid electricity meter.</p><p>The architecture could look like this:</p><p>Android Application<br> ↓<br> BLE<br> ↓<br>Smart Electricity Meter<br> ↓<br>Voltage<br>Current<br>Balance<br>Meter Status<br>The Android application can connect to the meter and read information such as voltage, current, balance, or meter status.</p><p>It may also send commands to the meter.</p><p>Final Thoughts<br>BLE is not just a smaller version of Bluetooth.</p><p>It is a communication technology designed mainly for low-power devices.</p><p>The basic idea is simple:</p><p>Advertise<br> ↓<br>Scan<br> ↓<br>Connect<br> ↓<br>Discover<br> ↓<br>Read / Write / Notify<br>Once these five concepts are clear, understanding BLE development becomes much easier.</p><p>In the next article, we can explore how BLE advertising actually works and how Android discovers nearby BLE devices</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91d94d161ec8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LiveData in Android]]></title>
            <link>https://dine9936.medium.com/livedata-in-android-ab38481e0951?source=rss-c9ff6785d3e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab38481e0951</guid>
            <dc:creator><![CDATA[Dinesh Kumar]]></dc:creator>
            <pubDate>Sun, 23 Nov 2025 12:54:58 GMT</pubDate>
            <atom:updated>2025-11-23T12:54:58.328Z</atom:updated>
            <content:encoded><![CDATA[<p>It is a magical container who holds value, notify automatically when value changed, survives configuration changes, follow lifecycle of it’s owner.</p><blockquote>Types of LiveData</blockquote><p>1- LiveData (Read only)</p><p>2- MutableLiveData (Updatable)</p><blockquote>postValue() vs setValue().</blockquote><p>updating value of a mutableLiveData from background thread</p><p>updating value of a mutableLiveData from main thread</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab38481e0951" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detection Of Cycle in Linked List]]></title>
            <link>https://dine9936.medium.com/detection-of-cycle-in-linked-list-77b7af04ca58?source=rss-c9ff6785d3e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/77b7af04ca58</guid>
            <category><![CDATA[linkedlist-in-java]]></category>
            <category><![CDATA[floyd-cycle-detection]]></category>
            <dc:creator><![CDATA[Dinesh Kumar]]></dc:creator>
            <pubDate>Fri, 21 Nov 2025 05:19:44 GMT</pubDate>
            <atom:updated>2025-11-21T05:19:44.436Z</atom:updated>
            <content:encoded><![CDATA[<p>Here, I am trying to show how can we detect is there cycle exist in Linked List or Not?</p><p>In Problem<br>1- Head of linked list</p><p>2- may be empty linked list</p><blockquote>We have to return “true” if cycle exist or return “false” if cycle not exist.</blockquote><p>Here is algorithm</p><p>step 1- first of all check if linked list empty or not if empty return false</p><p>step 2- initialize two variable of node type, slow and fast = head</p><p>step 3- now we have to traverse the linked list until fast != null &amp;&amp; fast.next != null (because fast pointer will run faster than slow)</p><p>step 4- move slow pointer with one step and fast with two step</p><p>step 5- with each traversal check if slow == fast then return true</p><p>step 6- when traversal completed then return false means not cycle exist.</p><p>Then is a pseudo code of above algorithm</p><blockquote>Java Code</blockquote><pre>    if(head == null) return false;<br>        ListNode slow = head;<br>        ListNode fast = head;<br>        while(fast != null &amp;&amp; fast.next != null){<br>             slow = slow.next;<br>            fast = fast.next.next;<br>            if(slow == fast) return true;<br>        }<br>        return false;<br>    }</pre><blockquote>Kotlin Code</blockquote><pre>fun hasCycle(head: ListNode?): Boolean {<br>        if(head == null) return false;<br>        var slow = head;<br>        var fast = head;<br>        while(fast != null &amp;&amp; fast?.next != null){<br>            slow = slow?.next<br>            fast = fast.next?.next<br><br>            if(slow == fast)return true<br>        }<br>        return false<br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77b7af04ca58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Stack data structure in Kotlin:]]></title>
            <link>https://dine9936.medium.com/mastering-stack-data-structure-in-kotlin-bf9b6b604a80?source=rss-c9ff6785d3e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf9b6b604a80</guid>
            <category><![CDATA[arraydeque]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[stack]]></category>
            <dc:creator><![CDATA[Dinesh Kumar]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 03:57:03 GMT</pubDate>
            <atom:updated>2025-03-28T03:57:03.219Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating stack in kotlin using array:</p><p>1 — create a class with primary constructor and a value which is capacity of stack.</p><p>2 — create an array of required data type (in my case Int).</p><p>3 — initialize a variable (top) with value -1 which will use for stack operations.</p><p>4 — create all function according to operations (push, pop, peek, size, isEmpty)</p><p>Push:</p><p>1 — We are using array to create stack so we have to check is array fulled when ever we push item.</p><p>2 — We will first increase top value by 1 and insert data at “top” position of array.</p><p>Pop:</p><p>1 — When ever we pop from stack we will check stack is empty or not using (top == -1)</p><p>2 — then decrease top value by 1</p><p>Peek:</p><p>1 — Peek means return stack top position value only.</p><p>2 — so first check is stack empty or not.</p><p>3 — return stack top value.</p><pre><br>class MyStack(private val capacity: Int){<br>  private val stackItems = IntArray(capacity)<br>  private var top = -1<br><br>  fun push(data: Int){<br>    if(top == capacity - 1){<br>      print(&quot;stack is full.&quot;)<br>      return<br>    }<br>    <br>    top++<br>    stackItems[top] = data<br>  }<br><br>  fun pop(){<br>    if(top == -1){<br>      print(&quot;stack is empty.&quot;)<br>      return<br>    }<br>    top--<br>  }<br><br>  fun peek(){<br>        if (top == -1){<br>            println(&quot;Stack is empty.&quot;)<br>            return<br>        }<br><br>        val peekItem = array[top]<br>        println(&quot;Peek item is $peekItem&quot;)<br>    }<br><br>    fun isEmpty(){<br>        if (top == -1){<br>            println(&quot;Yes stack is empty.&quot;)<br>        }else{<br>            println(&quot;No stack is not empty.&quot;)<br>        }<br>    }<br><br>    fun sizeOfStack(){<br>        println(&quot; Size of stack is ${top+1}&quot;)<br>    }<br>}</pre><p>This is stack using array. <br>we can also create a stack using ArrayList, MutableList, LinkedList.<br><strong>Note:</strong> Kotlin does not provide any built in function for stack like java. But we can use ArrayDeque class which is in kotlin collection.</p><h3>ArrayDeque:</h3><p>ArrayDeque is a resizable, array-based implementation of a double-ended queue (deque), allowing elements to be added or removed from both the front (head) and back (tail).</p><p>Combines the functionality of a stack (LIFO — Last In, First Out) and a queue (FIFO — First In, First Out)</p><pre>import kotlin. collections. ArrayDeque<br><br>class SimpleStack&lt;T&gt; {<br>    private val stack = ArrayDeque&lt;T&gt;()<br><br>    <br>    fun push(item: T) {<br>        stack.addLast(item) <br>    }<br><br>    fun pop(): T? {<br>        return if (stack.isEmpty()) {<br>            null <br>        } else {<br>            stack.removeLast() <br>        }<br>    }<br><br>    <br>    fun peek(): T? {<br>        return stack.lastOrNull() <br>    }<br><br>    <br>    fun isEmpty(): Boolean {<br>        return stack.isEmpty()<br>    }<br><br>   <br>    fun size(): Int {<br>        return stack.size<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf9b6b604a80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debug you android device with android device through wifi.]]></title>
            <link>https://dine9936.medium.com/debug-you-android-device-with-android-device-through-wifi-78c8eb8a752a?source=rss-c9ff6785d3e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/78c8eb8a752a</guid>
            <dc:creator><![CDATA[Dinesh Kumar]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 06:43:03 GMT</pubDate>
            <atom:updated>2025-03-27T06:43:03.528Z</atom:updated>
            <content:encoded><![CDATA[<p>1 — adb devices<br>2 — adb tcpip 5555<br>3 — adb connect device_ip:5555</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78c8eb8a752a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Know stack and basic operation using Kotlin]]></title>
            <link>https://dine9936.medium.com/know-stack-and-basic-operation-using-kotlin-ea70566df456?source=rss-c9ff6785d3e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea70566df456</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[stack-data-structure]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Dinesh Kumar]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 04:10:58 GMT</pubDate>
            <atom:updated>2025-03-27T04:10:58.924Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction:</strong></p><p>1 — It is a Linear Data Structure.</p><p>2 — Follows a specific order to perform operations like insertion, deletion.</p><p>3 — Order is known as LIFO means last in first out.</p><p>In computer memory data is arranged like that when we insert any new data in stack data structure, it will follow like a pile of plates.</p><p>Basic operations are — push(), pop(), isEmpty(), peek()</p><p><strong>Creation of stack data structure:</strong></p><pre>class MyStack(private val capacity: Int) {<br>    private val stackArray = arrayOfNulls&lt;Int&gt;(capacity)  // Fixed-size array<br>    private var top = -1  // Keeps track of the top element index<br><br>    // Push (Add an element to the stack)<br>    fun push(item: Int) {<br>        if (top == capacity - 1) {<br>            println(&quot;Stack Overflow! Cannot push $item.&quot;)<br>            return<br>        }<br>        top++<br>        stackArray[top] = item<br>        println(&quot;Pushed: $item&quot;)<br>    }<br><br>    // Pop (Remove and return the top element)<br>    fun pop(): Int? {<br>        if (isEmpty()) {<br>            println(&quot;Stack Underflow! Stack is empty.&quot;)<br>            return null<br>        }<br>        val removedItem = stackArray[top]<br>        stackArray[top] = null  // Optional: Clear the reference<br>        top--<br>        println(&quot;Popped: $removedItem&quot;)<br>        return removedItem<br>    }<br><br>    // Peek (See the top element without removing it)<br>    fun peek(): Int? {<br>        return if (isEmpty()) {<br>            println(&quot;Stack is empty!&quot;)<br>            null<br>        } else {<br>            stackArray[top]<br>        }<br>    }<br><br>    // Check if the stack is empty<br>    fun isEmpty(): Boolean {<br>        return top == -1<br>    }<br><br>    // Get the size of the stack<br>    fun size(): Int {<br>        return top + 1<br>    }<br><br>    // Print the stack<br>    fun printStack() {<br>        if (isEmpty()) {<br>            println(&quot;Stack is empty!&quot;)<br>            return<br>        }<br>        print(&quot;Stack: &quot;)<br>        for (i in 0..top) {<br>            print(&quot;${stackArray[i]} &quot;)<br>        }<br>        println()<br>    }<br>}<br><br>// Testing MyStack<br>fun main() {<br>    val stack = MyStack(5)  // Create a stack with a capacity of 5<br><br>    stack.push(10)<br>    stack.push(20)<br>    stack.push(30)<br><br>    stack.printStack() // Stack: 10 20 30<br><br>    println(&quot;Peek: ${stack.peek()}&quot;) // Peek: 30<br><br>    stack.pop()  // Removes 30<br>    stack.printStack() // Stack: 10 20<br><br>    stack.pop()  // Removes 20<br>    stack.pop()  // Removes 10<br>    stack.pop()  // Stack Underflow! Stack is empty.<br>}</pre><p>Pushed: 10<br>Pushed: 20<br>Pushed: 30<br>Stack: 10 20 30<br>Peek: 30<br>Popped: 30<br>Stack: 10 20<br>Popped: 20<br>Popped: 10<br>Stack Underflow! Stack is empty.</p><p>This is only basic points to know about stack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea70566df456" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trie Data Structure]]></title>
            <link>https://dine9936.medium.com/trie-data-structure-7d4a491ca2c1?source=rss-c9ff6785d3e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d4a491ca2c1</guid>
            <category><![CDATA[trie]]></category>
            <dc:creator><![CDATA[Dinesh Kumar]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 08:39:23 GMT</pubDate>
            <atom:updated>2025-03-26T08:39:23.331Z</atom:updated>
            <content:encoded><![CDATA[<p>A <strong>Trie</strong> is a tree-like data structure used for <strong>fast word searching, autocomplete, and spell checking</strong>. Each node represents a character, and children store possible next characters.</p><pre>class TrieNode {<br>    val children = Array&lt;TrieNode?&gt;(26) { null }<br>    var isEndOfWord = false <br>}</pre><p>Basic Operations : Insert, Search</p><pre>class Trie {<br>    private val root = TrieNode()<br><br>    // Insert a word into the Trie<br>    fun insert(word: String) {<br>        var current = root<br>        for (char in word) {<br>            val index = char - &#39;a&#39; // Convert character to index (0-25)<br>            if (current.children[index] == null) {<br>                current.children[index] = TrieNode()<br>            }<br>            current = current.children[index]!!<br>        }<br>        current.isEndOfWord = true // Mark last node as end of word<br>    }<br><br>    // Search for a word in the Trie<br>    fun search(word: String): Boolean {<br>        var current = root<br>        for (char in word) {<br>            val index = char - &#39;a&#39;<br>            if (current.children[index] == null) return false<br>            current = current.children[index]!!<br>        }<br>        return current.isEndOfWord // True only if it&#39;s a complete word<br>    }<br><br>    // Check if a prefix exists in the Trie<br>    fun startsWith(prefix: String): Boolean {<br>        var current = root<br>        for (char in prefix) {<br>            val index = char - &#39;a&#39;<br>            if (current.children[index] == null) return false<br>            current = current.children[index]!!<br>        }<br>        return true<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d4a491ca2c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>