setTaskHandler static method
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();
// Set the method call handler for the background channel.
_backgroundChannel.setMethodCallHandler((call) async {
final timestamp = DateTime.now();
final method = call.method;
switch (method) {
case 'start':
return await handler.onStart(timestamp, _lookupPort());
case 'event':
return await handler.onEvent(timestamp, _lookupPort());
case 'destroy':
return await handler.onDestroy(timestamp);
case 'onButtonPressed':
return handler.onButtonPressed(call.arguments.toString());
}
});
// Initializes the plug-in background channel and starts a foreground task.
_backgroundChannel.invokeMethod('initialize');
}