# Background execution

> How Beekon keeps tracking in the background on Android and iOS, and what each platform needs from your app.

Source: https://docs.getbeekon.com/guide/background/

The state machine, the gate and the stored schema are the same on every platform. The OS mechanics that keep an app running in the background are not. This page explains what Beekon uses on each platform, so you can tell what went wrong when background tracking stops.

## Android

Beekon runs a foreground service of type `location` (`FOREGROUND_SERVICE_LOCATION` on Android 14+). The service hosts the `FusedLocationProviderClient` subscription and keeps the app process runnable while tracking. It returns `START_STICKY`: if the OS kills it under memory pressure, Android restarts it, and Beekon reads the saved session from disk and continues (or stops, if no session was running).

| Mechanism                            | Role                                                                                                |
| ------------------------------------ | --------------------------------------------------------------------------------------------------- |
| `FusedLocationProviderClient`        | The location source. Fuses GPS, Wi-Fi, cell and sensor signals.                                     |
| Foreground service and notification  | Meets the Android 8+ background-location rules. Visible to the user.                                |
| `FOREGROUND_SERVICE_LOCATION` type   | Required on Android 14+ to start a location foreground service.                                     |
| `SharedPreferences` (`beekon_prefs`) | Saves the tracking intent and session so a restarted service, a cold launch or a reboot can resume. |

