Whenever I am trying to launch background service from a separate class then it doesn’t work at all, nothing happens. However when I include all the methods under void main()
in main.dart
file and in main use await initializeService();
then it works. Why I can’t launch this from an external class that I have created? I don’t want to keep all the methods in the main file because it’s getting messy. Am I doing something wrong? I am using this library https://pub.dev/packages/flutter_background_service
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await BackgroundService().initializeService();
child: const MyApp()));
}
class BackgroundService {
Future<void> initializeService() async {
final service = FlutterBackgroundService();
await service.configure(
androidConfiguration: AndroidConfiguration(
// this will executed when app is in foreground or background in separated isolate
onStart: onStart,
// auto start service
autoStart: true,
isForegroundMode: true,
),
iosConfiguration: IosConfiguration(
// auto start service
autoStart: true,
// this will executed when app is in foreground in separated isolate
onForeground: onStart,
// you have to enable background fetch capability on xcode project
onBackground: onIosBackground,
),
);
}
// to ensure this executed
// run app from xcode, then from xcode menu, select Simulate Background Fetch
void onIosBackground() {
WidgetsFlutterBinding.ensureInitialized();
print('FLUTTER BACKGROUND FETCH');
}
void onStart() {
WidgetsFlutterBinding.ensureInitialized();
final service = FlutterBackgroundService();
service.onDataReceived.listen((event) {
if (event!["action"] == "setAsForeground") {
service.setForegroundMode(true);
return;
}
if (event["action"] == "setAsBackground") {
service.setForegroundMode(false);
}
if (event["action"] == "stopService") {
service.stopBackgroundService();
}
});
// bring to foreground
service.setForegroundMode(true);
Timer.periodic(const Duration(seconds: 3), (timer) async {
if (!(await service.isServiceRunning())) timer.cancel();
service.setNotificationInfo(
title: "My App Service",
content: "Updated at ${DateTime.now()}",
);
print("Hello");
service.sendData(
{
"current_date": DateTime.now().toIso8601String(),
// "device": device,
},
);
});
}
}
Make all functions static in backgroundservice class
Call it like this in your main
Background Service Code