Background Services in Flutter

When it comes to creating background services in Flutter, there are a few plugins and packages that make sure our app is operating in the background, such as Work manager. There are also other packages that call native side services to run Dart code in the background. Today, though, we’re going to use a plugin called flutter_background_service.

Therefore, only the iOS platform requires certain setups; the Android operating system does not need these permissions.

Plug-in usage

Initialize this plugin as follows at beginning

final service = FlutterBackgroundService();

For code clarity, it is preferable to work using functions.

I wrote the initializeBackgroundService() async{} function.

Once initialised:

Configure Android and iOS as shown below.

await service.configure(
 androidConfiguration: AndroidConfiguration(
onStart: onStart,
 autoStart: true,
 isForegroundMode: true,
 ),
 iosConfiguration: IosConfiguration(
 autoStart: true,
 onForeground: onStart,
 onBackground: onIosBackground,
 ),
 );
 service.startService();

We are still left with defining “onStart” and “onIosBackground” in the aforementioned code snippet.

onStart(ServiceInstance service) async {
DartPluginRegistrant.ensureInitialized();
if (service is AndroidServiceInstance) {
    service.on('setForgorund').listen((event) {
      service.setAsForegroundService();
    });
service.on('setBackground').listen((event) {
      service.setAsBackgroundService();
    });
  }
service.on('stopService').listen((event) {
    service.stopSelf();
  });

A parameter named ServiceInstance (an abstract class that implements Observables) is needed for the onStart function (interface)

The next step is to launch the DartPluginRegistrant.

There are also functions that use native side services to use foreground, background, and stop, respectively.

Now that the fundamental concept is clear, only a short section of code is left.

Timer.periodic(const Duration(seconds: 10), (timer) async {
  if (service is AndroidServiceInstance) {
service.setForegroundNotificationInfo(
      title: "Background Service",
      content: "Preparing",
    );
  }
  service.invoke(
    'update',
    {
      "current_date": DateTime.now().toIso8601String(),
    },
  );
});

similar to the passage above

if AndroidServiceInstance is the Service (which is a subclass of ServiceInstance)

Make sure this function comes after WidgetsFlutterBinding.ensureInitialized ()

That’s all!!!

I hope this Article has given you some useful knowledge.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories