DEV Community

Cover image for Your Android BLE scan quietly dies after 5 minutes, and you don't even know it
Denis Khamidullin
Denis Khamidullin

Posted on Originally published at Medium

Your Android BLE scan quietly dies after 5 minutes, and you don't even know it

"What is essential is invisible to the eye."

Antoine de Saint-Exupéry, The Little Prince

Hi everyone! I'm Denis Khamidullin, an Android developer at Navigine.

For more than ten years we have been building indoor positioning solutions for people, vehicles and equipment inside buildings and on enclosed sites, in industry, logistics and retail.

In short, here is how our solution works. Positioning is based on Bluetooth Low Energy (BLE). The device scans BLE beacons: small autonomous devices that keep broadcasting short packets with an identifier (in iBeacon, that is UUID + major + minor) and the calibrated signal strength at 1 m. Measurements from several beacons are the input for algorithms that estimate the device position.

More about our algorithms and technology is on our blog.

Quite often the tracked device is an ordinary Android phone in an employee's pocket. That means it has to work not only while unlocked, but also in the background with the screen off. This is where things get strange: on one phone everything is stable, on another the beacons "disappear" after half an hour, and on a third the app quietly stops working overnight.

Most articles on this topic were written back in the Android 7–9 days and are badly outdated. In this article I will explain how BLE scanning works and why it degrades in the background on modern Android: which limits are built into the Bluetooth stack itself (with links to the AOSP sources) and what device manufacturers add on top. Then I will show how we solved the problem, which pitfalls we hit along the way, and what of this is confirmed by measurements on a real device.

stable_bg_meme

Android keeps tightening the screws

Android has been optimizing power consumption for years. It started with Android 6, which introduced Doze mode and App Standby. There are two reasons for this: saving battery and protecting user privacy. With every OS release it gets harder to do work in the background, and every app has to fight for its place in the sun.

Android version What changed
6 (2015) Doze and App Standby; BLE scanning requires a runtime location permission
7 Doze "on the go" (light doze); undocumented BLE limits: no more than 5 scan starts per 30 s, and a timeout for long-running scans
8 / 8.1 Background services are stopped a few minutes after the app goes to the background, so long-running work needs a Foreground Service; PendingIntent scanning appears; in 8.1, unfiltered scans are paused while the screen is off
9 App Standby Buckets: how often background work runs depends on how often the user opens the app
10 Separate ACCESS_BACKGROUND_LOCATION permission; foregroundServiceType="location"
11 "Allow all the time" location access can only be granted in Settings
12 Starting a Foreground Service from the background is banned (with exceptions); new BLUETOOTH_SCAN permission
13 Bluetooth moves into a separate system module (Mainline); in QPR1 the 30-minute timeout also applies to filtered scans
14 Foreground Service type is mandatory, plus a separate permission for each type
15 Force stop cancels all of the app's PendingIntents, including a PendingIntent scan
16 JobScheduler quotas apply even while a Foreground Service is running; the Bluetooth module is updated independently of the firmware
17 Per-app memory limits depending on the amount of RAM

On top of that, device manufacturers often ship their own Android skins that add their own background rules: "sleeping" apps, autostart controls, aggressive background cleanup. This has been a long-standing pain for every Android developer, but more on that later.

All measurements in this article were taken on a Samsung device (Android 14, One UI 6.1). Data on other manufacturers comes from public sources.

1. The basic scan: how it works

Let's start with the manifest, since that is where all permissions are declared. Every Android release asks for more of them. The set you need to scan beacons depends on the Android version:

Android What you need to scan beacons
6–9 (API 23–28) BLUETOOTH, BLUETOOTH_ADMIN + runtime ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION; location services turned on
10–11 (API 29–30) ACCESS_FINE_LOCATION (coarse is no longer enough); for background, ACCESS_BACKGROUND_LOCATION (on 11, only via Settings)
12+ (API 31+) Runtime BLUETOOTH_SCAN ("Nearby devices" group); beacons still need ACCESS_FINE_LOCATION, and ACCESS_BACKGROUND_LOCATION for background (see neverForLocation below)
14+ (API 34+) For the background service: FOREGROUND_SERVICE + FOREGROUND_SERVICE_LOCATION and foregroundServiceType="location"; such a service can be started from the background only with ACCESS_BACKGROUND_LOCATION

