> ## Documentation Index
> Fetch the complete documentation index at: https://docs.plaud.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Background Syncs

> Patterns to sync files from Plaud device to mobile app

Your users' phones may be in different states while their Plaud device syncs its audio to your mobile app - your user may lock their phone, move the app to the background, or close out of the app completely.

![screen off sync](https://mintcdn.com/plaud/pQkZPRdatcPNMcm5/assets/screen-off-sync.png?fit=max\&auto=format\&n=pQkZPRdatcPNMcm5\&q=85\&s=41f6419905bc5833a2605a6125cb7c68)

## Syncing while phone is locked/in-background

Even when your users' phone may be in the background

* User locks their phone
* User goes to the home screen
* User switches to another app

you can still run processes in the background via event-driven callbacks.

### For iOS

> [!TIP]
>
> See our [iOS Starter App](https://docs.plaud.ai/plaud-embedded/ios-starter-app.md) for a working example.

#### Prerequisites

Make sure that the `UIBackgroundModes = [bluetooth-central]` is enabled in your permission declarations.

```yaml project.yml theme={"system"}
UIBackgroundModes:
  - bluetooth-central
```

```xml Info.plist theme={"system"}
<key>UIBackgroundModes</key>
<array>
  <string>bluetooth-central</string>
</array>
```

The bluetooth permission allows the app to react to GATT events while in the background.

#### Callback-driven Syncs

Use Embedded SDK callbacks and methods to drive file exports while your app is in the background.

| Type | Method/Callback | Description | Doc Reference |
| :-: | :-: | :-: | :-: |
| Method | `.exportAudio` | Export audio file from device to mobile app | [File Sync](https://docs.plaud.ai/plaud-embedded/ios-sdk.md#file-synchronization) |
| Method | `.getFileList` | Gets files from device | [Get all files](https://docs.plaud.ai/plaud-embedded/ios-sdk.md#file-synchronization) |
| Callback | `AudioExportCallback` | Callbacks like `onError`, `onProgress`, and `onComplete` | [Export Callback](https://docs.plaud.ai/plaud-embedded/ios-sdk.md#audioexportcallback) |
| Callback | `PlaudDeviceAgentProtocol` | Device events like `bleFileList` and `bleRecordStop` | [Bluetooth drive callbacks](https://docs.plaud.ai/plaud-embedded/ios-sdk.md#plauddeviceagentprotocol) |

Use a combination of these callbacks and methods, along with recursion, to sync large files and multiple files in the background.

```swift Swift icon="Swift" expandable theme={"system"}
final class SyncManager: SyncManagerProtocol {
  //...

  func startSync() {
    PlaudDeviceAgent.shared.getFileList(startSessionId: 0)
  }

  func bleFileList(bleFiles: [BleFile]) {
    downloadNextFile()
  }

  private func downloadNextFile() {
    let next = pendingDownloads.first  
    let outputDir = RecordingStore.shared.audioDir()

    PlaudDeviceAgent.shared.exportAudio(
        sessionId: next.sessionId,
        outputDir: outputDir,
        format: .mp3,
        channels: 1,
        callback: self
    )
  }
}

extension SyncManager: AudioExportCallback {
  //...
  public func onComplete(_outputPath: String) {
    guard let sessionId = currentExportSessionId else { return }
    PlaudDeviceAgent.shared.deleteFile(sessionId: sessionId)
    downloadNextFile()
  }
}

final class DeviceManager: DeviceManagerProtocol {
  //...
  func bleRecordStop(sessionId: Int, _reason: Int, _fileExist: Bool, _fileSize: Int) {
    // Auto-sync files 1 second after recording stops
    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        SyncManager.shared.startSync()
    }
  }
}
```

### For Android

> [!TIP]
>
> See our [Android Starter App](https://docs.plaud.ai/plaud-embedded/android-starter-app.md) for a working example of the sync loop.

#### Callback-driven Syncs

Use Embedded SDK callbacks and methods to drive file exports while your app is in the background.

| Type | Method/Callback | Description | Doc Reference |
| :-: | :-: | :-: | :-: |
| Method | `.exportAudio` | Export audio file from device to mobile app | [File Sync](https://docs.plaud.ai/plaud-embedded/android-sdk.md#file-synchronization) |
| Method | `.getFileList` | Gets files from device | [Get all files](https://docs.plaud.ai/plaud-embedded/android-sdk.md#file-synchronization) |
| Callback | `AudioExporter.ExportCallback` | Callbacks like `onError`, `onProgress`, and `onComplete` | [Export Callback](https://docs.plaud.ai/plaud-embedded/android-sdk.md#audioexporterexportcallback) |
| Callback | `PlaudDeviceAgentListener` | Device events like `bleFileList` and `bleRecordStop` | [Bluetooth driven callbacks](https://docs.plaud.ai/plaud-embedded/android-sdk.md#plauddeviceagentlistener) |

```kotlin Kotlin icon="android" expandable theme={"system"}
object SyncManager {
    private val pending = ArrayDeque<Long>()

    fun startSync() {
        PlaudDeviceAgent.getFileList()
    }

    // PlaudDeviceAgentListener
    fun bleFileList(files: List<BleFile>) {
        pending.addAll(files.map { it.sessionId })
        downloadNextFile()
    }

    private fun downloadNextFile() {
        val sessionId = pending.removeFirstOrNull() ?: return

        PlaudDeviceAgent.exportAudio(
            sessionId = sessionId,
            outputDir = RecordingStore.exportDir,
            format = AudioExportFormat.MP3,
            channels = 1,
            callback = object : AudioExporter.ExportCallback {
                override fun onProgress(progress: Int, message: String) { }

                override fun onComplete(outputFile: File) {
                    PlaudDeviceAgent.deleteFile(sessionId)
                    downloadNextFile() // the queue re-arms itself here
                }

                override fun onError(error: String) {
                    downloadNextFile()
                }
            }
        )
    }
}

object RecordingManager {
    // PlaudDeviceAgentListener
    fun bleRecordStop(sessionId: Long, reason: Int, fileExist: Boolean, fileSize: Long) {
        // Auto-sync files 1 second after recording stops
        scope.launch {
            delay(1_000)
            SyncManager.startSync()
        }
    }
}
```

## App Wakeup when Plaud is in-range

> [!WARNING]
>
> This is currently an **iOS app-only feature**, leveraging the iPhone's native iBeacon feature.
>
> It also requires:
>
> 1. **SDK 1.0.15+**
> 2. The user's **Always** location permission
> 3. **Note Pro with firmware 1.7.0+**.
>
> This feature may come to NotePin S at a later date.

### Requirements

Add location services to your list of permissions in `Info.plist`.

```xml theme={"system"}
<key>UIBackgroundModes</key>
<array>
    <string>bluetooth-central</string>
    <string>location</string>        <!-- required: the SDK asserts at runtime without it -->
</array>
<key>NSLocationWhenInUseUsageDescription</key>
<string>…</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>…explain that the app is woken when your recorder is nearby…</string>
```

### Setting up iBeacon

Activate monitoring on the phone and register the user's paired devices by serial number. Do this in `application(_:didFinishLaunchingWithOptions:)`:

```swift Swift icon="swift" theme={"system"}
PlaudDeviceAgent.shared.delegate = myDeviceDelegate
PlaudDeviceAgent.shared.activateBeaconMonitoring()       // synchronous
PlaudDeviceAgent.shared.updateBeaconMonitoredDevices(serialNumbers: pairedSerialNumbers)
```

Then turn iBeacon on in the Plaud device itself.

```swift Swift icon="swift" theme={"system"}
let agent = PlaudDeviceAgent.shared
if agent.isBeaconLocationAlwaysGranted {
    agent.setIBeaconWakeupEnabled(value: 1)
} else if agent.canRequestBeaconLocationAlwaysUpgrade {
    agent.requestBeaconLocationAlwaysPermission { granted in
        DispatchQueue.main.async {
            if granted { agent.setIBeaconWakeupEnabled(value: 1) } else { /* toggle off */ }
        }
    }
} 
```

### Using iBeacon

Now that you've setup iBeacon on your users' phone and their Plaud device, when their Plaud device comes back in range, your app receives `bleIBeaconWakeupTriggered(sn:)`.

The SDK does **not** reconnect on its own, so we also call `connectBySN`:

The connection result comes back through the usual `bleConnectState` / `bleBind` callbacks. If your app is in the background, nothing in your UI is running to start the file sync after the reconnect, so set a flag when the wake-up fires and start the sync from `bleBind` once the handshake completes:

```swift Swift icon="swift" expandable theme={"system"}
final class DeviceManager: PlaudDeviceAgentProtocol {
  private var pendingBeaconWakeupSync = false

  func bleIBeaconWakeupTriggered(sn: String) {
      pendingBeaconWakeupSync = true
      PlaudDeviceAgent.shared.connectBySN(sn)
  }

  func bleBind(sn: String?, status: Int, protVersion: Int, timezone: Int) {
      guard status == 0, sn != nil else { return }
      startBeaconWakeupSync()
  }

  private func startBeaconWakeupSync() {
      guard pendingBeaconWakeupSync else { return }
      DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
          SyncManager.shared.startSync()
      }
  }
}
```

From there, the [callback-driven sync loop](#callback-driven-syncs) above exports each file in turn.

> [!NOTE]
>
> For the full docs on iBeacon, go to our [iOS SDK Reference](https://docs.plaud.ai/plaud-embedded/ios-sdk.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.