configure method

Future<void> configure([
  1. LocationService? configuration
])

Configures the LocationManager, incl. sending a notification to the Android notification system.

Configuration is done based on the LocationService. If not provided, as set of default configurations are used.

Implementation

Future<void> configure([LocationService? configuration]) async {
  // fast out if already enabled or is in the process of configuring
  if (enabled) return;
  if (_configuring) return;

  _configuring = true;
  info('Configuring $runtimeType - configuration: $configuration');

  _enabled = false;

  bool serviceEnabled = await locationManager.serviceEnabled();
  if (!serviceEnabled) {
    serviceEnabled = await locationManager.requestService();
    if (!serviceEnabled) {
      warning('$runtimeType - Location service could not be enabled.');
      return;
    }
  }

  if (await locationManager.hasPermission() !=
      location.PermissionStatus.granted) {
    warning(
        "$runtimeType - Permission to collect location data 'Always' in the background has not been granted. "
        "Make sure to grant this BEFORE sensing is resumed. "
        "The context sampling package does not handle permissions. This should be handled on the application level.");
    _configuring = false;
    return;
  }

  try {
    await locationManager.changeSettings(
      accuracy: location.LocationAccuracy.values[
          configuration?.accuracy.index ??
              GeolocationAccuracy.balanced.index],
      distanceFilter: configuration?.distance ?? 0,
      interval: configuration?.interval.inMilliseconds ?? 1000,
    );

    await locationManager.changeNotificationOptions(
      title: configuration?.notificationTitle ?? 'CARP Location Service',
      subtitle: configuration?.notificationMessage ??
          'The location service is running in the background',
      description: configuration?.notificationDescription ??
          'Background location is on to keep the app up-to-date with your location. '
              'This is required for main features to work properly when the app is not in use.',
      onTapBringToFront: false,
    );
  } catch (error) {
    warning('$runtimeType - Configuration failed - $error');
    return;
  }

  _enabled = true;

  bool backgroundMode = false;
  try {
    backgroundMode = await locationManager.enableBackgroundMode();
  } catch (error) {
    warning('$runtimeType - Could not enable background mode - $error');
  }
  info('$runtimeType - configured, background mode enabled: $backgroundMode');
}