# Permissions

> Ask for OS permissions at runtime. getRequiredPermissions() says what the active config needs; requestNextNeededPermission() and requestPermission() ask for it, one prompt per call.

Source: https://docs.getbeekon.com/start/permissions/

The manifest entries and Info.plist keys are on [Platform setup](https://docs.getbeekon.com/start/setup/). This page covers asking for the permissions at runtime.

## What each permission does

| Permission            | Importance                                                                                     | What it powers                                                                                                                                                                         | Without it                                                                                                                                                                            |
| --------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `location`            | Required                                                                                       | All tracking. Any foreground grant satisfies it.                                                                                                                                       | `start()` ends in `Stopped(PermissionDenied)`.                                                                                                                                        |
| `backgroundLocation`  | Recommended                                                                                    | Resuming tracking without your app on screen: after a stationary pause, after the OS stops the app, and (Android) after a reboot. Geofences. Android “Allow all the time”, iOS Always. | Tracking started in the foreground still runs in the background, but doesn’t come back once the OS stops it, and geofences don’t fire. [Details below](#without-background-location). |
| `activityRecognition` | Required when `detectActivity` is on; otherwise recommended or absent, depending on the config | Motion-based stationary detection, its battery savings, and `Location.activity`.                                                                                                       | Motion detection is off and `activity` is null.                                                                                                                                       |
| `notifications`       | Recommended, Android 13 and later                                                              | The foreground-service notification and [per-geofence notifications](https://docs.getbeekon.com/guide/geofencing/#per-geofence-notifications).                                                                   | The service runs, but its notification is hidden; geofence notifications don’t show.                                                                                                  |

`requestNextNeededPermission()` asks only for **required** permissions. Ask for the recommended ones yourself with `requestPermission(...)`, in particular `backgroundLocation`: the [SDK quickstart](https://docs.getbeekon.com/start/#3-request-permissions) shows both steps.

### Without background location

Tracking you start while the app is in the foreground keeps running in the background. Without the background grant:

* it doesn’t resume once the OS stops the app, on either platform;
* on Android, it doesn’t resume after a stationary pause;
* on iOS, Beekon skips the stationary pause instead, so tracking runs at full power while the device is still;
* geofences don’t fire.

## The permission doctor

`getRequiredPermissions()` returns the permissions the **current** config needs, each tagged `required` or `recommended` and marked as satisfied or not by the live OS grant. It is read-only and never prompts.

Call it after `configure(...)`. Before that, and in [Cloud](https://docs.getbeekon.com/cloud/) mode (where the server owns the config and the SDK doesn’t know it before `start()`), it returns a conservative list. Each entry is a `PermissionRequirement`:

| Field        | Type   | Meaning                                                                                                                                                                                                         |
| ------------ | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `permission` | enum   | `location`, `backgroundLocation`, `activityRecognition` or `notifications`: Beekon’s names, not the raw OS constants.                                                                                           |
| `importance` | enum   | `required`: tracking can’t start, or a feature you turned on doesn’t work, without it. `recommended`: a feature degrades and tracking continues.                                                                |
| `satisfied`  | bool   | Whether the live OS grant already covers it.                                                                                                                                                                    |
| `rationale`  | string | A sentence on why it’s needed and what degrades without it. In SDK 0.5.0 the `backgroundLocation` sentence wrongly says tracking is foreground-only without it; SDK 0.6.0 corrects it to match the table above. |

`location` and `backgroundLocation` are always listed. `activityRecognition` is listed when the config can use motion detection. `notifications` is listed on Android 13 and later, always. The iOS doctor never lists `notifications`, but per-geofence notifications on iOS still need notification authorisation: ask with `requestPermission(.notifications)`.

On Android, `satisfied` is the runtime grant. iOS has no runtime motion-permission query, so there `activityRecognition` is satisfied when `NSMotionUsageDescription` is in the Info.plist and the device has a motion coprocessor.

* Android

  ```kotlin
  // Synchronous; call after configure().
  Beekon.getRequiredPermissions().forEach { r ->
    Log.d(
      "beekon",
      "${r.permission} (${r.importance}) satisfied=${r.satisfied}: ${r.rationale}",
    )
  }
  // r.permission: BeekonPermission.Location / .BackgroundLocation /
  //               .ActivityRecognition / .Notifications
  // r.importance: PermissionImportance.Required / .Recommended
  ```

* iOS

  ```swift
  // Actor-isolated; call after configure(_:).
  for r in await Beekon.shared.getRequiredPermissions() {
    print(
      "\(r.permission) (\(r.importance)) satisfied=\(r.satisfied): \(r.rationale)"
    )
  }
  // r.permission: .location / .backgroundLocation / .activityRecognition
  //               (never .notifications on iOS)
  // r.importance: .required / .recommended
  ```

* Flutter

  ```dart
  final reqs = await Beekon.instance.getRequiredPermissions();
  for (final r in reqs) {
    print(
      '${r.permission} (${r.importance}) satisfied=${r.satisfied}: ${r.rationale}',
    );
  }
  ```

* React Native

  ```ts
  const reqs = await Beekon.getRequiredPermissions();
  reqs.forEach((r) => {
    console.log(r.permission, r.importance, r.satisfied, r.rationale);
  });
  ```

start() warns about missing permissions

On every platform, `start()` checks the list. For each required or recommended permission still missing, it writes a `warn` entry to the [`logs` stream](https://docs.getbeekon.com/guide/diagnostics/#the-log-surface) and to `exportLog()`, naming the permission and what degrades. A missing required location grant also ends tracking with `Stopped(PermissionDenied)` on the [`state` stream](https://docs.getbeekon.com/guide/lifecycle/#stop-reasons); a missing recommended permission only produces the warning. Flutter and React Native call the native `start()`, so they get the same check.

## Requesting permissions

Beekon never prompts on its own: nothing in `configure(...)`, `start()` or initialisation shows a dialog, and no call chains one prompt into the next. Each prompt is one your code triggers, after your own explanation. The request API performs the OS ask correctly on each platform. Permission libraries (`permission_handler`, `react-native-permissions` and others) work too; drive them from `getRequiredPermissions()`.

| Method                          | What it does                                                                                                                                                                                           |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `requestPermission(permission)` | Asks for one permission and returns a `PermissionRequestResult`. Never fires a prompt the OS would drop silently.                                                                                      |
| `requestNextNeededPermission()` | Asks for the first unsatisfied **required** permission in the doctor’s order and returns its result, or null (nil on iOS) when no required permission is missing. Recommended permissions are skipped. |
| `openSettings(permission)`      | Opens the closest OS settings screen. The only way forward once an outcome is `requiresSettings`.                                                                                                      |

### The onboarding flow

Render the doctor list to show what’s needed and why. On each onboarding screen, call `requestNextNeededPermission()` from a button. When it returns null, ask for `backgroundLocation` (and any other recommended permission you want) with `requestPermission(...)`, then call `start()`.

* Android

  ```kotlin
  // suspend; needs a foreground Activity.
  when (val r = Beekon.requestNextNeededPermission(activity)) {
    null -> {
      // No required permission missing. Ask for background location on its own
      // screen.
      Beekon.requestPermission(activity, BeekonPermission.BackgroundLocation)
      Beekon.start()
    }
    else -> when (r.outcome) {
      PermissionRequestOutcome.RequiresSettings ->
        Beekon.openSettings(activity, BeekonPermission.Location)
      else -> { /* show your explanation again; ask on the next tap */ }
    }
  }
  // A result also carries r.prerequisite (when Blocked), r.reason
  // (when NotAttempted) and r.status.
  ```

* iOS

  ```swift
  // Actor method; the Core Location work runs on the main actor internally.
  if let r = await Beekon.shared.requestNextNeededPermission() {
    switch r.outcome {
    case .requiresSettings: Beekon.openSettings(for: .location)
    default: break // show your explanation again; ask on the next tap
    }
  } else {
    // No required permission missing. Ask for Always on its own screen.
    _ = await Beekon.shared.requestPermission(.backgroundLocation)
    await Beekon.shared.start()
  }
  // A result also carries r.prerequisite (when .blocked), r.reason
  // (when .notAttempted) and r.status.
  ```

* Flutter

  ```dart
  final r = await Beekon.instance.requestNextNeededPermission();
  if (r == null) {
    await Beekon.instance.requestPermission(BeekonPermission.backgroundLocation);
    await Beekon.instance.start();
  } else if (r.outcome == PermissionRequestOutcome.requiresSettings) {
    await Beekon.instance.openSettings(BeekonPermission.location);
  }
  ```

* React Native

  ```ts
  const r = await Beekon.requestNextNeededPermission();
  if (r === null) {
    await Beekon.requestPermission('backgroundLocation');
    await Beekon.start();
  } else if (r.outcome === 'requiresSettings') {
    await Beekon.openSettings('location');
  }
  ```

### The result

Every request returns a `PermissionRequestResult` with four fields: `outcome`; `prerequisite`, the permission to ask for first (set only when `outcome` is `blocked`); `reason` (set only when `outcome` is `notAttempted`); and `status`, a fresh [`PermissionStatus`](https://docs.getbeekon.com/reference/api/#permission-status).

| `outcome`          | Meaning                                                                                                                                             |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `granted`          | The grant now covers the request. Includes iOS provisional Always and one-time grants; neither OS says whether a grant will last.                   |
| `denied`           | The prompt ran and the grant is still missing. The OS may allow another prompt later.                                                               |
| `requiresSettings` | The OS will not prompt again. `openSettings(...)` is the only way forward.                                                                          |
| `alreadySatisfied` | Nothing to do; the grant already covered it.                                                                                                        |
| `blocked`          | A precondition failed; `prerequisite` names the permission to ask for first (for example foreground location before background).                    |
| `notAttempted`     | The SDK did not fire a prompt that could not succeed. `reason` is `missing_manifest_entry`, `missing_plist_key`, `unsupported` or `not_foreground`. |

`PermissionRequestOutcome` may gain values in a minor release, so give every `switch` an `else` or `default` branch.

### Platform notes

* Android

  * Requests need a foreground `Activity`. Without one the result is `notAttempted` with reason `not_foreground`.
  * The permission must be in the merged manifest, or the result is `notAttempted` with `missing_manifest_entry`. `ACCESS_BACKGROUND_LOCATION` is not in Beekon’s manifest; add it yourself ([Platform setup](https://docs.getbeekon.com/start/setup/#android-permissions)).
  * A location request asks for FINE and COARSE together.
  * Background comes after foreground. Asking for background location while foreground location is missing returns `blocked` with `prerequisite = location`, because Android 11 and later deny a combined request without showing anything.
  * `notifications` can be requested only on Android 13 (API 33) and later, with a target SDK of 33 or higher; otherwise the result is `notAttempted` with `unsupported`.

* iOS

  * The upgrade to Always prompts at most once. After that, further requests show nothing and return `requiresSettings`.
  * Each request needs its Info.plist usage string (`NSLocation…UsageDescription`, or `NSMotionUsageDescription` for activity recognition). Without it the result is `notAttempted` with `missing_plist_key`. See [Info.plist](https://docs.getbeekon.com/start/setup/#ios-infoplist).
  * `requestPermission(.notifications)` uses `UNUserNotificationCenter` and checks for an earlier denial first. `Beekon.requestNotificationAuthorization()` is deprecated in favour of it and will be removed before 1.0.
  * iOS has no motion-permission request API, so `requestPermission(.activityRecognition)` triggers the one-time `CMMotionActivityManager` prompt.

* Flutter

  The plugin calls the native SDKs, so the Android and iOS notes apply unchanged. The result fields (`outcome`, `prerequisite`, `reason`, `status`) cross the bridge as they are.

* React Native

  The module calls the native SDKs, so the Android and iOS notes apply unchanged. `outcome` and `reason` arrive as strings (`'granted'`, `'requiresSettings'`, `'missing_plist_key'` and so on); handle values you don’t recognise.