You can already hit a couple of pitfalls at this stage.

1) neverForLocation. The Android 12 documentation offers the neverForLocation flag, which declares that you don't derive location from scan results. Tempting, but with this flag the system silently strips iBeacon and Eddystone packets from the results. AOSP has a denylist for this, matching the signatures 0x004C 0x02 (iBeacon) and 0xFEAA (Eddystone). In our case that means an empty screen without a single error.

2) Checking legacy permissions. If BLUETOOTH/BLUETOOTH_ADMIN are declared with maxSdkVersion="30" (as Google recommends), checkSelfPermission returns DENIED for them on Android 12+. Code that checks them on every version will never start a scan.

1.1 How to start a scan

val scanner = bluetoothManager.adapter.bluetoothLeScanner

val filters = listOf(
    ScanFilter.Builder()
        // iBeacon: manufacturer Apple (0x004C), first two data bytes = 0x02 0x15
        .setManufacturerData(0x004C, byteArrayOf(0x02, 0x15), byteArrayOf(-1, -1))
        .build()
)

val settings = ScanSettings.Builder()
    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
    .build()

scanner.startScan(filters, settings, object : ScanCallback() {
    override fun onScanResult(callbackType: Int, result: ScanResult) { /* RSSI, scanRecord */ }
    override fun onScanFailed(errorCode: Int) { /* not always delivered */ }
})
Enter fullscreen mode Exit fullscreen mode
  • ScanFilter is what to look for: MAC, name, service UUID, service data, manufacturer data with a mask. Where possible, filters run right in the Bluetooth controller, so the CPU doesn't wake up for other people's devices. And as we'll see in section 3, without a filter background scanning simply doesn't work.
  • ScanSettings is how to look: the scan mode (scanMode), the callback type (every packet / first match / match lost), and reportDelay (buffer results in the controller and deliver them in batches). ### 1.2 What is a scan mode?

A beacon sends the same packet on three advertising channels (37, 38, 39) in turn, once per advertising interval (T_adv, usually 100–1000 ms). The phone doesn't listen to the air all the time either, but in windows: in each scan interval it listens on one channel for the length of the window and sleeps the rest of the time. The SCAN_MODE_* constants are just names for window / interval pairs.

Mode Window / interval, ms Share of time listening
LOW_POWER 140 / 1400 10%
BALANCED 183 / 730 ~25%
LOW_LATENCY 100 / 100 ~100%
SCREEN_OFF (internal) 512 / 10 240 5%
SCREEN_OFF_BALANCED (internal) 183 / 730 ~25%

We can't request the last two modes: they are internal to the system. More on that in section 3.

How many packets will we see? If the window is longer than T_adv, a packet almost certainly lands in every window. If it is shorter, the chance to catch a packet in one window is roughly window / T_adv:

detections per minute ≈ (60 000 / interval) × min(1, window / T_adv) × (1 − over-the-air loss)
Enter fullscreen mode Exit fullscreen mode

Our test beacon advertises every ~500 ms. In LOW_LATENCY with the screen on, the phone saw 94 packets per minute out of ~120 possible: about 22% are lost even in ideal conditions. For LOW_POWER the formula gives ~9–12 per minute, for BALANCED ~23–30.

The takeaway: besides the rate, you need to watch the maximum gap between detections. With a 10-second scan interval (SCREEN_OFF), a person can walk 10–15 meters between two measurements.

1.3 Where does the scan actually run?

Call path: app → BluetoothLeScanner → binder → Bluetooth system process (GattService → ScanManager) → native stack → HCI → Bluetooth controller.

scan callpath

