enableBackgroundSync function

Future<bool> enableBackgroundSync()

Experimental API On iOS, this method is a no-op returning true. iOS HealthKit Background Delivery is an app-level entitlement, and does not require explicit user consent.

If you intend to pause or unpause synchronization, use pauseSynchronization and setPauseSynchronization(_:) instead.

Overview

Enable background sync on Android. This includes requesting permissions from the end user whenever necessary.

Vital SDK achieves automatic data sync through Android AlarmManager exact alarms.

Refer to the Vital Health Connect guide for full context and setup instructions.

Gist on Exact Alarms

"Exact Alarm" here refers to the Android Exact Alarm mechanism. The Vital SDK would propose to the Android OS to fire the next data sync with a T+60min wall clock target. The Android OS may fulfill the request exactly as proposed, e.g., when the user happens to be actively using the device. However, it may also choose to defer it arbitrarily, under the influence of power-saving policies like Doze mode.

On Android 12 (API Level 31) or above, this contract would automatically initiate the OS-required user consent flow for Exact Alarm usage. If the permission has been granted prior, this activity contract shall return synchronously.

On Android 13 (API Level 33) or above, you have the option to use (with platform policy caveats) the android.Manifest.permission.USE_EXACT_ALARM permission instead, which does not require an explicit consent flow. This contract would return synchronously in this scenario.

Regardless of API Level, your App Manifest must declare android.Manifest.permission.RECEIVE_BOOT_COMPLETED. Otherwise, background sync stops once the phone encounters a cold reboot or a quick restart.

@return true if the background sync has been enabled successfully. false otherwise.

Implementation

Future<bool> enableBackgroundSync() async {
  if (!Platform.isAndroid) {
    // iOS background delivery does not require user explicit consent.
    // It requires only the app-level HealthKit Bgnd. Delivery entitlement.
    return true;
  }

  return await VitalHealthPlatform.instance.enableBackgroundSync();
}