initialize method

Future<bool> initialize({
  1. String? notificationTitle,
  2. String? notificationText,
})

Initialize the background service.

On Android, this will initialize the background service with the provided notification title and text. If not provided, default English titles and text will be used. If you want to use localized titles and text, you can provide them here.

On iOS, this will do nothing as background services are not supported.

Returns true if the background service was successfully initialized, false otherwise.

Implementation

Future<bool> initialize({
  String? notificationTitle,
  String? notificationText,
}) async {
  if (Platform.isIOS) {
    warning('$runtimeType - Background services are not supported on iOS.');
    return false;
  }
  if (_initialized) {
    warning('$runtimeType - Background service is already initialized');
    return true;
  }
  info('Initializing background service...');

  final config = FlutterBackgroundAndroidConfig(
    notificationTitle: notificationTitle ?? "CARP Mobile Sensing",
    notificationText:
        notificationText ?? "Data sampling will be running in the background",
    notificationImportance: AndroidNotificationImportance.normal,
  );

  // Initialize the background service with the provided configuration.
  // This has to be done twice due to a quirk in the flutter_background package.
  // See issue #56 in the flutter_background package for more information.

  // First attempt will open the "Stop Battery Optimization" dialog on Android,
  // which is required to allow the app to run in the background.
  _initialized = await FlutterBackground.initialize(androidConfig: config);
  bool backgroundPermissions = await FlutterBackground.hasPermissions;

  // Second attempt will actually initialize the background service if permissions were granted.
  if (!_initialized && backgroundPermissions) {
    _initialized = await FlutterBackground.initialize(androidConfig: config);
  }

  if (!_initialized) {
    warning('$runtimeType - Failed to initialize background service');
  }
  debug('$runtimeType - Background service initialized: $_initialized');
  return _initialized;
}