The service never starts. I am lost can you help? Here is the code:
// The callback function should always be a top-level function.
@pragma('vm:entry-point')
void startCallback() {
// The setTaskHandler function must be called to handle the task in the background.
FlutterForegroundTask.setTaskHandler(FirstTaskHandler());
}
WebSocketChannel? _channel;
class FirstTaskHandler extends TaskHandler {
Timer? _timer;
@override
void onStart(DateTime timestamp, SendPort? sendPort) async {
// Start sending ping messages periodically
_timer = Timer.periodic(Duration(seconds: 15), (Timer t) async {
try {
_channel!.sink.add(jsonEncode({'type': 'ping'})); // Send a ping message
print('pinging');
} catch (e) {
//there is a problem so we abort
}
});
}
@override
void onRepeatEvent(DateTime timestamp, SendPort? sendPort) async {}
@override
void onDestroy(DateTime timestamp, SendPort? sendPort) async {
_timer?.cancel();
}
}
in the custom _init function I call:
WidgetsBinding.instance.addPostFrameCallback((_) async {
await _requestPermissionForAndroid();
await _startForegroundTask();
});
Future<void> _startForegroundTask() async {
FlutterForegroundTask.init(
androidNotificationOptions: AndroidNotificationOptions(
channelId: 'channel_id',
channelName: 'Foreground Service',
channelDescription:
'This notification appears when the foreground service is running.',
channelImportance: NotificationChannelImportance.LOW,
priority: NotificationPriority.LOW,
iconData: NotificationIconData(
resType: ResourceType.mipmap,
resPrefix: ResourcePrefix.ic,
name: 'launcher',
),
),
iosNotificationOptions: const IOSNotificationOptions(
showNotification: true,
playSound: false,
),
foregroundTaskOptions: const ForegroundTaskOptions(
interval: 5000,
autoRunOnBoot: true,
allowWifiLock: true,
),
);
await FlutterForegroundTask.startService(
notificationTitle: 'Foreground service is running',
notificationText: 'Tap to return to the app',
callback: startCallback,
);
}
I have the permission added on android manifest.
Finally my main widget is wrapped: return WithForegroundTask( child: Scaffold(
The service never starts. I am lost can you help? Here is the code:
in the custom _init function I call:
I have the permission added on android manifest. Finally my main widget is wrapped:
return WithForegroundTask( child: Scaffold(