This leads to three important points:

  1. There is one Bluetooth controller for the whole device. All apps use it at once, and the system configures it. We can pass our wishes (mode, filters) and receive results in a callback. If another app is scanning in parallel with a more aggressive mode, the controller changes how it works. That is why the same app can behave differently on two identical phones.
  2. The system picks the final mode. This is the job of ScanManager, a component of the system Bluetooth service. It takes into account whether the screen is on, whether the app is visible to the user, and how long the scan has been running. Based on that, it can downgrade the mode we asked for. More on this in the next section.
  3. Bluetooth is a separate updatable module. It has been a Mainline module since Android 13, and since Android 16 it is updated independently of the firmware. So scanning behavior depends both on the Android version and on the version of this module. You have to babysit background scanning yourself. For location, Android has ready-made system mechanisms such as Fused Location and geofences: the system collects data and wakes the app up. For long-running BLE scanning, unfortunately, there is no such mechanism. The app has to keep the scan alive on its own: run in a Foreground Service, restart the scan, and recover after the process dies.

2. What breaks in the background, and why

Background scanning problems fit neatly into three layers: the Bluetooth stack, the process lifecycle, and the manufacturer's firmware. Each layer can stop the scan on its own, regardless of the others.

ble layers

Layer A: the AOSP Bluetooth stack (ScanManager)

This is what we described above: scan filters, windows and intervals, timeouts and limits. Think of it as the first line of defense. Most problems you run into while implementing scanning live right here. But beyond the trees there is a whole forest.

Layer B: the process lifecycle

If you want (almost) guaranteed background scanning, you need a Foreground Service. Sounds simple: a couple of classes and you're done. In reality it is more involved, and depending on the OS version you have to follow a set of rules:

  • Android 12: a Foreground Service can't be started from the background, with rare exceptions. Start the service while the app is on screen.
  • Android 14: the service type is mandatory. For us that is location, plus a separate FOREGROUND_SERVICE_LOCATION permission; without location access the service won't start.
  • Android 15: force stop cancels all of the app's PendingIntents, including a PendingIntent scan. BOOT_COMPLETED receivers may no longer start some service types, but location is not on that list.
  • Android 16: JobScheduler quotas apply even while a Foreground Service is running.
  • Android 17: per-app memory limits depending on the amount of RAM (behavior changes). When the limit is exceeded, the process is killed: ApplicationExitInfo reports REASON_OTHER with MemoryLimiter:AnonSwap in the description. For now the limits are generous and aimed at memory leaks, but for a service that runs for days this matters. WorkManager and JobScheduler won't do the job here, unfortunately: periodic work can run no more often than once every 15 minutes. They are still useful as a watchdog that restarts the scan with a PendingIntent.

Three more things worth knowing:

  • Doze. When the phone lies still with the screen off and isn't charging, the system defers network access, alarms and background jobs. The scan itself runs in the Bluetooth process, but whatever you do with the results (uploading to a server, timers) falls under these restrictions. Some manufacturers have their own, harsher "deep" Doze. For example, on HyperOS developers report a log line where the system refuses to start a scan for non-system apps.
  • Force stop. After "Force stop" in Settings, the system tears everything down: the service, alarms, jobs, and since Android 15 the PendingIntent scan too. The app won't start again until the user opens it. This is a deliberate user action, and you shouldn't try to work around it.
  • Process death. When memory is low, the system can kill even a process with a Foreground Service. With START_STICKY the service restarts by itself, but the scan has to be started again in onStartCommand (our measurement is in section 3.5). ### Layer C: OEM firmware

As mentioned earlier, manufacturers add their own power-saving mechanisms on top of Android, and these work below the API level. The service notification is showing, the code follows the documentation, and the firmware still decides the app doesn't need to run. The main restrictions from popular vendors:

Manufacturer What gets in the way
Samsung (One UI) "Sleeping" and "deep sleeping" app lists: an app that hasn't been opened for several days is restricted automatically. Since One UI 6.0, Samsung states that Foreground Services of apps targeting Android 14 work as intended
Xiaomi (MIUI, HyperOS) Autostart is off by default, and without it the service isn't restarted; aggressive background cleanup. On a Xiaomi 12T with the screen off, scan results arrive in a batch once every 5 minutes (Nordic DevZone)
Huawei, Honor (EMUI, HarmonyOS) "App launch" in automatic mode blocks autostart and background activity
OPPO, Vivo, OnePlus Periodic cleanup of background processes, including ones with a Foreground Service

