setBackgroundHandler method

Future<MapxusMethodResponse> setBackgroundHandler(
  1. MapxusBackgroundHandler handler
)

Registers a background handler that is called by the Android foreground service with every positioning event even when the app is fully closed.

handler must be a top-level function annotated with @pragma('vm:entry-point'). Call this before startForegroundService.

@pragma('vm:entry-point')
Future<void> onBackgroundLocation(MapxusEvent event) async {
  if (event is MapxusLocationEvent) {
    await MyApi.uploadLocation(event.latitude, event.longitude);
  }
}

// In initState / main():
await mapxus.setBackgroundHandler(onBackgroundLocation);
await mapxus.startForegroundService(appId: '...', secret: '...');

Implementation

Future<MapxusMethodResponse> setBackgroundHandler(
    MapxusBackgroundHandler handler) async {
  // Get the raw handle for our internal dispatcher entry point.
  final CallbackHandle? dispatcherHandle =
      PluginUtilities.getCallbackHandle(_mapxusBackgroundMain);

  // Get the raw handle for the developer's callback.
  final CallbackHandle? userHandle =
      PluginUtilities.getCallbackHandle(handler);

  if (dispatcherHandle == null || userHandle == null) {
    return MapxusMethodResponse.fromMap({
      'success': false,
      'message': 'Could not get callback handle. '
          'Make sure the handler is a top-level function annotated '
          "with @pragma('vm:entry-point').",
    });
  }

  return _platform.setBackgroundHandlerRaw(
    dispatcherHandle: dispatcherHandle.toRawHandle(),
    userCallbackHandle: userHandle.toRawHandle(),
  );
}