### Define Installation Directories Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Sets variables for the installation directories of data and libraries. ```cmake set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") ``` -------------------------------- ### Install Executable Target Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Installs the main executable to the specified runtime destination. ```cmake install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) ``` -------------------------------- ### Install Flutter Library Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Installs the main Flutter library to the library directory. ```cmake install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Install Bundled Plugin Libraries Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Installs any bundled plugin libraries to the library directory. ```cmake if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Install Flutter Assets Directory Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Removes and then installs the Flutter assets directory to ensure it's up-to-date. ```cmake set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Initialize and Start Background Service with Socket.io Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/README.md This snippet demonstrates a simple implementation of a background service using Socket.io for real-time communication. It includes service initialization, Socket.io connection, event handling, and periodic emission of messages. Ensure to replace 'your-server-url' with your actual server address. The service is configured to run in the background (isForegroundMode: false) and automatically start on boot. ```dart import 'dart:async'; import 'dart:ui'; import 'package:socket_io_client/socket_io_client.dart' as io; import 'package:flutter/material.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await initializeService(); runApp(MyApp()); } void startBackgroundService() { final service = FlutterBackgroundService(); service.startService(); } void stopBackgroundService() { final service = FlutterBackgroundService(); service.invoke("stop"); } Future initializeService() async { final service = FlutterBackgroundService(); await service.configure( iosConfiguration: IosConfiguration( autoStart: true, onForeground: onStart, onBackground: onIosBackground, ), androidConfiguration: AndroidConfiguration( autoStart: true, onStart: onStart, isForegroundMode: false, autoStartOnBoot: true, ), ); } @pragma('vm:entry-point') Future onIosBackground(ServiceInstance service) async { WidgetsFlutterBinding.ensureInitialized(); DartPluginRegistrant.ensureInitialized(); return true; } @pragma('vm:entry-point') void onStart(ServiceInstance service) async { final socket = io.io("your-server-url", { 'transports': ['websocket'], 'autoConnect': true, }); socket.onConnect((_) { print('Connected. Socket ID: ${socket.id}'); // Implement your socket logic here // For example, you can listen for events or send data }); socket.onDisconnect((_) { print('Disconnected'); }); socket.on("event-name", (data) { //do something here like pushing a notification }); service.on("stop").listen((event) { service.stopSelf(); print("background process is now stopped"); }); service.on("start").listen((event) {}); Timer.periodic(const Duration(seconds: 1), (timer) { socket.emit("event-name", "your-message"); print("service is successfully running ${DateTime.now().second}"); }); } ``` -------------------------------- ### Install AOT Library Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Installs the Ahead-Of-Time (AOT) compiled library for Profile and Release configurations. ```cmake install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### FlutterBackgroundService.startService() Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Programmatically starts the background service. This is useful when `autoStart` is set to `false` during configuration, or to restart the service after it has been stopped. Returns `true` if the service was started successfully. ```APIDOC ## FlutterBackgroundService.startService() ### Description Programmatically starts the service when `autoStart` is set to `false`, or re-starts it after it has been stopped. Returns `true` if the service was started successfully. ### Method `startService` ### Request Example ```dart final started = await service.startService(); debugPrint('Service started: $started'); ``` ### Response - **started** (bool) - Returns `true` if the service was started successfully. ``` -------------------------------- ### Set Visual Studio Install to Default Build Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Configures Visual Studio to include the 'install' step in the default build process. ```cmake set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) ``` -------------------------------- ### Install ICU Data File Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Installs the ICU data file to the data directory. ```cmake install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Set Install Prefix for Bundled Executable Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Sets the installation prefix to the directory of the executable, enabling in-place running. ```cmake if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() ``` -------------------------------- ### Start Flutter Background Service Manually Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Programmatically starts the service when autoStart is false, or restarts it after it has been stopped. Returns true if the service was started successfully. ```dart final service = FlutterBackgroundService(); // Only start if not already running final bool isRunning = await service.isRunning(); if (!isRunning) { final bool started = await service.startService(); debugPrint('Service started: $started'); } ``` -------------------------------- ### Control boot auto-start at runtime Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Dynamically enables or disables the `BOOT_COMPLETED` / `QUICKBOOT_POWERON` receiver that restarts the service after device reboot. This allows runtime control over whether the service should automatically start when the device boots up. ```APIDOC ## `AndroidServiceInstance.setAutoStartOnBootMode()` — Control boot auto-start at runtime Dynamically enables or disables the `BOOT_COMPLETED` / `QUICKBOOT_POWERON` receiver that restarts the service after device reboot. ### Usage ```dart @pragma('vm:entry-point') void onStart(ServiceInstance service) async { DartPluginRegistrant.ensureInitialized(); // Disable auto-start on boot dynamically if (service is AndroidServiceInstance) { service.on('disableBootStart').listen((_) async { await service.setAutoStartOnBootMode(false); }); service.on('enableBootStart').listen((_) async { await service.setAutoStartOnBootMode(true); }); } } ``` ``` -------------------------------- ### Set Installation RPATH Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Configures the runtime search path for libraries relative to the executable. ```cmake set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") ``` -------------------------------- ### Initialize WebSocket Background Service Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Configures and starts the background service with Android and iOS specific settings. It includes the entry point for the background service logic. ```dart import 'dart:async'; import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; import 'package:socket_io_client/socket_io_client.dart' as io; // ── Entry points ───────────────────────────────────────────────────────────── @pragma('vm:entry-point') Future onIosBackground(ServiceInstance service) async { WidgetsFlutterBinding.ensureInitialized(); DartPluginRegistrant.ensureInitialized(); return true; } @pragma('vm:entry-point') void onStart(ServiceInstance service) async { DartPluginRegistrant.ensureInitialized(); final socket = io.io( 'wss://your-server-url', io.OptionBuilder().setTransports(['websocket']).enableAutoConnect().build(), ); socket.onConnect((_) => debugPrint('Socket connected: ${socket.id}')); socket.onDisconnect((_) => debugPrint('Socket disconnected')); socket.on('server-event', (data) { // Relay server event to the UI isolate service.invoke('serverEvent', {'payload': data.toString()}); }); // Heartbeat Timer.periodic(const Duration(seconds: 5), (_) { socket.emit('ping', 'heartbeat'); }); // Graceful stop from UI service.on('stop').listen((_) { socket.disconnect(); socket.dispose(); service.stopSelf(); }); // Android-specific foreground toggle if (service is AndroidServiceInstance) { service.on('setAsForeground').listen((_) => service.setAsForegroundService()); service.on('setAsBackground').listen((_) => service.setAsBackgroundService()); } } // ── Service initializer ─────────────────────────────────────────────────────── Future initializeService() async { final service = FlutterBackgroundService(); await service.configure( androidConfiguration: AndroidConfiguration( onStart: onStart, autoStart: true, autoStartOnBoot: true, isForegroundMode: false, // silent background; requires battery opt. disabled ), iosConfiguration: IosConfiguration( autoStart: true, onForeground: onStart, onBackground: onIosBackground, ), ); } // ── UI ──────────────────────────────────────────────────────────────────────── class ServicePage extends StatelessWidget { const ServicePage({super.key}); @override Widget build(BuildContext context) { final service = FlutterBackgroundService(); return Scaffold( appBar: AppBar(title: const Text('Background Service Demo')), body: Column( children: [ StreamBuilder?>( stream: service.on('serverEvent'), builder: (_, snap) => Text( snap.hasData ? 'Event: ${snap.data!['payload']}' : 'Waiting...', ), ), ElevatedButton( onPressed: () => service.invoke('stop'), child: const Text('Stop Service'), ), ], ), ); } } ``` -------------------------------- ### Create Notification Channel for Foreground Service Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/README.md Defines the notification channel and initializes the background service. This setup is crucial for foreground services to display persistent notifications. ```dart Future main() async { WidgetsFlutterBinding.ensureInitialized(); await initializeService(); runApp(MyApp()); } // this will be used as notification channel id const notificationChannelId = 'my_foreground'; // this will be used for notification id, So you can update your custom notification with this id. const notificationId = 888; Future initializeService() async { final service = FlutterBackgroundService(); const AndroidNotificationChannel channel = AndroidNotificationChannel( notificationChannelId, // id 'MY FOREGROUND SERVICE', // title description: 'This channel is used for important notifications.', // description importance: Importance.low, // importance must be at low or higher level ); final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); await flutterLocalNotificationsPlugin .resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(channel); await service.configure( androidConfiguration: AndroidConfiguration( // this will be executed when app is in foreground or background in separated isolate onStart: onStart, // auto start service autoStart: true, isForegroundMode: true, notificationChannelId: notificationChannelId, // this must match with notification channel you created above. initialNotificationTitle: 'AWESOME SERVICE', initialNotificationContent: 'Initializing', foregroundServiceNotificationId: notificationId, ), ... ``` -------------------------------- ### FlutterBackgroundService.isRunning() Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Checks the current status of the background service. Returns `true` if the service is active, and `false` otherwise. This is useful for controlling UI elements or preventing duplicate service starts. ```APIDOC ## FlutterBackgroundService.isRunning() ### Description Returns `true` when the background service is currently active. Useful for toggling UI controls or preventing duplicate service starts. ### Method `isRunning` ### Request Example ```dart final running = await service.isRunning(); if (running) { debugPrint('Service is active'); } else { debugPrint('Service is not running'); await service.startService(); } ``` ### Response - **running** (bool) - Returns `true` if the service is active, `false` otherwise. ``` -------------------------------- ### Dart Configuration for Foreground Service Types Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/README.md Configure foreground service types in your Dart code using `AndroidConfiguration`. The types specified here must also be declared in your `AndroidManifest.xml`. Ensure all required permissions are granted before starting the service. ```dart await service.configure( // IOS configuration androidConfiguration: AndroidConfiguration( ... // Add this foregroundServiceTypes: [AndroidForegroundType.WhatForegroundServiceTypeDoYouWant] // Example: // foregroundServiceTypes: [AndroidForegroundType.mediaPlayback] ), ); ``` -------------------------------- ### Check Flutter Background Service Status Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Returns true when the background service is currently active. Useful for toggling UI controls or preventing duplicate service starts. ```dart final service = FlutterBackgroundService(); final bool running = await service.isRunning(); if (running) { debugPrint('Service is active'); } else { debugPrint('Service is not running'); await service.startService(); } ``` -------------------------------- ### Ensure Service Runs in Release Mode Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/README.md Add the @pragma('vm:entry-point') annotation to your onStart method to ensure the service is correctly initialized in release builds. ```dart @pragma('vm:entry-point') void onStart(ServiceInstance service){ ... } ``` -------------------------------- ### iOS Service Configuration Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Holds the iOS entry-point callbacks and auto-start flag passed to `configure()`. For `onBackground`, ensure 'Background Fetch' capability is enabled in Xcode and configured in `Info.plist`. ```dart IosConfiguration( autoStart: true, // Runs in a separate isolate while the app is in the foreground onForeground: onStart, // Executed periodically by BGTaskScheduler; must return within ~15–20 seconds // Enable "Background Fetch" capability in Xcode and add to Info.plist: // BGTaskSchedulerPermittedIdentifiers // dev.flutter.background.refresh onBackground: onIosBackground, ) @pragma('vm:entry-point') Future onIosBackground(ServiceInstance service) async { WidgetsFlutterBinding.ensureInitialized(); DartPluginRegistrant.ensureInitialized(); // Perform a quick task — max ~15-20 seconds return true; // signal success to iOS } ``` -------------------------------- ### Configure Flutter Background Service Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Registers background entry-point callbacks and sets startup behavior. Must be called from main() before runApp(). ```dart import 'dart:async'; import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await initializeService(); runApp(const MyApp()); } Future initializeService() async { final service = FlutterBackgroundService(); // Create a notification channel (required for Android foreground service) const AndroidNotificationChannel channel = AndroidNotificationChannel( 'my_foreground', 'MY FOREGROUND SERVICE', description: 'Background task notifications.', importance: Importance.low, ); final FlutterLocalNotificationsPlugin flln = FlutterLocalNotificationsPlugin(); await flln .resolvePlatformSpecificImplementation() ?.createNotificationChannel(channel); final bool configured = await service.configure( androidConfiguration: AndroidConfiguration( onStart: onStart, // top-level or static entry point autoStart: true, // start immediately after configure autoStartOnBoot: true, // restart after device reboot isForegroundMode: true, // show persistent notification notificationChannelId: 'my_foreground', // match the channel created above initialNotificationTitle: 'My Service', initialNotificationContent: 'Initializing...', foregroundServiceNotificationId: 888, foregroundServiceTypes: [AndroidForegroundType.dataSync], ), iosConfiguration: IosConfiguration( autoStart: true, onForeground: onStart, // runs when the app is in the foreground onBackground: onIosBackground, // periodic background fetch (~15 s) ), ); debugPrint('Service configured: $configured'); } // Must be annotated so the Dart VM tree-shaker keeps it in release builds @pragma('vm:entry-point') void onStart(ServiceInstance service) async { DartPluginRegistrant.ensureInitialized(); debugPrint('Background service started'); } @pragma('vm:entry-point') Future onIosBackground(ServiceInstance service) async { WidgetsFlutterBinding.ensureInitialized(); DartPluginRegistrant.ensureInitialized(); return true; // tells iOS the background fetch succeeded } ``` -------------------------------- ### Include Application Build Rules Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Includes the build rules for the application runner. ```cmake add_subdirectory("runner") ``` -------------------------------- ### Initialize Foreground Service with Custom Notification Channel Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/README.md Sets up the main entry point for the Flutter app and initializes the background service. It configures a custom Android notification channel and prepares the service for foreground mode. ```dart Future main() async { WidgetsFlutterBinding.ensureInitialized(); await initializeService(); runApp(MyApp()); } // this will be used as notification channel id const notificationChannelId = 'my_foreground'; // this will be used for notification id, So you can update your custom notification with this id. const notificationId = 888; Future initializeService() async { final service = FlutterBackgroundService(); const AndroidNotificationChannel channel = AndroidNotificationChannel( notificationChannelId, // id 'MY FOREGROUND SERVICE', // title description: 'This channel is used for important notifications.', // description importance: Importance.low, // importance must be at low or higher level ); final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); await flutterLocalNotificationsPlugin .resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(channel); await service.configure( androidConfiguration: AndroidConfiguration( // this will be executed when app is in foreground or background in separated isolate onStart: onStart, // auto start service autoStart: true, isForegroundMode: true, notificationChannelId: notificationChannelId, // this must match with notification channel you created above. initialNotificationTitle: 'AWESOME SERVICE', initialNotificationContent: 'Initializing', foregroundServiceNotificationId: notificationId, ), ... ``` -------------------------------- ### Android Gradle and Kotlin Versions Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/README.md Ensure your project uses compatible Gradle and Kotlin versions for the background service. These are specified in your `android/build.gradle` and `android/gradle/wrapper/gradle-wrapper.properties` files. ```gradle classpath 'com.android.tools.build:gradle:7.4.2' ``` ```gradle ext.kotlin_version = '1.8.10' ``` ```properties distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-all.zip ``` -------------------------------- ### Include Flutter Library and Tool Build Rules Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Includes the build rules for the Flutter library and tools. ```cmake add_subdirectory(${FLUTTER_MANAGED_DIR}) ``` -------------------------------- ### Configure Build Options Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Sets the available build configurations (Debug, Profile, Release) based on whether the generator is multi-configuration. ```cmake get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) if(IS_MULTICONFIG) set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" CACHE STRING "" FORCE) else() if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() endif() ``` -------------------------------- ### AndroidConfiguration Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Data class that holds all Android-specific configuration parameters passed to the `configure()` method. This includes settings for auto-start, foreground mode, and notification details. ```APIDOC ## `AndroidConfiguration` — Android-specific service configuration Data class that holds all Android-side configuration parameters passed to `configure()`. ### Parameters - **onStart** (Function) - Required - The top-level or static entry point for the service. - **autoStart** (bool) - Optional - Whether to start the service when `configure()` is called. Defaults to `false`. - **autoStartOnBoot** (bool) - Optional - Whether to restart the service after device reboot. Defaults to `false`. - **isForegroundMode** (bool) - Optional - Whether to show a persistent notification when the service starts. Defaults to `false`. - **initialNotificationTitle** (String) - Optional - The title for the initial foreground notification. - **initialNotificationContent** (String) - Optional - The content for the initial foreground notification. - **notificationChannelId** (String) - Required - The ID of the notification channel to use. Must be pre-created. - **foregroundServiceNotificationId** (int) - Optional - A unique ID for the foreground service notification. - **foregroundServiceTypes** (List) - Optional - Required on Android 14+ (SDK 34) to specify the type of foreground service. ### Example ```dart AndroidConfiguration( onStart: onStart, // required: top-level or static entry point autoStart: true, // start service when configure() is called autoStartOnBoot: true, // restart after reboot isForegroundMode: true, // show persistent notification initialNotificationTitle: 'App', initialNotificationContent: 'Running...', notificationChannelId: 'my_channel', // must be pre-created foregroundServiceNotificationId: 101, foregroundServiceTypes: [ AndroidForegroundType.dataSync, // required on Android 14+ (SDK 34) ], ) ``` ``` -------------------------------- ### FlutterBackgroundService.configure() Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Registers and configures the background service for both Android and iOS platforms. This method sets up the service's behavior, including auto-start, foreground/background modes, and notification appearance. It must be called from `main()` before `runApp()`. ```APIDOC ## FlutterBackgroundService.configure() ### Description Registers background entry-point callbacks for both Android and iOS, sets startup behavior (auto-start, foreground/background mode, notification appearance), and prepares the native service. Must be called from `main()` before `runApp()` to ensure the callback handles are registered. Returns `true` on success. ### Method `configure` ### Parameters #### Android Configuration - **onStart** (Function) - Required - The entry point for the background service on Android. - **autoStart** (bool) - Optional - If true, the service starts immediately after configuration. - **autoStartOnBoot** (bool) - Optional - If true, the service restarts after device reboot. - **isForegroundMode** (bool) - Optional - If true, a persistent notification is shown. - **notificationChannelId** (string) - Required if `isForegroundMode` is true - The ID of the notification channel. - **initialNotificationTitle** (string) - Optional - The title of the initial notification. - **initialNotificationContent** (string) - Optional - The content of the initial notification. - **foregroundServiceNotificationId** (int) - Optional - The ID for the foreground service notification. - **foregroundServiceTypes** (List) - Optional - Specifies the types of foreground services. #### iOS Configuration - **autoStart** (bool) - Optional - If true, the service starts automatically. - **onForeground** (Function) - Optional - Callback when the app is in the foreground. - **onBackground** (Function) - Optional - Callback for periodic background fetch (~15 s). ### Request Example ```dart await service.configure( androidConfiguration: AndroidConfiguration( onStart: onStart, autoStart: true, autoStartOnBoot: true, isForegroundMode: true, notificationChannelId: 'my_foreground', initialNotificationTitle: 'My Service', initialNotificationContent: 'Initializing...', foregroundServiceNotificationId: 888, foregroundServiceTypes: [AndroidForegroundType.dataSync], ), iosConfiguration: IosConfiguration( autoStart: true, onForeground: onStart, onBackground: onIosBackground, ), ); ``` ### Response - **configured** (bool) - Returns `true` on successful configuration. ``` -------------------------------- ### Control Android Service Boot Auto-Start Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Dynamically enables or disables the `BOOT_COMPLETED` / `QUICKBOOT_POWERON` receiver that restarts the service after device reboot. Listen for custom events to toggle this behavior. ```dart @pragma('vm:entry-point') void onStart(ServiceInstance service) async { DartPluginRegistrant.ensureInitialized(); // Disable auto-start on boot dynamically if (service is AndroidServiceInstance) { service.on('disableBootStart').listen((_) async { await service.setAutoStartOnBootMode(false); }); service.on('enableBootStart').listen((_) async { await service.setAutoStartOnBootMode(true); }); } } ``` -------------------------------- ### Include Generated Plugin Build Rules Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Includes CMake scripts to manage building and integrating generated plugins. ```cmake include(flutter/generated_plugins.cmake) ``` -------------------------------- ### Profile Build Configuration Flags Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Copies release flags to profile builds for consistency. ```cmake set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") ``` -------------------------------- ### ServiceInstance.stopSelf() Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Terminates the background service from inside the `onStart` callback. Typically triggered in response to a UI command or an internal condition. ```APIDOC ## ServiceInstance.stopSelf() ### Description Terminates the background service from inside the `onStart` callback. Typically triggered in response to a UI command or an internal condition. ### Method `stopSelf()` ### Parameters None ### Request Example ```dart @pragma('vm:entry-point') void onStart(ServiceInstance service) async { DartPluginRegistrant.ensureInitialized(); int countdown = 60; Timer.periodic(const Duration(seconds: 1), (timer) async { countdown--; debugPrint('Countdown: $countdown'); if (countdown <= 0) { timer.cancel(); await service.stopSelf(); // gracefully terminates the service } }); } ``` ### Response None. This method performs an action and does not return a value. ``` -------------------------------- ### Apply Standard Compilation Settings Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt A function to apply common compilation features, options, and definitions to a target. ```cmake function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_17) target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") target_compile_options(${TARGET} PRIVATE /EHsc) target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") endfunction() ``` -------------------------------- ### Enable Unicode Support Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Adds definitions to enable Unicode support in the project. ```cmake add_definitions(-DUNICODE -D_UNICODE) ``` -------------------------------- ### ServiceInstance.invoke() Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Sends a named event with optional data from within the `onStart` callback (background isolate) to the UI isolate. The UI listens using `FlutterBackgroundService().on(method)`. ```APIDOC ## ServiceInstance.invoke() ### Description Sends a named event with optional data from within the `onStart` callback (background isolate) to the UI isolate. The UI listens using `FlutterBackgroundService().on(method)`. ### Method `invoke(String method, [Map? data])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart @pragma('vm:entry-point') void onStart(ServiceInstance service) async { DartPluginRegistrant.ensureInitialized(); // Periodically push data back to the UI Timer.periodic(const Duration(seconds: 2), (timer) { service.invoke('update', { 'current_date': DateTime.now().toIso8601String(), 'counter': timer.tick, }); }); // Respond to a stop command sent from the UI service.on('stopService').listen((_) async { timer?.cancel(); await service.stopSelf(); }); } ``` ### Response None directly from this method, as it's for sending messages. ``` -------------------------------- ### ServiceInstance.on() Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Listens for named events sent by the UI via `FlutterBackgroundService().invoke()`. Returns a broadcast `Stream`. ```APIDOC ## ServiceInstance.on() ### Description Listens for named events sent by the UI via `FlutterBackgroundService().invoke()`. Returns a broadcast `Stream`. ### Method `on(String method)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart @pragma('vm:entry-point') void onStart(ServiceInstance service) async { DartPluginRegistrant.ensureInitialized(); // Listen for a stop command from the UI service.on('stopService').listen((event) { service.stopSelf(); }); // Listen for a configuration update from the UI service.on('updateInterval').listen((event) { final int newInterval = event?['seconds'] ?? 10; debugPrint('Interval updated to $newInterval seconds'); }); // Listen for foreground/background toggle if (service is AndroidServiceInstance) { service.on('setAsForeground').listen((_) => service.setAsForegroundService()); service.on('setAsBackground').listen((_) => service.setAsBackgroundService()); } } ``` ### Response #### Success Response (Stream) A broadcast `Stream` that emits events sent from the UI isolate. ``` -------------------------------- ### Update Foreground Service Notification Content Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/README.md Defines the `onStart` callback for the background service. This function is executed in a separate isolate and is responsible for updating the foreground service notification periodically with new content. ```dart Future onStart(ServiceInstance service) async { // Only available for flutter 3.0.0 and later DartPluginRegistrant.ensureInitialized(); final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); // bring to foreground Timer.periodic(const Duration(seconds: 1), (timer) async { if (service is AndroidServiceInstance) { if (await service.isForegroundService()) { flutterLocalNotificationsPlugin.show( notificationId, 'COOL SERVICE', 'Awesome ${DateTime.now()}', const NotificationDetails( android: AndroidNotificationDetails( notificationChannelId, 'MY FOREGROUND SERVICE', icon: 'ic_bg_service_small', ongoing: true, ), ), ); } } }); } ``` -------------------------------- ### Set Minimum CMake Version and Project Name Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Specifies the minimum required CMake version and names the project. ```cmake cmake_minimum_required(VERSION 3.14) project(example LANGUAGES CXX) ``` -------------------------------- ### Set CMake Policy Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Applies a specific CMake policy for new behavior. ```cmake cmake_policy(SET CMP0063 NEW) ``` -------------------------------- ### Send messages from background service to UI Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Inside the `onStart` callback, use `service.invoke(method, data)` to send messages back to the UI isolate. The UI listens using `FlutterBackgroundService().on(method)`. ```dart @pragma('vm:entry-point') void onStart(ServiceInstance service) async { DartPluginRegistrant.ensureInitialized(); // Periodically push data back to the UI Timer.periodic(const Duration(seconds: 2), (timer) { service.invoke('update', { 'current_date': DateTime.now().toIso8601String(), 'counter': timer.tick, }); }); // Respond to a stop command sent from the UI service.on('stopService').listen((_) async { timer?.cancel(); await service.stopSelf(); }); } ``` -------------------------------- ### Open Host App from Android Service Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Launches the Flutter application from within the background service, returning `true` if the app was successfully brought to the foreground. Listen for a specific event to trigger this action. ```dart @pragma('vm:entry-point') void onStart(ServiceInstance service) async { DartPluginRegistrant.ensureInitialized(); service.on('openApp').listen((_) async { if (service is AndroidServiceInstance) { final bool opened = await service.openApp(); debugPrint('App opened: $opened'); } }); } ``` -------------------------------- ### Receive messages inside the background isolate Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Use `service.on(method)` within the `onStart` callback to listen for events sent from the UI isolate. This allows the background service to react to commands like stopping or updating configuration. ```dart @pragma('vm:entry-point') void onStart(ServiceInstance service) async { DartPluginRegistrant.ensureInitialized(); // Listen for a stop command from the UI service.on('stopService').listen((event) { service.stopSelf(); }); // Listen for a configuration update from the UI service.on('updateInterval').listen((event) { final int newInterval = event?['seconds'] ?? 10; debugPrint('Interval updated to $newInterval seconds'); }); // Listen for foreground/background toggle if (service is AndroidServiceInstance) { service.on('setAsForeground').listen((_) => service.setAsForegroundService()); service.on('setAsBackground').listen((_) => service.setAsBackgroundService()); } } ``` -------------------------------- ### Bring the host app to the foreground Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Launches the Flutter application from within the background service, returning `true` if the app was successfully brought to the foreground. This is useful for user interaction or notifications that require the app to be visible. ```APIDOC ## `AndroidServiceInstance.openApp()` — Bring the host app to the foreground Launches the Flutter application from within the background service, returning `true` if the app was successfully brought to the foreground. ### Usage ```dart @pragma('vm:entry-point') void onStart(ServiceInstance service) async { DartPluginRegistrant.ensureInitialized(); service.on('openApp').listen((_) async { if (service is AndroidServiceInstance) { final bool opened = await service.openApp(); debugPrint('App opened: $opened'); } }); } ``` ``` -------------------------------- ### Set Binary Name Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Defines the name of the final executable binary. ```cmake set(BINARY_NAME "example") ``` -------------------------------- ### Android Service Configuration Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Holds all Android-specific service configuration parameters passed to `configure()`. Ensure `notificationChannelId` is pre-created and `foregroundServiceTypes` are set for Android 14+. ```dart AndroidConfiguration( onStart: onStart, // required: top-level or static entry point autoStart: true, // start service when configure() is called autoStartOnBoot: true, // restart after reboot isForegroundMode: true, // show persistent notification initialNotificationTitle: 'App', initialNotificationContent: 'Running...', notificationChannelId: 'my_channel', // must be pre-created foregroundServiceNotificationId: 101, foregroundServiceTypes: [ AndroidForegroundType.dataSync, // required on Android 14+ (SDK 34) ], ) ``` -------------------------------- ### Configure Windows Runner Build Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/runner/CMakeLists.txt Defines the build settings for the Windows executable, including source files, compiler flags, and library dependencies. This is essential for compiling the native Windows part of the Flutter application. ```cmake cmake_minimum_required(VERSION 3.14) project(runner LANGUAGES CXX) add_executable(${BINARY_NAME} WIN32 "flutter_window.cpp" "main.cpp" "utils.cpp" "win32_window.cpp" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" "Runner.rc" "runner.exe.manifest" ) apply_standard_settings(${BINARY_NAME}) target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") add_dependencies(${BINARY_NAME} flutter_assemble) ``` -------------------------------- ### FlutterBackgroundService.on() Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Listens for messages from the background isolate. Returns a `Stream?>` that emits whenever the background service calls `service.invoke(method, data)` with a matching method name. ```APIDOC ## FlutterBackgroundService.on() ### Description Listens for messages from the background isolate. Returns a `Stream?>` that emits whenever the background service calls `service.invoke(method, data)` with a matching method name. Use in a `StreamBuilder` for reactive UI updates. ### Method `on(String method)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart // In a StatefulWidget or build method: StreamBuilder?>( stream: FlutterBackgroundService().on('update'), builder: (context, snapshot) { if (!snapshot.hasData) { return const CircularProgressIndicator(); } final data = snapshot.data!; final String device = data['device'] ?? 'Unknown'; final String timestamp = data['current_date'] ?? ''; return Column( children: [ Text('Device: $device'), Text('Last update: $timestamp'), ], ); }, ) ``` ### Response #### Success Response (Stream) A `Stream?>` that emits data sent from the background service. ``` -------------------------------- ### Android Manifest Configuration for Foreground Services (SDK 34+) Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/README.md Configure your `AndroidManifest.xml` to declare foreground service permissions and types for Android 14 (SDK 34) and above. This includes adding necessary permissions and specifying the `foregroundServiceType` for the background service. ```xml ... ... ... ``` -------------------------------- ### Set Flutter Managed Directory Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service/example/windows/CMakeLists.txt Defines the path to the Flutter managed directory. ```cmake set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") ``` -------------------------------- ### Configure iOS Background Task Scheduler Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/README.md This snippet shows how to configure the background task scheduler for iOS 13 and later by adding permitted identifiers to your `Info.plist` file. This is necessary if you wish the iOS `IosConfiguration.onBackground` callback to be executed. ```xml BGTaskSchedulerPermittedIdentifiers dev.flutter.background.refresh ``` -------------------------------- ### FlutterBackgroundService.invoke() Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Sends a named event with an optional payload from the UI isolate to the background service isolate. The background service listens using `service.on(method)`. ```APIDOC ## FlutterBackgroundService.invoke() ### Description Sends a named event with an optional payload from the UI isolate to the background service isolate. The background service listens using `service.on(method)`. ### Method `invoke(String method, [Map? arguments])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart final service = FlutterBackgroundService(); // Send a simple command service.invoke('stopService'); // Send a command with a payload service.invoke('updateConfig', { 'interval': 5, 'endpoint': 'https://api.example.com/data', }); // Switch Android service to foreground mode service.invoke('setAsForeground'); // Switch Android service to background mode (silent) service.invoke('setAsBackground'); ``` ### Response None directly from this method, as it's for sending messages. ``` -------------------------------- ### Stop background service from within the isolate Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Call `service.stopSelf()` within the `onStart` callback to gracefully terminate the background service. This is typically used when a specific condition is met or in response to a UI command. ```dart @pragma('vm:entry-point') void onStart(ServiceInstance service) async { DartPluginRegistrant.ensureInitialized(); int countdown = 60; Timer.periodic(const Duration(seconds: 1), (timer) async { countdown--; debugPrint('Countdown: $countdown'); if (countdown <= 0) { timer.cancel(); await service.stopSelf(); // gracefully terminates the service } }); } ``` -------------------------------- ### Android Manifest Configuration for Foreground Services Source: https://github.com/ekasetiawans/flutter_background_service/blob/master/README.md Declare foreground service types in your AndroidManifest.xml. Ensure the `FOREGROUND_SERVICE` permission is present and the `foregroundServiceType` attribute matches your app's needs. Consult Android documentation for valid types. ```xml ... ... ... ``` -------------------------------- ### Toggle foreground mode at runtime Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Switches an Android service between foreground mode (with a visible notification) and background mode (silent, may be killed by the OS) while the service is running. This is done by invoking 'setAsForeground' or 'setAsBackground' on the service instance. ```APIDOC ## `AndroidServiceInstance.setAsForegroundService()` / `setAsBackgroundService()` — Toggle foreground mode at runtime Switches an Android service between foreground mode (with a visible notification) and background mode (silent, may be killed by the OS) while the service is running. ### Usage **UI side — send toggle commands:** ```dart final service = FlutterBackgroundService(); service.invoke('setAsForeground'); service.invoke('setAsBackground'); ``` **Background isolate — handle the toggle commands:** ```dart @pragma('vm:entry-point') void onStart(ServiceInstance service) async { DartPluginRegistrant.ensureInitialized(); if (service is AndroidServiceInstance) { service.on('setAsForeground').listen((_) async { await service.setAsForegroundService(); }); service.on('setAsBackground').listen((_) async { await service.setAsBackgroundService(); }); } } ``` ``` -------------------------------- ### Listen for messages from background service in UI Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Use `FlutterBackgroundService().on('update')` to listen for events emitted from the background isolate. This is useful for updating the UI reactively. Requires a `StreamBuilder` to display data. ```dart // In a StatefulWidget or build method: StreamBuilder?>( stream: FlutterBackgroundService().on('update'), builder: (context, snapshot) { if (!snapshot.hasData) { return const CircularProgressIndicator(); } final data = snapshot.data!; final String device = data['device'] ?? 'Unknown'; final String timestamp = data['current_date'] ?? ''; return Column( children: [ Text('Device: $device'), Text('Last update: $timestamp'), ], ); }, ) ``` -------------------------------- ### Send messages from UI to background service Source: https://context7.com/ekasetiawans/flutter_background_service/llms.txt Use `FlutterBackgroundService().invoke()` to send named events with optional data to the background isolate. The background service must be listening with `service.on(method)`. ```dart final service = FlutterBackgroundService(); // Send a simple command service.invoke('stopService'); // Send a command with a payload service.invoke('updateConfig', { 'interval': 5, 'endpoint': 'https://api.example.com/data', }); // Switch Android service to foreground mode service.invoke('setAsForeground'); // Switch Android service to background mode (silent) service.invoke('setAsBackground'); ```