The foreground notification is required by Android, not by Beekon. The channel id and notification id are SDK-internal constants. The title, text and status-bar icon are set with `NotificationConfig`: see [Configuration](https://docs.getbeekon.com/start/configuration/#notificationconfig).

### Cold-launch resume

Android has no equivalent of the iOS Significant Location Change wake, so after process death your app resumes the session. Call `Beekon.resumeIfNeeded()` from `Application.onCreate`. It adopts the saved `BeekonConfig`, re-arms the gate, and resumes only when a session was running and not stopped. A session the user stopped stays stopped.

```kotlin
import android.app.Application
import com.getbeekon.sdk.Beekon
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch


class App : Application() {
  override fun onCreate() {
    super.onCreate()
    MainScope().launch { Beekon.resumeIfNeeded() } // suspend; never throws
  }
}
```

Reboots and app updates are handled by the SDK. Beekon’s library manifest registers a receiver for `BOOT_COMPLETED` and `MY_PACKAGE_REPLACED`. It restarts the foreground service for a session that was active and re-arms the saved geofences. The restart needs `ACCESS_BACKGROUND_LOCATION`. Without it, the receiver skips the start and keeps the session for a later resume. To opt out of boot survival, remove the receiver in your app manifest (with `xmlns:tools` declared):

```xml
<receiver
    android:name="com.getbeekon.sdk.internal.receiver.BootCompletedReceiver"
    tools:node="remove" />
```

On Flutter and React Native, call `resumeIfNeeded()` early in startup (`main()` in Flutter, your app entry in React Native). A background relaunch on Android may not start the Dart or JS engine. If you need resume in that case, also call the native `Beekon.resumeIfNeeded()` from `Application.onCreate`.

### What can still stop the service

Battery managers on some devices (Xiaomi, Huawei, Samsung, OPPO, Vivo and others) kill foreground services. The [dontkillmyapp.com](https://dontkillmyapp.com) matrix lists the per-manufacturer settings, such as auto-start allow-lists and battery-optimisation exemptions. Show those instructions in your onboarding on affected devices. When the service is killed for good, the state becomes `Stopped(System)`, and your app calls `start()` again when it suits.

On Android 12+, the OS can refuse a foreground-service start when the process was woken in the background (for example, by the SDK’s own upload worker). Beekon then moves to `Stopped(BackgroundStartDenied)` and keeps the saved session. The next `start()` or `resumeIfNeeded()`, usually when the user opens the app, recovers it in full. A refused background start never deletes a session.

### Doze and App Standby

Doze (device idle) and App Standby (per-app idle) reduce how often backgrounded apps wake. The foreground service exempts the app from most of this, but not all: expect fewer updates during deep Doze. Because the gate admits locations by time and distance, those periods record fewer locations; the trip is not cut.

## iOS

On iOS, background execution depends on whether the app process is alive at all. On iOS 17+, Beekon uses one code path:

```plaintext
CLLocationUpdate.liveUpdates(.default)
+ CLBackgroundActivitySession               // keeps background delivery alive
+ CLServiceSession(authorization: .always)  // iOS 18+ only, declared-authorization
```

`CLLocationUpdate.liveUpdates` is the async sequence that replaces the Core Location delegate. `CLBackgroundActivitySession` keeps it delivering in the background. The configuration is fixed at `CLLocationUpdate.LiveConfiguration.default`, because Apple does not expose power-profile tuning. Beekon’s time and distance gate sets the rate.

On iOS 15 and 16, where those APIs don’t exist, Beekon runs a legacy engine on `CLLocationManager` standard location updates, with `CLCircularRegion` geofencing. There, the two pause [stationary modes](https://docs.getbeekon.com/start/configuration/#enums) turn on Core Motion automatically to detect stillness. `activity` on each location stays `null` unless you set `detectActivity`.

### Significant Location Change

Beekon runs a Significant Location Change (SLC) monitor alongside `liveUpdates`. SLC is the only mechanism that wakes a terminated iOS app on coarse movement; `liveUpdates` does not.

When SLC wakes your app into a new process, Beekon resumes by itself:

1. At launch, the SDK observes `UIApplication.didFinishLaunchingNotification` and calls `resumeIfNeeded()`. It calls it again each time the app becomes active. No host code is needed. Calling `await Beekon.shared.resumeIfNeeded()` yourself (from `.task {}` or `application(_:didFinishLaunchingWithOptions:)`) does no harm.
2. Beekon reads the saved tracking intent from a `UserDefaults` suite (`com.getbeekon.sdk`). If the user called `stop()`, there is no intent and nothing resumes. Saved geofences are re-armed either way.
3. The new process has a new `state` stream. Subscribe again; the latest state replays.

If the user force-quits the app, iOS turns SLC off until the app is next opened. Beekon can’t change that.

### Background tasks

Background sync and the `pauseWithCheckIns` check-ins run as a `BGAppRefreshTask`. It needs the `fetch` background mode, the `com.getbeekon.sdk.sync` identifier and a synchronous `Beekon.registerBackgroundTasks()` call during launch (not from a `Task`), all listed on [iOS: background tasks](https://docs.getbeekon.com/start/setup/#ios-background-tasks). If the handler was never registered, `start()` logs a warning on the [`logs` stream](https://docs.getbeekon.com/guide/diagnostics/#the-log-surface).

`BGAppRefreshTask` is opportunistic. iOS decides when to grant a refresh window, based on how often the app is used, the battery and Low Power Mode. Expect anything from about every 15 minutes for a frequently used app to hours, or no runs at all, for a rarely used one. Foreground use and location tracking are not affected.

### Authorisation

Tracking that you start while your app is in the foreground keeps running in the background with `WhenInUse` authorisation and the `location` background mode. `Always` adds what needs iOS to wake or relaunch your app:

* resuming after a stationary pause;
* the significant-change relaunch described above;
* geofences.

With `WhenInUse` only, Beekon skips the stationary pause, so tracking keeps running at full power while the device is still.

iOS grants `Always` in two steps, and Beekon never prompts by itself. Request `.location` (When In Use) first, for example with `requestNextNeededPermission()`, then call `requestPermission(.backgroundLocation)` for the one-time upgrade to `Always`. `requestNextNeededPermission()` asks only for required permissions, so it never asks for `Always`. If you ask for `Always` first, iOS shows the `WhenInUse` prompt and offers the upgrade later, once. See [Requesting permissions](https://docs.getbeekon.com/start/permissions/#requesting-permissions), or [Platform setup](https://docs.getbeekon.com/start/setup/#ios-authorisation-flow) to drive Core Location yourself.

The location background mode is required

Add `location` to `UIBackgroundModes` in `Info.plist`. Without it, iOS does not deliver background locations to your app, whatever the authorisation.

## Testing on a device

Verify background behaviour with a 30–60 minute walk on a real device with the app in the background. Emulators and simulators do not reproduce Doze or SLC.
