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();
// Initializing the Platform-specific SharedPreferences plugin.
if (Platform.isAndroid) {
SharedPreferencesAndroid.registerWith();
} else if (Platform.isIOS) {
SharedPreferencesIOS.registerWith();
}
// Set the method call handler for the background channel.
backgroundChannel.setMethodCallHandler((call) async {
final timestamp = DateTime.now();
final sendPort = _lookupPort();
switch (call.method) {
case 'onStart':
await handler.onStart(timestamp, sendPort);
break;
case 'onEvent':
await handler.onEvent(timestamp, sendPort);
break;
case 'onDestroy':
await handler.onDestroy(timestamp, sendPort);
break;
case 'onButtonPressed':
handler.onButtonPressed(call.arguments.toString());
break;
case 'onNotificationPressed':
handler.onNotificationPressed();
}
});
// Initializes the plug-in background channel and starts a foreground task.
backgroundChannel.invokeMethod('initialize');
}