startService static method

Future<ReceivePort?> startService({
  1. required String notificationTitle,
  2. required String notificationText,
  3. Function? callback,
})

Start the foreground service with notification.

Implementation

static Future<ReceivePort?> startService({
  required String notificationTitle,
  required String notificationText,
  Function? callback,
}) async {
  if (await isRunningService) {
    throw const ForegroundTaskException(
        'Already started. Please call this function after calling the stop function.');
  }

  if (_foregroundTaskOptions == null) {
    throw const ForegroundTaskException(
        'Not initialized. Please call this function after calling the init function.');
  }

  final receivePort = _registerPort();
  if (receivePort == null) {
    throw const ForegroundTaskException(
        'Failed to register SendPort to communicate with background isolate.');
  }

  final options = Platform.isAndroid
      ? _androidNotificationOptions?.toJson() ?? <String, dynamic>{}
      : _iosNotificationOptions?.toJson() ?? <String, dynamic>{};
  options['notificationContentTitle'] = notificationTitle;
  options['notificationContentText'] = notificationText;
  if (callback != null) {
    options.addAll(_foregroundTaskOptions!.toJson());
    options['callbackHandle'] =
        PluginUtilities.getCallbackHandle(callback)?.toRawHandle();
  }

  final bool result =
      await _methodChannel.invokeMethod('startForegroundService', options);
  if (result) {
    _printMessage('FlutterForegroundTask has started.');
    return receivePort;
  }

  return null;
}