setTaskHandler static method

void setTaskHandler(
  1. TaskHandler handler
)

Set up the task handler and start the foreground task.

It must always be called from a top-level function, otherwise foreground task will not work.

Implementation

static void setTaskHandler(TaskHandler handler) {
  // Create a method channel to communicate with the platform.
  const backgroundChannel =
      MethodChannel('flutter_foreground_task/background');

  // Binding the framework to the flutter engine.
  WidgetsFlutterBinding.ensureInitialized();
  DartPluginRegistrant.ensureInitialized();

  // Set the method call handler for the background channel.
  backgroundChannel.setMethodCallHandler((call) async {
    await (await SharedPreferences.getInstance()).reload();
    final timestamp = DateTime.now();
    final sendPort = _lookupPort();

    switch (call.method) {
      case 'onStart':
        handler.onStart(timestamp, sendPort);
        break;
      case 'onRepeatEvent':
        handler.onRepeatEvent(timestamp, sendPort);
        break;
      case 'onDestroy':
        handler.onDestroy(timestamp, sendPort);
        break;
      case 'onNotificationButtonPressed':
        final String id = call.arguments.toString();
        handler.onNotificationButtonPressed(id);
        break;
      case 'onNotificationPressed':
        handler.onNotificationPressed();
    }
  });

  // Initializes the plug-in background channel and starts a foreground task.
  backgroundChannel.invokeMethod('initialize');
}