There is a great site that tracks all of these restrictions; if you're an Android developer, you probably know it already: dontkillmyapp.com.

3. What we tested

We ran a bare scanner on a Samsung test device (Android 14) under different conditions: screen on and off, app open and minimized, process killed, app swiped away from Recents. The scanner ran inside a Foreground Service of type location, and the app was excluded from battery optimization.

The short version: almost all problems come down to one mechanism, the long-running scan timeout. Below, in order: what we expected, what we saw, and how to check it yourself.

A caveat: the app was excluded from battery optimization. Behavior on other manufacturers' devices may differ.

3.1 The long-running scan timeout: 5 minutes

We start LOW_LATENCY with an iBeacon filter and leave the phone lying with the screen on. For the first five minutes everything is great: 75–100 detections per minute. In the sixth minute the rate drops to 5–14 per minute and never recovers. Having the app open on screen changes nothing: the drop is the same as in the background.

The cause is right there in logcat:

23:56:14.796 scan started (scannerId 7, LOW_LATENCY)
00:01:14.826 W BtGatt.ScanManager: Moving filtered scan client to downgraded scan (scannerId 7)
Enter fullscreen mode Exit fullscreen mode

Exactly 300 seconds. This is an AOSP mechanism: if a scan runs longer than scan_timeout_millis, ScanManager moves it to LOW_POWER, and an unfiltered scan to opportunistic mode. Downgrading filtered scans was added in Android 13 QPR1. The app is told nothing: callbacks keep coming, just less often. In dumpsys bluetooth_manager the scan gets a Forced mark, while its settings still say LOW_LATENCY.

In AOSP the default is 30 minutes, but in practice the value varies from phone to phone. Starting with Android 15, Google lowered it to 10 minutes (600000 ms). You can check it with:

$ adb shell device_config get bluetooth scan_timeout_millis
Enter fullscreen mode Exit fullscreen mode

The good news: the timer is counted from each startScan call. How we use that is in section 4.

3.2 No filter vs. an empty filter

Since Android 8.1, an unfiltered scan is paused when the screen turns off. The internet often suggests working around this with an empty filter, ScanFilter.Builder().build(). That used to work. We tested three options:

Filter Screen on, detections/min Screen off, detections/min
No filter (null) 90 ~0
Empty ScanFilter 80 ~0
iBeacon (0x004C, 02 15) 80 45–60

The conclusion is simple: you need a real filter. For iBeacon, filter on Apple manufacturer data (0x004C) with the 02 15 prefix; you can also add your beacons' UUID.

3.3 The start quota and silent rejection

The system allows an app no more than 5 startScan calls per 30 seconds (scan_quota_count and scan_quota_window_millis). We restarted the scan 7 times about 5 seconds apart. The first five starts went through, and the system rejected the sixth:

E BtGatt.GattService: App 'com.navigine.indoornavigationdemo' is scanning too frequently
Enter fullscreen mode Exit fullscreen mode

The seventh went through again: by then the first start had left the 30-second window.

The worst part is that the app never learned about the rejection. Since API 33 there is an error code, SCAN_FAILED_SCANNING_TOO_FREQUENTLY, but in our case onScanFailed was never called. As far as the app knows, the scan is "running", yet there are no results. If your code has a "no results → restart" loop, it can easily run into the quota and switch itself off.

So starts need their own counter, and onScanFailed can't be your only signal.

3.4 Screen off and a Foreground Service

According to the AOSP code, a background app gets one of the power-saving SCREEN_OFF modes when the screen is off. The exception is apps with a Foreground Service: they keep LOW_LATENCY. Our Samsung confirmed this. We started a scan and turned the screen off after 2 minutes:

Minute after start Screen Detections/min
1–2 on 55, 80
3–5 off 62, 45, 47
6–7 off 17, 2

With the screen off there are about half as many detections, and dumpsys shows why: the moment the screen turns off, Samsung switches LOW_LATENCY from a 4096 ms window and 4096 ms interval (100%) to a 158.75 ms window and 305.6 ms interval, about 52% of the time.

In the sixth minute, the same timeout from section 3.1 fires. So with a Foreground Service, turning the screen off doesn't cut the scan by itself. The timeout does, and with the screen off the downgrade can go even deeper. Restarting the scan solves this; more on that below.

3.5 Process death and swiping from Recents

We tested two scenarios.

Process killed (kill -9). The system restarted the START_STICKY service after 1.7 seconds, and the first detection arrived 2.1 seconds after the kill. The new scan ran at full speed again.

App swiped away from Recents. onTaskRemoved arrived, but the process stayed alive: the service and the scan kept running, with a 0.3-second gap in the results stream. Without a running service, the same gesture kills the process on this phone (ApplicationExitInfo reports REMOVE TASK).

4. How we solve it in our SDK

Our scanning logic used to be fairly naive: LOW_LATENCY while the app is on screen, LOW_POWER with a filter by beacon manufacturers when it is minimized. The scan was started by app lifecycle events and then left to live on its own. In practice that meant everything described in section 3: after 5 minutes the detection rate dropped several times over, and after a process restart without UI the scan might not start at all.

Through observation and trial and error, we reworked our logic to account for system limits as much as possible. Below, limit by limit: what the system does, what we do, pseudocode, and the cost of the solution.

The long-running scan timeout

As we found out, the scan is downgraded to LOW_POWER scan_timeout_millis after it starts. On our test device that is 5 minutes; the AOSP default used to be 30 (1800000 ms), and on Android 15+ devices it is 10 minutes.

How we fixed it. The system timer is counted from each startScan call, so we restart the scan before it expires: once every 4 minutes. The app can't find out the exact timeout on a given phone, because it is not allowed to read device_config. So we pick an interval with a margin under the shortest timeout we know of.

const val RESTART_PERIOD_MS = 4 * 60_000L // shorter than the 5-minute timeout

fun onScanStarted() {
    handler.removeCallbacks(restartTask)
    handler.postDelayed(restartTask, RESTART_PERIOD_MS)
}

val restartTask = Runnable { restart() } // stopScan() + requestStart()
Enter fullscreen mode Exit fullscreen mode

In a test implementation of this approach, the drop at the fifth minute is gone:

No restart, after minute 5 Restart every 4 minutes
Screen on, detections/min ~10 92
Screen off, detections/min 2–6 48

Beacon detections per minute with and without a scan restart

The cost. The radio spends more time in active mode, so battery drain is higher than with a downgraded scan. Each restart means a short gap in the stream (at most 3.4 s with the screen on in our test) and one start out of the quota, but once every 4 minutes this goes unnoticed. We did not measure battery drain separately.

No filter vs. an empty filter

With the screen off, a scan with no filter or with an empty filter is paused.

How we fixed it. We added filters for every beacon format our parser understands. Filters in the list are combined with OR: a packet passes if it matches at least one of them. Optionally, once a venue is loaded and its beacons' UUIDs are known, the iBeacon filter can be narrowed down to them.

fun filters(): List<ScanFilter> = listOf(
    // iBeacon: Apple (0x004C), prefix 02 15
    ScanFilter.Builder()
        .setManufacturerData(0x004C, byteArrayOf(0x02, 0x15), byteArrayOf(-1, -1)).build(),
    // iBecom
    ScanFilter.Builder().setManufacturerData(0x0059, byteArrayOf()).build(),
    // Eddystone
    ScanFilter.Builder().setServiceData(ParcelUuid.fromString("0000FEAA-0000-1000-8000-00805F9B34FB"), byteArrayOf()).build(),
    // Kontakt.io
    ScanFilter.Builder().setServiceData(ParcelUuid.fromString("0000FE6A-0000-1000-8000-00805F9B34FB"), byteArrayOf()).build(),
)
Enter fullscreen mode Exit fullscreen mode

The cost. Filters run in the controller, and the controller supports a limited number of them, so we keep the list short. A new beacon format without its own filter won't be visible in the background; each one has to be added explicitly.

The start quota and silent rejection

The system doesn't allow more than 5 startScan calls per 30 seconds and rejects the sixth.

