# SDK quickstart

> Install Beekon, ask for location permissions including background, and receive your first location on Android, iOS, Flutter and React Native.

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

This page takes you from an empty app to your first locations in five steps: install, configure, request permissions, start, subscribe. Pick your platform once; the tabs stay in sync across the site.

Beekon never prompts on its own

Nothing in `configure`, `start` or the SDK’s initialisation shows a permission dialog. Your app decides when to ask, with the SDK’s [request API](https://docs.getbeekon.com/start/permissions/#requesting-permissions) or your own permission code. The OS declarations (manifest entries, Info.plist keys) are on [Platform setup](https://docs.getbeekon.com/start/setup/).

## 1. Install

* Android

  app/build.gradle.kts

  ```kotlin
  dependencies {
    implementation("io.github.beekonlabs:beekon:0.6.0")
  }
  ```

  Android 8.0 (API 26) or later, `compileSdk = 36` or higher, JDK 17, Kotlin 2.x. The package is on Maven Central, which Gradle includes by default.

* iOS

  In Xcode, choose **File → Add Package Dependencies…** and enter:

  ```plaintext
  https://github.com/beekonlabs/beekon-ios-binary.git
  ```

  Select version `0.6.0`, add `BeekonKit` to your app target and set it to **Embed & Sign**. iOS 15 or later; on iOS 17 and later the SDK uses the `CLLocationUpdate` stack automatically.

* Flutter

  pubspec.yaml

  ```yaml
  dependencies:
    beekon_flutter: ^0.6.0
  ```

  ```sh
  flutter pub get
  ```

  Flutter 3.35 or later (Dart 3.9). Android 8.0 (API 26) or later with `compileSdk` 36 or higher, iOS 17 or later.

* React Native

  ```sh
  npm install @wayq/beekon-rn@0.6.0
  cd ios && pod install
  ```

  React Native 0.76 or later with the New Architecture. Android 8.0 (API 26) or later with `compileSdk` 36 or higher, iOS 17 or later. Android links automatically.

## 2. Configure

`configure` sets the [gate](https://docs.getbeekon.com/start/configuration/#the-gate): the minimum time and distance between stored locations. It is optional. Without it, Beekon uses 30 s and 100 m, balanced accuracy, and pauses while the device is still. Every field is on [Configuration](https://docs.getbeekon.com/start/configuration/).

* Android

  The SDK initialises itself through AndroidX Startup. Call `configure` once in `Application.onCreate`, and register the class with `android:name=".App"` on the `<application>` element of your manifest.

  ```kotlin
  import android.app.Application
  import com.getbeekon.sdk.AccuracyMode
  import com.getbeekon.sdk.Beekon
  import com.getbeekon.sdk.BeekonConfig
  import com.getbeekon.sdk.NotificationConfig
  import com.getbeekon.sdk.StationaryMode
  import com.getbeekon.sdk.TrackingConfig
  import kotlinx.coroutines.MainScope
  import kotlinx.coroutines.launch


  class App : Application() {
    override fun onCreate() {
      super.onCreate()
      Beekon.configure(
        BeekonConfig.Local(
          tracking = TrackingConfig(
            minTimeBetweenLocationsSeconds = 30,
            minDistanceBetweenLocationsMeters = 100.0,
            accuracyMode = AccuracyMode.Balanced,
            whenStationary = StationaryMode.Pause,
          ),
          notification = NotificationConfig(
            title = "Tracking location",
            text = "Capturing your trip",
          ),
        ),
      )
      // Resumes a session that was running when Android killed the process.
      MainScope().launch { Beekon.resumeIfNeeded() } // suspend; never throws
    }
  }
  ```

  `NotificationConfig` is the text of the foreground-service notification Android shows while tracking. Its title defaults to “Tracking location”. `resumeIfNeeded()` does nothing unless a session was running when the process died; see [Cold-launch resume](https://docs.getbeekon.com/guide/background/#cold-launch-resume).

* iOS

  `Beekon.shared` is an actor and needs no initialisation. Two things happen at launch:

  * `Beekon.registerBackgroundTasks()`, once and synchronously, before launch finishes. It registers the background task that runs sync and check-ins. iOS ignores a registration made later.
  * `configure`, which is `async throws`. Await it before you call `start()`.

  ```swift
  import BeekonKit
  import SwiftUI


  @main
  struct MyApp: App {
    init() {
      Beekon.registerBackgroundTasks() // synchronous; must run during launch
    }


    var body: some Scene {
      WindowGroup {
        ContentView()
          .task {
            do {
              try await Beekon.shared.configure(
                BeekonConfig.local(
                  tracking: TrackingConfig(
                    minTimeBetweenLocationsSeconds: 30,
                    minDistanceBetweenLocationsMeters: 100,
                    accuracyMode: .balanced,
                    whenStationary: .pause
                  )
                )
              )
            } catch {
              print("Beekon configure failed: \(error)")
            }
          }
      }
    }
  }
  ```

  If your app uses a `UIApplicationDelegate` instead of the SwiftUI `App` lifecycle, call both from `application(_:didFinishLaunchingWithOptions:)`: `registerBackgroundTasks()` directly, `configure` inside a `Task`. The SDK resumes an interrupted session by itself on iOS.

* Flutter

  The native SDKs initialise themselves, and the plugin registers the iOS background task for you. `configure` is async.

  ```dart
  import 'package:beekon_flutter/beekon_flutter.dart';
  import 'package:flutter/widgets.dart';


  Future<void> main() async {
    WidgetsFlutterBinding.ensureInitialized(); // platform channels before runApp
    await Beekon.instance.configure(
      BeekonConfig.local(
        tracking: const TrackingConfig(
          minTimeBetweenLocationsSeconds: 30,
          minDistanceBetweenLocationsMeters: 100,
          accuracyMode: AccuracyMode.balanced,
          whenStationary: StationaryMode.pause,
        ),
      ),
    );
    await Beekon.instance.resumeIfNeeded(); // resumes a session the OS killed
    runApp(const MyApp());
  }
  ```

  `resumeIfNeeded()` does nothing unless a session was running when the app was killed. See [Cold-launch resume](https://docs.getbeekon.com/guide/background/#cold-launch-resume).

* React Native

  The native SDKs initialise themselves. `configure` is async. The React Native samples on this site use top-level `await` for brevity; run them inside an async function such as your startup code.

  ```ts
  import { Beekon } from '@wayq/beekon-rn';


  await Beekon.configure({
    mode: 'local',
    tracking: {
      minTimeBetweenLocationsSeconds: 30,
      minDistanceBetweenLocationsMeters: 100,
      accuracyMode: 'balanced',
      whenStationary: 'pause',
    },
  });
  await Beekon.resumeIfNeeded(); // resumes a session the OS killed
  ```

  On iOS, also register the background task in `AppDelegate.swift`, inside `application(_:didFinishLaunchingWithOptions:)`:

  ```swift
  import BeekonRn


  BeekonRnImpl.registerBackgroundTasks()
  ```

## 3. Request permissions

Add the OS declarations from [Platform setup](https://docs.getbeekon.com/start/setup/) first. On Android that is `ACCESS_BACKGROUND_LOCATION` in your manifest; on iOS it is the two location usage strings, the `location` and `fetch` background modes and the background task identifier.

Then ask at runtime, in two steps:

1. **Foreground location.** `requestNextNeededPermission()` asks for the first missing **required** permission, one OS prompt per call, and returns null (nil on iOS) when none is left. For a typical config the only required permission is foreground location.
2. **Background location.** Ask for it yourself with `requestPermission(backgroundLocation)` after foreground location is granted: it is **recommended**, not required, so `requestNextNeededPermission()` never asks for it. It lets tracking resume after the OS stops your app and powers geofences. Without it, tracking you start in the foreground still runs in the background but doesn’t come back once the OS stops your app; the details are on [Permissions](https://docs.getbeekon.com/start/permissions/#what-each-permission-does).

Call each from a button in your onboarding, after your own explanation of why the app needs it.

* Android

  ```kotlin
  import com.getbeekon.sdk.BeekonPermission


  // In an Activity; both calls need the Activity in the foreground.
  lifecycleScope.launch {
    // 1. Foreground location (null when nothing required is missing).
    Beekon.requestNextNeededPermission(this@MainActivity)


    // 2. Background location, on a later screen. On Android 11 and later
    //    this opens the system page where the user picks "Allow all the time".
    Beekon.requestPermission(this@MainActivity, BeekonPermission.BackgroundLocation)
  }
  ```

* iOS

  ```swift
  // 1. Foreground location: the When In Use prompt
  //    (nil when nothing required is missing).
  _ = await Beekon.shared.requestNextNeededPermission()


  // 2. Background location, on a later screen: the one-time upgrade to Always.
  _ = await Beekon.shared.requestPermission(.backgroundLocation)
  ```

* Flutter

  ```dart
  // 1. Foreground location (null when nothing required is missing).
  await Beekon.instance.requestNextNeededPermission();


  // 2. Background location, on a later screen.
  await Beekon.instance.requestPermission(BeekonPermission.backgroundLocation);
  ```

* React Native

  ```ts
  // 1. Foreground location (null when nothing required is missing).
  await Beekon.requestNextNeededPermission();


  // 2. Background location, on a later screen.
  await Beekon.requestPermission('backgroundLocation');
  ```

Each call returns a result whose `outcome` says what happened. When it is `requiresSettings`, the OS will not prompt again: call `openSettings(...)` to send the user to the app’s settings. Every outcome, and the other recommended permissions (activity recognition, notifications), are on [Permissions](https://docs.getbeekon.com/start/permissions/#requesting-permissions).

## 4. Start tracking

`start()` brings up the platform’s background machinery: a foreground service on Android, a `CLBackgroundActivitySession` on iOS. It never throws. A missing permission or a refusal from the OS shows up as `Stopped(reason)` on the `state` stream.

* Android

  ```kotlin
  lifecycleScope.launch {
    Beekon.start() // suspend; never throws
  }
  ```

* iOS

  ```swift
  await Beekon.shared.start() // never throws
  ```

* Flutter

  ```dart
  await Beekon.instance.start(); // never throws
  ```

* React Native

  ```ts
  await Beekon.start(); // never throws
  ```

## 5. Subscribe to locations

The `locations` stream delivers each location that passes the gate. The `state` stream tells you when tracking stops and why.

* Android

  ```kotlin
  import android.util.Log
  import androidx.lifecycle.lifecycleScope
  import com.getbeekon.sdk.Beekon
  import com.getbeekon.sdk.BeekonState
  import com.getbeekon.sdk.StopReason
  import kotlinx.coroutines.launch


  // In an Activity. collect never returns, so each stream gets its own coroutine.
  // locations is a SharedFlow: no replay, a 64-item buffer, oldest dropped first.
  lifecycleScope.launch {
    Beekon.locations.collect { loc ->
      Log.d(
        "beekon",
        "${loc.latitude}, ${loc.longitude}  acc=${loc.accuracy ?: "?"} m",
      )
    }
  }


  lifecycleScope.launch {
    Beekon.state.collect { s ->
      if (s is BeekonState.Stopped) when (s.reason) {
        StopReason.PermissionDenied -> { /* ask for location, then start() again */ }
        StopReason.LocationServicesDisabled -> {
          /* Location is off in system settings */
        }
        else -> {}
      }
    }
  }
  ```

* iOS

  ```swift
  Task {
    for await loc in await Beekon.shared.locations {
      let acc = loc.accuracy.map { "\($0)" } ?? "?"
      print("\(loc.latitude), \(loc.longitude)  acc=\(acc) m")
    }
  }


  Task {
    for await s in await Beekon.shared.state {
      if case let .stopped(reason) = s {
        switch reason {
        case .permissionDenied: break // ask for location, then start() again
        case .locationServicesDisabled: break // Location Services are off
        default: break
        }
      }
    }
  }
  ```

* Flutter

  ```dart
  // Each stream is a Dart Stream. Call cancel() on the subscription to stop
  // listening.
  final locationSub = Beekon.instance.locations.listen((loc) {
    print('${loc.latitude}, ${loc.longitude}');
  });


  final stateSub = Beekon.instance.state.listen((state) {
    if (state is Stopped && state.reason == StopReason.permissionDenied) {
      // Ask for location, then start() again.
    }
  });
  ```

* React Native

  ```ts
  // Each subscription returns a function that unsubscribes.
  const offLocation = Beekon.onLocation((loc) => {
    console.log(loc.latitude, loc.longitude);
  });


  const offState = Beekon.onState((state) => {
    if (state.kind === 'stopped' && state.reason === 'permissionDenied') {
      // Ask for location, then start() again.
    }
  });
  ```

Every location is also written to an on-device SQLite history that survives process death. Read a time range with `getLocations(from, to)`; see [Locations & history](https://docs.getbeekon.com/guide/locations/).

## Next steps

1. Send locations to a backend: your own server with [Turn on sync](https://docs.getbeekon.com/guide/sync/), or [Beekon Cloud](https://docs.getbeekon.com/cloud/) with [Cloud mode](https://docs.getbeekon.com/start/configuration/#cloud-mode).
2. Finish the OS declarations on [Platform setup](https://docs.getbeekon.com/start/setup/), so tracking keeps running in the background.
3. Tune the gate and accuracy on [Configuration](https://docs.getbeekon.com/start/configuration/).
4. Learn the state machine behind `state` on [Lifecycle & states](https://docs.getbeekon.com/guide/lifecycle/).

A licence key is optional; if you have one, see [Licensing](https://docs.getbeekon.com/reference/licensing/).
