startService method
Future<bool>
startService({
- required AndroidNotificationOptions androidNotificationOptions,
- required IOSNotificationOptions iosNotificationOptions,
- required ForegroundTaskOptions foregroundTaskOptions,
- required String notificationTitle,
- required String notificationText,
- Function? callback,
override
Implementation
@override
Future<bool> startService({
required AndroidNotificationOptions androidNotificationOptions,
required IOSNotificationOptions iosNotificationOptions,
required ForegroundTaskOptions foregroundTaskOptions,
required String notificationTitle,
required String notificationText,
Function? callback,
}) async {
if (await isRunningService) {
return true;
}
// for Android 13
if (Platform.isAndroid && await attachedActivity) {
try {
final NotificationPermission notificationPermissionStatus =
await checkNotificationPermission();
if (notificationPermissionStatus != NotificationPermission.granted) {
await requestNotificationPermission();
}
} catch (_) {
//
}
}
final options = <String, dynamic>{
if (Platform.isAndroid)
...androidNotificationOptions.toJson()
else
...iosNotificationOptions.toJson(),
'notificationContentTitle': notificationTitle,
'notificationContentText': notificationText,
...foregroundTaskOptions.toJson(),
};
if (callback != null) {
options['callbackHandle'] =
PluginUtilities.getCallbackHandle(callback)?.toRawHandle();
}
final bool reqResult =
await methodChannel.invokeMethod('startService', options);
if (!reqResult) {
return false;
}
final Stopwatch stopwatch = Stopwatch()..start();
bool startState = false;
await Future.doWhile(() async {
startState = await isRunningService;
// official doc: Once the service has been created, the service must call its startForeground() method within five seconds.
// ref: https://developer.android.com/guide/components/services#StartingAService
if (startState || stopwatch.elapsedMilliseconds > 5 * 1000) {
return false;
} else {
await Future.delayed(const Duration(milliseconds: 100));
return true;
}
});
return startState;
}