How we fixed it. Scan starts used to come from several places in the code, and not all of them respected the limit. Now every start (scheduled restart, mode change, watchdog, Bluetooth turned back on) goes through a single counter. If the limit is used up, the start is postponed until the oldest start leaves the 30-second window, plus a small margin. If more requests arrive in the meantime, only the latest one runs.

class StartQuota(val max: Int = 5, val windowMs: Long = 30_000) {
    private val starts = ArrayDeque<Long>()
    private var pending: (() -> Unit)? = null

    fun runWhenAllowed(start: () -> Unit) {
        val now = SystemClock.elapsedRealtime()
        starts.removeAll { now - it > windowMs }
        if (starts.size < max) {
            starts.addLast(now)
            start()
        } else {
            val firstScheduling = pending == null
            pending = start // older requests are replaced by the latest one
            if (firstScheduling) {
                val delay = starts.first() + windowMs - now + 2_000
                handler.postDelayed({ pending?.let { pending = null; runWhenAllowed(it) } }, delay)
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The cost. In the worst case the scan starts with a delay of up to ~30 seconds. The system counts the limit per app, so if something else in the app is scanning too, our counter may not match the system's. That is what the next item is for.

Silent rejection when the quota is exceeded

If the system rejected a start, onScanFailed may never arrive. The app thinks the scan is running, but there are no results.

How we fixed it. We added a watchdog. It remembers when the last result arrived and, if the silence lasts longer than a threshold, restarts the scan through the same quota counter. That way the watchdog can't run into the limit itself.

const val SILENCE_MS = 60_000L
var lastResultAt = 0L

fun onScanResult(result: ScanResult) {
    lastResultAt = SystemClock.elapsedRealtime()
    deliver(result)
}

val watchdogTask = object : Runnable {
    override fun run() {
        if (SystemClock.elapsedRealtime() - lastResultAt > SILENCE_MS) restart()
        handler.postDelayed(this, SILENCE_MS)
    }
}
Enter fullscreen mode Exit fullscreen mode

The cost. Silence doesn't always mean failure: the person may simply have walked out of beacon range. Then we restart the scan once a minute for nothing. It is almost free for the system, but the threshold should be tuned to your use case.

Process death and swiping from Recents

The system can kill the process when memory is low or, starting with Android 17, when the app exceeds its memory limit.

How we fixed it. The service returns START_STICKY, and the system restarts it by itself. This is where we hit a pitfall. In the old version, the scan was started on ON_START and ON_STOP events from ProcessLifecycleOwner. If the process came up without UI (which is exactly what happens on a START_STICKY restart), these events never arrived, and the scan didn't start until the user opened the app. Now the scan starts immediately, and the mode is chosen from the app's current state. Lifecycle events are only used to switch modes.

class ScanService : Service() {
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startForeground(NOTIFICATION_ID, notification, FOREGROUND_SERVICE_TYPE_LOCATION)
        scanController.start() // both on first launch and after a restart (intent == null)
        return START_STICKY
    }
}

fun BleScanController.start() {
    val visible = ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast(STARTED)
    mode = if (visible) FOREGROUND else BACKGROUND
    requestStart() // don't wait for ON_START / ON_STOP
}
Enter fullscreen mode Exit fullscreen mode

In the kill -9 test, the system restarted the service in 1.7 s, and the first detection arrived after 2.1 s.

The cost. START_STICKY is not a silver bullet. The system may increase the delay between restarts after repeated crashes, and some firmware won't bring the service back at all without the autostart permission.

Background process restrictions

Without a Foreground Service, a background process gets stopped sooner or later. And since Android 12, the service itself can't be started from the background.

How we fixed it. We start a Foreground Service of type location while the app is open. After that the service lives on its own and survives minimizing and swiping from Recents. In our device tests, the gap in the stream after a swipe was 0.3 s.

// in an Activity, while the app is on screen
if (hasScanPermissions()) {
    ContextCompat.startForegroundService(this, Intent(this, ScanService::class.java))
}
Enter fullscreen mode Exit fullscreen mode

The cost. On Android 13+ you have to request the runtime notification permission, and not every user likes seeing a permanent notification in the shade.

The background scan mode gets downgraded

The system moves background apps to power-saving modes. We used to switch to LOW_POWER in the background on our side too, which gives about 10 detections per minute with the screen on and about 6 with it off.

How we fixed it. While a Foreground Service is running, the system keeps LOW_LATENCY in the background as well, as long as the scan has a filter. So our SDK has a flag that keeps LOW_LATENCY after the app is minimized. Of course, you still won't get the screen-on rate: in our tests the controller listens about 52% of the time in this case and delivers about 48 detections per minute instead of 90. That is the price of stable operation.

fun settings(mode: Mode): ScanSettings = ScanSettings.Builder()
    .setScanMode(
        if (mode == FOREGROUND || config.lowLatencyInBackground) SCAN_MODE_LOW_LATENCY
        else SCAN_MODE_LOW_POWER
    )
    .build()
Enter fullscreen mode Exit fullscreen mode

The cost. This is the most battery-hungry part of the setup: the radio is working almost all the time. That is exactly why it is an option, not the default: if you only need a position every few seconds, LOW_POWER is enough.

WorkManager and JobScheduler: no more than once every 15 minutes

Periodic jobs run no more often than once every 15 minutes, and since Android 16 quotas apply to them even while a service is running. That doesn't work for our task.

How we fixed it. The scan itself runs only in the service. A periodic job checks every 15 minutes whether the service is alive and how long ago the last result came in. If the service is dead, the job tries to bring it back, and if the system won't allow starting the service from the background, it turns on a PendingIntent scan as a fallback.

class ScanGuardWorker(ctx: Context, params: WorkerParameters) : Worker(ctx, params) {
    override fun doWork(): Result {
        if (ScanService.isAliveAndReceiving()) return Result.success()
        try {
            ContextCompat.startForegroundService(
                applicationContext, Intent(applicationContext, ScanService::class.java)
            )
        } catch (e: ForegroundServiceStartNotAllowedException) {
            startPendingIntentScan(applicationContext) // fallback
        }
        return Result.success()
    }
}

// registration
WorkManager.getInstance(ctx).enqueueUniquePeriodicWork(
    "scan-guard", ExistingPeriodicWorkPolicy.KEEP,
    PeriodicWorkRequestBuilder<ScanGuardWorker>(15, TimeUnit.MINUTES).build()
)
Enter fullscreen mode Exit fullscreen mode

The cost. Up to 15 minutes pass before the safety net kicks in, and in Doze it can be even longer. On Android 12+, a Foreground Service can be started from the background only in specific cases, for example when the app is excluded from battery optimization or a high-priority push arrives. Otherwise ForegroundServiceStartNotAllowedException is thrown. The system downgrades a background PendingIntent scan too, so it is a safety net, not a replacement for the service.

Doze, standby buckets, battery settings and permissions

These restrictions deserve a separate item, because unfortunately there is no way around them in code. All you can do is notice them in time and ask the user for help.

Doze. When the phone lies still and isn't charging, the system defers network access, alarms and jobs. A service won't protect you from that. One possible approach is to buffer the data and upload it to the server once the network is available again.

Standby bucket. While a Foreground Service is running, the app counts as active. But if the service has died and the app hasn't been opened for a long time, the system moves it to a stricter bucket, RESTRICTED (Android 12+), and our worker-based safety net will run rarely. You can check the bucket with UsageStatsManager.getAppStandbyBucket().

Battery optimization. An app excluded from battery optimization suffers less from Doze and can start a Foreground Service from the background. You can check this with isIgnoringBatteryOptimizations() and, if needed, open the settings for the user. Google Play allows the direct REQUEST_IGNORE_BATTERY_OPTIMIZATIONS request only for apps whose core function is broken by Doze and App Standby. For firmware with its own settings ("Never sleeping apps" on Samsung, autostart on Xiaomi), it is better to show vendor-specific instructions.

Permissions and device state. Before starting, we check everything that can silently stop the scan and tell the app exactly what is wrong. We catch Bluetooth being turned off and on via ACTION_STATE_CHANGED and restart the scan through the quota counter.

fun diagnose(ctx: Context): List<Problem> = buildList {
    if (!bluetoothEnabled()) add(BLUETOOTH_OFF)
    if (SDK_INT >= 31 && !granted(BLUETOOTH_SCAN)) add(NO_BLUETOOTH_SCAN)
    if (!granted(ACCESS_FINE_LOCATION)) add(NO_FINE_LOCATION)
    if (!granted(ACCESS_BACKGROUND_LOCATION)) add(NO_BACKGROUND_LOCATION)
    if (!locationServicesEnabled()) add(LOCATION_OFF)
    if (SDK_INT >= 33 && !granted(POST_NOTIFICATIONS)) add(NO_NOTIFICATIONS)
    if (!powerManager.isIgnoringBatteryOptimizations(ctx.packageName)) add(BATTERY_OPTIMIZED)
    if (usageStats.appStandbyBucket >= STANDBY_BUCKET_RARE) add(STANDBY_RESTRICTED)
}
Enter fullscreen mode Exit fullscreen mode

Keep in mind that every request to the user is one more setup screen and one more chance they skip it. In enterprise deployments this is often solved by configuring devices via MDM; in consumer apps, only by a really good explanation.

Conclusion

Of course, none of this is an absolute guarantee that scanning will work perfectly. With every new Android version and every new firmware, you have to find ever more creative ways to live with the restrictions. The scan timeout itself is a server-side setting and can change without a system update, and since Android 16 the Bluetooth module is updated separately from the firmware.

So the main thing we took away from this story is the habit of measuring. Things in the system rarely break loudly, and if you don't measure the stream of results, you may first hear about the problem from a customer.

On our phone, the main problem turned out to be the long-running scan timeout: after 5 minutes the system downgrades the mode, and you get 5–10 times fewer detections. The app never finds out: formally the scan is running and callbacks are coming in, just rarely.

In short, reliable background scanning needs four things:

  1. A real filter for your beacon format. An empty filter doesn't work with the screen off.
  2. Restarting the scan before the timeout, through a single start counter so you don't hit the limit.
  3. Monitoring the results stream. You can't rely on onScanFailed; if there are no results for a long time, restart the scan.
  4. A Foreground Service that brings the scan back right after a process restart, without waiting for the UI to open. Before you choose your intervals, check how long the timeout is on your devices:
adb shell device_config get bluetooth scan_timeout_millis
Enter fullscreen mode Exit fullscreen mode

We'd love it if you shared the values from your phones in the comments.

Thanks for reading!

Top comments (3)

Collapse
 
yonto profile image
Yonto Player •

Great write-up, the AOSP links are what most posts on this are missing. We hit the same wall with long downloads in our Android app: a foreground service is the floor, and then the OEM battery managers decide the rest. dontkillmyapp.com has been the most useful map of who does what. Did asking for the battery optimisation exemption make a measurable difference on the Xiaomi and Oppo devices, or do they ignore it?

Collapse
 
nedmah profile image
Denis Khamidullin •

Thank you! It partially helps with Doze and App StandBy, but Bluetooth ScanManager has it's own logic. Also on the Oppo devices there are more app management mechanisms

Collapse
 
ascendra_ventures_92c21f2 profile image
Ascendra Ventures •

The table of what each Android version took away is the useful part for me, especially the undocumented limit of five scan starts per 30 seconds and unfiltered scans being paused with the screen off since 8.1. Yonto's comment about OEM battery managers matches what most people find: the foreground service is only the floor, and your reply that the Bluetooth ScanManager keeps its own logic on top of Doze explains why the battery exemption alone was not enough.

We work with BLE from the other end at Ascendra Ventures, in a much simpler setting. When the official app for Actofit body-composition scales stopped returning the full readout, we rebuilt the experience as a web app that reads the scale through Web Bluetooth in the browser. The scale only sends two raw numbers, weight and impedance, and everything else is recomputed from the user's profile. That works because a person stands on the scale with the page open in front of them, so none of the background limits you describe come into play. Your post is a good reminder of how much harder it gets once the scan has to survive a pocket and a locked screen.

Which of the fixes made the biggest difference on the Oppo devices you mentioned in the comments?