### App Installer YAML Configuration Example Source: https://pub.dev/packages/flutter_background_service/packages/msix Example YAML configuration for setting up App Installer properties within the `msix_config` block, including `publish_folder_path`, update check intervals, and background task settings. ```YAML msix_config: display_name: Flutter App app_installer: #<-- app installer configuration publish_folder_path: c:\\path\\to\\myPublishFolder hours_between_update_checks: 0 automatic_background_task: true update_blocks_activation: true show_prompt: true force_update_from_any_version: false msix_version: 1.0.3.0 ``` -------------------------------- ### App Installer YAML Configuration Example Source: https://pub.dev/packages/flutter_background_service/documentation/msix/latest Example YAML configuration for the App Installer, detailing settings like publish folder, update check frequency, background tasks, and update behavior. ```YAML msix_config: display_name: Flutter App app_installer: #<-- app installer configuration publish_folder_path: c:\\path\\to\\myPublishFolder hours_between_update_checks: 0 automatic_background_task: true update_blocks_activation: true show_prompt: true force_update_from_any_version: false msix_version: 1.0.3.0 ``` -------------------------------- ### Basic Shelf Router Setup and Route Definition Source: https://pub.dev/packages/flutter_background_service/packages/shelf_router This example demonstrates how to initialize a `Router` instance from the `shelf_router` package and define two basic HTTP GET routes. It shows how to handle simple requests and requests with URL parameters, then serves the application using `shelf_io`. ```Dart import 'package:shelf_router/shelf_router.dart'; import 'package:shelf/shelf.dart'; import 'package:shelf/shelf_io.dart' as io; var app = Router(); app.get('/hello', (Request request) { return Response.ok('hello-world'); }); app.get('/user/', (Request request, String user) { return Response.ok('hello $user'); }); var server = await io.serve(app, 'localhost', 8080); ``` -------------------------------- ### Install Equatable Package via Pub Source: https://pub.dev/packages/flutter_background_service/documentation/equatable/latest Commands to fetch and install the `equatable` package using `pub get` for Dart projects or `flutter packages get` for Flutter projects. ```Shell # Dart pub get # Flutter flutter packages get ``` -------------------------------- ### Flutter Dotted Border Package Main Application Setup Source: https://pub.dev/packages/flutter_background_service/packages/dotted_border/example Initializes the Flutter application and sets up the main UI structure, including an `AppBar` and a `ListView` that displays various examples of `DottedBorder` configurations. Each example is encapsulated in a separate widget. ```Dart import 'package:dotted_border/dotted_border.dart'; import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) => MaterialApp( theme: ThemeData(useMaterial3: true), home: Scaffold( appBar: AppBar(title: const Text('Dotted Border')), body: SafeArea( child: ListView( children: const [ _RectDottedBorder(key: Key('rect_dotted_border')), _RoundedRectDottedBorder( key: Key('rounded_rect_dotted_border'), ), _OvalDottedBorder(key: Key('oval_dotted_border')), _CircleDottedBorder(key: Key('circle_dotted_border')), _CustomPathBorder(key: Key('custom_path_dotted_border')), _GradientBorder(key: Key('gradient_dotted_border')), ] .map( (e) => Padding( padding: const EdgeInsets.all(10), child: e, ), ) .toList(), ), ), ), ); ``` -------------------------------- ### Execute Pana from the command line Source: https://pub.dev/packages/flutter_background_service/packages/pana/install Example of running the globally installed pana executable after installation to analyze a Dart package. ```Shell $ pana ``` -------------------------------- ### Setup ffigen with Clang Paths Source: https://pub.dev/packages/flutter_background_service/packages/posix Commands to install 'libclang-dev' and run the 'ffigen' setup, specifying the include and library paths for Clang. This step is crucial for 'ffigen' to locate necessary C headers and libraries for binding generation. ```Bash sudo apt-get install libclang-dev dart pub run ffigen:setup -I/usr/lib/llvm-11/include -L/usr/lib/llvm-11/lib ``` -------------------------------- ### Background Service Initialization and Logic (onStart) Source: https://pub.dev/packages/flutter_background_service/packages/flutter_background_service/versions/2.4.3/example Demonstrates the core logic executed by the Flutter background service when it starts. This includes optional foreground notification setup, logging current time, retrieving device information using `DeviceInfoPlugin` for both Android and iOS, and sending updated data back to the main application UI using `service.invoke`. ```Dart // if you don't using custom notification, uncomment this // service.setForegroundNotificationInfo( // title: "My App Service", // content: "Updated at ${DateTime.now()}", // ); } } /// you can see this log in logcat print('FLUTTER BACKGROUND SERVICE: ${DateTime.now()}'); // test using external plugin final deviceInfo = DeviceInfoPlugin(); String? device; if (Platform.isAndroid) { final androidInfo = await deviceInfo.androidInfo; device = androidInfo.model; } if (Platform.isIOS) { final iosInfo = await deviceInfo.iosInfo; device = iosInfo.model; } service.invoke( 'update', { "current_date": DateTime.now().toIso8601String(), "device": device, }, ); }); ``` -------------------------------- ### App Installer Configuration Options Source: https://pub.dev/packages/flutter_background_service/documentation/msix/latest Details available configuration options for the App Installer, including their command-line arguments, descriptions, and example values, for publishing applications outside the Microsoft Store. ```APIDOC Option: publish_folder_path Command-line: --publish-folder-path Description: A path to publish folder, where the msix versions and the .appinstaller file will be saved. Example: c:\\path\\to\\myPublishFolder Option: hours_between_update_checks Command-line: --hours-between-update-checks Description: Defines the minimal time gap between update checks, when the user open the app. Default is 0 (will check for update every time the app opened). Example: 2 Option: automatic_background_task Command-line: --automatic-background-task Description: Checks for updates in the background every 8 hours independently of whether the user launched the app. Example: false Option: update_blocks_activation Command-line: --update-blocks-activation Description: Defines the experience when an app update is checked for. Example: false Option: show_prompt Command-line: --show-prompt Description: Defines if a window is displayed when updates are being installed, and when updates are being checked for. Example: false Option: force_update_from_any_version Command-line: --force-update-from-any-version Description: Allows the app to update from version x to version x++ or to downgrade from version x to version x--. Example: false ``` -------------------------------- ### Run Interactive Dart REPL Source: https://pub.dev/packages/flutter_background_service/packages/interactive Shows the simple command to start the `interactive` REPL after installation. ```Shell interactive ``` -------------------------------- ### Initialize and Configure Flutter Background Service Source: https://pub.dev/packages/flutter_background_service/packages/flutter_background_service/versions/5.0.0/example This comprehensive Dart example demonstrates the setup of `flutter_background_service` within a Flutter application's `main.dart`. It includes the `main` function setup, `initializeService` for configuring Android and iOS background execution, setting up `flutter_local_notifications` for foreground service notifications, and defining `onStart` and `onIosBackground` entry points for background tasks. It also shows how to manage service state (foreground/background) and stop the service. ```Dart import 'dart:async'; import 'dart:io'; import 'dart:ui'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:flutter/material.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; import 'package:flutter_background_service_android/flutter_background_service_android.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:shared_preferences/shared_preferences.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await initializeService(); runApp(const MyApp()); } Future initializeService() async { final service = FlutterBackgroundService(); /// OPTIONAL, using custom notification channel id const AndroidNotificationChannel channel = AndroidNotificationChannel( 'my_foreground', // 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(); if (Platform.isIOS || Platform.isAndroid) { await flutterLocalNotificationsPlugin.initialize( const InitializationSettings( iOS: DarwinInitializationSettings(), android: AndroidInitializationSettings('ic_bg_service_small'), ), ); } 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: 'my_foreground', initialNotificationTitle: 'AWESOME SERVICE', initialNotificationContent: 'Initializing', foregroundServiceNotificationId: 888, ), iosConfiguration: IosConfiguration( // auto start service autoStart: true, // this will be executed when app is in foreground in separated isolate onForeground: onStart, // you have to enable background fetch capability on xcode project onBackground: onIosBackground, ), ); service.startService(); } // to ensure this is executed // run app from xcode, then from xcode menu, select Simulate Background Fetch @pragma('vm:entry-point') Future onIosBackground(ServiceInstance service) async { WidgetsFlutterBinding.ensureInitialized(); DartPluginRegistrant.ensureInitialized(); SharedPreferences preferences = await SharedPreferences.getInstance(); await preferences.reload(); final log = preferences.getStringList('log') ?? []; log.add(DateTime.now().toIso8601String()); await preferences.setStringList('log', log); return true; } @pragma('vm:entry-point') void onStart(ServiceInstance service) async { // Only available for flutter 3.0.0 and later DartPluginRegistrant.ensureInitialized(); // For flutter prior to version 3.0.0 // We have to register the plugin manually SharedPreferences preferences = await SharedPreferences.getInstance(); await preferences.setString("hello", "world"); /// OPTIONAL when use custom notification final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); if (service is AndroidServiceInstance) { service.on('setAsForeground').listen((event) { service.setAsForegroundService(); }); service.on('setAsBackground').listen((event) { service.setAsBackgroundService(); }); } service.on('stopService').listen((event) { service.stopSelf(); }); // bring to foreground Timer.periodic(const Duration(seconds: 1), (timer) async { if (service is AndroidServiceInstance) { if (await service.isForegroundService()) { /// OPTIONAL for use custom notification /// the notification id must be equals with AndroidConfiguration when you call configure() method. flutterLocalNotificationsPlugin.show( 888, 'COOL SERVICE', 'Awesome ${DateTime.now()}', const NotificationDetails( android: AndroidNotificationDetails( 'my_foreground', 'MY FOREGROUND SERVICE', ``` -------------------------------- ### Complete Flutter Background Service Initialization and Usage Example Source: https://pub.dev/packages/flutter_background_service/packages/flutter_background_service/versions/3.0.1/example This comprehensive Dart example demonstrates how to set up and utilize the `flutter_background_service` plugin. It includes `main` function setup, `initializeService` for configuring Android and iOS background execution, and `onStart` and `onIosBackground` entry points for background tasks. The example also shows integration with `flutter_local_notifications` for foreground service notifications and `shared_preferences` for data persistence in background tasks. ```Dart import 'dart:async'; import 'dart:io'; import 'dart:ui'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:flutter/material.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; import 'package:flutter_background_service_android/flutter_background_service_android.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:shared_preferences/shared_preferences.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await initializeService(); runApp(const MyApp()); } Future initializeService() async { final service = FlutterBackgroundService(); /// OPTIONAL, using custom notification channel id const AndroidNotificationChannel channel = AndroidNotificationChannel( 'my_foreground', // 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(); if (Platform.isIOS || Platform.isAndroid) { await flutterLocalNotificationsPlugin.initialize( const InitializationSettings( iOS: DarwinInitializationSettings(), android: AndroidInitializationSettings('ic_bg_service_small'), ), ); } 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: 'my_foreground', initialNotificationTitle: 'AWESOME SERVICE', initialNotificationContent: 'Initializing', foregroundServiceNotificationId: 888, ), iosConfiguration: IosConfiguration( // auto start service autoStart: true, // this will be executed when app is in foreground in separated isolate onForeground: onStart, // you have to enable background fetch capability on xcode project onBackground: onIosBackground, ), ); service.startService(); } // to ensure this is executed // run app from xcode, then from xcode menu, select Simulate Background Fetch @pragma('vm:entry-point') Future onIosBackground(ServiceInstance service) async { WidgetsFlutterBinding.ensureInitialized(); DartPluginRegistrant.ensureInitialized(); SharedPreferences preferences = await SharedPreferences.getInstance(); await preferences.reload(); final log = preferences.getStringList('log') ?? []; log.add(DateTime.now().toIso8601String()); await preferences.setStringList('log', log); return true; } @pragma('vm:entry-point') void onStart(ServiceInstance service) async { // Only available for flutter 3.0.0 and later DartPluginRegistrant.ensureInitialized(); // For flutter prior to version 3.0.0 // We have to register the plugin manually SharedPreferences preferences = await SharedPreferences.getInstance(); await preferences.setString("hello", "world"); /// OPTIONAL when use custom notification final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); if (service is AndroidServiceInstance) { service.on('setAsForeground').listen((event) { service.setAsForegroundService(); }); service.on('setAsBackground').listen((event) { service.setAsBackgroundService(); }); } service.on('stopService').listen((event) { service.stopSelf(); }); // bring to foreground Timer.periodic(const Duration(seconds: 1), (timer) async { if (service is AndroidServiceInstance) { if (await service.isForegroundService()) { /// OPTIONAL for use custom notification /// the notification id must be equals with AndroidConfiguration when you call configure() method. flutterLocalNotificationsPlugin.show( 888, 'COOL SERVICE', 'Awesome ${DateTime.now()}', const NotificationDetails( android: AndroidNotificationDetails( 'my_foreground', 'MY FOREGROUND SERVICE', ``` -------------------------------- ### Complete Flutter Background Service Implementation Example Source: https://pub.dev/packages/flutter_background_service/packages/flutter_background_service/versions/2.0.0-dev.0/example This example demonstrates the full setup and usage of the `flutter_background_service` plugin. It includes the main application entry point, service initialization for Android and iOS, background task definitions (`onStart`, `onIosBackground`), handling service events (foreground/background mode, stop), and updating UI elements based on data from the background service. ```Dart import 'dart:async'; import 'dart:io'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:flutter/material.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; import 'package:flutter_background_service_android/flutter_background_service_android.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await initializeService(); runApp(const MyApp()); } Future initializeService() async { final service = FlutterBackgroundService(); await service.configure( androidConfiguration: AndroidConfiguration( // this will executed when app is in foreground or background in separated isolate onStart: onStart, // auto start service autoStart: true, isForegroundMode: true, ), iosConfiguration: IosConfiguration( // auto start service autoStart: true, // this will executed when app is in foreground in separated isolate onForeground: onStart, // you have to enable background fetch capability on xcode project onBackground: onIosBackground, ), ); service.startService(); } // to ensure this executed // run app from xcode, then from xcode menu, select Simulate Background Fetch bool onIosBackground(ServiceInstance service) { WidgetsFlutterBinding.ensureInitialized(); print('FLUTTER BACKGROUND FETCH'); return true; } void onStart(ServiceInstance service) { if (service is AndroidServiceInstance) { service.on('setAsForeground').listen((event) { service.setAsForegroundService(); }); service.on('setAsBackground').listen((event) { service.setAsBackgroundService(); }); } service.on('stopService').listen((event) { service.stopSelf(); }); // bring to foreground Timer.periodic(const Duration(seconds: 1), (timer) async { if (service is AndroidServiceInstance) { service.setForegroundNotificationInfo( title: "My App Service", content: "Updated at ${DateTime.now()}", ); } /// you can see this log in logcat print('FLUTTER BACKGROUND SERVICE: ${DateTime.now()}'); // test using external plugin final deviceInfo = DeviceInfoPlugin(); String? device; if (Platform.isAndroid) { final androidInfo = await deviceInfo.androidInfo; device = androidInfo.model; } if (Platform.isIOS) { final iosInfo = await deviceInfo.iosInfo; device = iosInfo.model; } service.invoke( 'update', { "current_date": DateTime.now().toIso8601String(), "device": device, }, ); }); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State { String text = "Stop Service"; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Service App'), ), body: Column( children: [ StreamBuilder?>( stream: FlutterBackgroundService().on('update'), builder: (context, snapshot) { if (!snapshot.hasData) { return const Center( child: CircularProgressIndicator(), ); } final data = snapshot.data!; String? device = data["device"]; DateTime? date = DateTime.tryParse(data["current_date"]); return Column( children: [ Text(device ?? 'Unknown'), Text(date.toString()), ], ); }, ), ElevatedButton( child: const Text("Foreground Mode"), onPressed: () { FlutterBackgroundService().invoke("setAsForeground"); }, ), ElevatedButton( child: const Text("Background Mode"), onPressed: () { FlutterBackgroundService().invoke("setAsBackground"); }, ), ElevatedButton( child: Text(text), onPressed: () async { final service = FlutterBackgroundService(); var isRunning = await service.isRunning(); if (isRunning) { ``` -------------------------------- ### Run RxDart Web Examples Source: https://pub.dev/packages/flutter_background_service/packages/rxdart Instructions to set up and run the web examples for the RxDart package, typically found in the 'example' folder of the cloned repository. ```Shell dart pub get dart run build_runner serve example ``` -------------------------------- ### Example: Enabling Calendar Permission in iOS Podfile Source: https://pub.dev/packages/flutter_background_service/packages/permission_handler This specific example illustrates how to enable calendar access by uncommenting the relevant line in the Podfile configuration. It shows the `PERMISSION_EVENTS=1` macro, which corresponds to `PermissionGroup.calendar`. ```Ruby ## dart: PermissionGroup.calendar 'PERMISSION_EVENTS=1', ``` -------------------------------- ### Schedule Weekly Notification on Specific Day and Time (Flutter/Dart) Source: https://pub.dev/packages/flutter_background_service/packages/flutter_local_notifications/versions/0.3 This example shows how to schedule a notification to appear weekly on a designated day and time. It sets up notification details for both Android and iOS platforms. ```Dart var time = new Time(10, 0, 0); var androidPlatformChannelSpecifics = new AndroidNotificationDetails('show weekly channel id', 'show weekly channel name', 'show weekly description'); var iOSPlatformChannelSpecifics = new IOSNotificationDetails(); var platformChannelSpecifics = new NotificationDetails( androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics); await flutterLocalNotificationsPlugin.showWeeklyAtDayAndTime( 0, 'show weekly title', 'Weekly notification shown on Monday at approximately ${_toTwoDigitString(time.hour)}:${_toTwoDigitString(time.minute)}:${_toTwoDigitString(time.second)}', Day.Monday, time, platformChannelSpecifics); ``` -------------------------------- ### Flutter Image Picker Example Application Setup Source: https://pub.dev/packages/flutter_background_service/packages/image_picker/example This Dart code provides the main entry point and initial setup for a Flutter application demonstrating the `image_picker` plugin. It includes the basic `MaterialApp` and `MyHomePage` widget structure, along with state management for selected media files, error handling, and controllers for image picking options like `maxWidth`, `maxHeight`, and `quality`. It also shows how to initialize and manage `VideoPlayerController` for video playback and handles different media picking scenarios (single image, multi-image, video, media). ```Dart // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: public_member_api_docs import 'dart:async'; import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'package:mime/mime.dart'; import 'package:video_player/video_player.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Image Picker Demo', home: MyHomePage(title: 'Image Picker Example'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, this.title}); final String? title; @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { List? _mediaFileList; void _setImageFileListFromFile(XFile? value) { _mediaFileList = value == null ? null : [value]; } dynamic _pickImageError; bool isVideo = false; VideoPlayerController? _controller; VideoPlayerController? _toBeDisposed; String? _retrieveDataError; final ImagePicker _picker = ImagePicker(); final TextEditingController maxWidthController = TextEditingController(); final TextEditingController maxHeightController = TextEditingController(); final TextEditingController qualityController = TextEditingController(); final TextEditingController limitController = TextEditingController(); Future _playVideo(XFile? file) async { if (file != null && mounted) { await _disposeVideoController(); late VideoPlayerController controller; if (kIsWeb) { controller = VideoPlayerController.networkUrl(Uri.parse(file.path)); } else { controller = VideoPlayerController.file(File(file.path)); } _controller = controller; // In web, most browsers won't honor a programmatic call to .play // if the video has a sound track (and is not muted). // Mute the video so it auto-plays in web! // This is not needed if the call to .play is the result of user // interaction (clicking on a "play" button, for example). const double volume = kIsWeb ? 0.0 : 1.0; await controller.setVolume(volume); await controller.initialize(); await controller.setLooping(true); await controller.play(); setState(() {}); } } Future _onImageButtonPressed( ImageSource source, { required BuildContext context, bool isMultiImage = false, bool isMedia = false, }) async { if (_controller != null) { await _controller!.setVolume(0.0); } if (context.mounted) { if (isVideo) { final XFile? file = await _picker.pickVideo( source: source, maxDuration: const Duration(seconds: 10)); await _playVideo(file); } else if (isMultiImage) { await _displayPickImageDialog(context, true, (double? maxWidth, double? maxHeight, int? quality, int? limit) async { try { final List pickedFileList = isMedia ? await _picker.pickMultipleMedia( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: quality, limit: limit, ) : await _picker.pickMultiImage( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: quality, limit: limit, ); setState(() { _mediaFileList = pickedFileList; }); } catch (e) { setState(() { _pickImageError = e; }); } }); } else if (isMedia) { await _displayPickImageDialog(context, false, (double? maxWidth, double? maxHeight, int? quality, int? limit) async { try { final List pickedFileList = []; final XFile? media = await _picker.pickMedia( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: quality, ); if (media != null) { pickedFileList.add(media); setState(() { ``` -------------------------------- ### Flutter Background Service: Initialization and UI Interaction Example Source: https://pub.dev/packages/flutter_background_service/packages/flutter_background_service/versions/0.1.0-nullsafety.1/example This comprehensive example demonstrates how to initialize and manage a Flutter background service. It includes the main application setup, the `onStart` callback for background execution, and UI elements to interact with the service, such as setting foreground/background mode, stopping the service, and displaying data received from the background. ```Dart import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); FlutterBackgroundService.initialize(onStart); runApp(MyApp()); } void onStart() { WidgetsFlutterBinding.ensureInitialized(); final service = FlutterBackgroundService(); service.onDataReceived.listen((event) { if (event["action"] == "setAsForeground") { service.setForegroundMode(true); return; } if (event["action"] == "setAsBackground") { service.setForegroundMode(false); } if (event["action"] == "stopService") { service.stopBackgroundService(); } }); // bring to foreground service.setForegroundMode(true); Timer.periodic(Duration(seconds: 1), (timer) async { if (!(await service.isServiceRunning())) timer.cancel(); service.setNotificationInfo( title: "My App Service", content: "Updated at ${DateTime.now()}", ); service.sendData( {"current_date": DateTime.now().toIso8601String()}, ); }); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State { String text = "Stop Service"; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Service App'), ), body: Column( children: [ StreamBuilder>( stream: FlutterBackgroundService().onDataReceived, builder: (context, snapshot) { if (!snapshot.hasData) { return Center( child: CircularProgressIndicator(), ); } final data = snapshot.data; DateTime date = DateTime.tryParse(data["current_date"]); return Text(date.toString()); }, ), RaisedButton( child: Text("Foreground Mode"), onPressed: () { FlutterBackgroundService() .sendData({"action": "setAsForeground"}); }, ), RaisedButton( child: Text("Background Mode"), onPressed: () { FlutterBackgroundService() .sendData({"action": "setAsBackground"}); }, ), RaisedButton( child: Text(text), onPressed: () async { var isRunning = await FlutterBackgroundService().isServiceRunning(); if (isRunning) { FlutterBackgroundService().sendData( {"action": "stopService"}, ); } else { FlutterBackgroundService.initialize(onStart); } if (!isRunning) { text = 'Stop Service'; } else { text = 'Start Service'; n} setState(() {}); }, ), ], ), floatingActionButton: FloatingActionButton( onPressed: () { FlutterBackgroundService().sendData({ "hello": "world", }); }, child: Icon(Icons.play_arrow), ), ), ); } } ``` -------------------------------- ### Show a Notification Periodically Source: https://pub.dev/packages/flutter_background_service/packages/flutter_local_notifications/versions/0.3 This example demonstrates how to configure a notification to repeat at a specified interval, such as every minute. It uses the `flutterLocalNotificationsPlugin.periodicallyShow` method along with a `RepeatInterval` enum value to achieve this recurring notification behavior. ```Dart // Show a notification every minute with the first appearance happening a minute after invoking the method var androidPlatformChannelSpecifics = new AndroidNotificationDetails('repeating channel id', 'repeating channel name', 'repeating description'); var iOSPlatformChannelSpecifics = new IOSNotificationDetails(); var platformChannelSpecifics = new NotificationDetails( androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics); await flutterLocalNotificationsPlugin.periodicallyShow(0, 'repeating title', 'repeating body', RepeatInterval.EveryMinute, platformChannelSpecifics); ``` -------------------------------- ### Run RxDart Flutter Examples Source: https://pub.dev/packages/flutter_background_service/packages/rxdart Instructions to set up and run the Flutter examples for the RxDart package, including dependency checks and running the application after navigating to the example directory. ```Shell flutter doctor flutter packages get flutter run ``` -------------------------------- ### Basic Shelf Server Example Source: https://pub.dev/packages/flutter_background_service/packages/shelf Demonstrates how to set up a basic web server using the Shelf package, including request logging and a simple echo handler. It initializes a pipeline with middleware and a handler, then serves it on localhost. ```Dart import 'package:shelf/shelf.dart'; import 'package:shelf/shelf_io.dart' as shelf_io; void main() async { var handler = const Pipeline().addMiddleware(logRequests()).addHandler(_echoRequest); var server = await shelf_io.serve(handler, 'localhost', 8080); // Enable content compression server.autoCompress = true; print('Serving at http://${server.address.host}:${server.port}'); } Response _echoRequest(Request request) => Response.ok('Request for "${request.url}"'); ``` -------------------------------- ### Cancel All Local Notifications on First App Install (iOS < 10) Source: https://pub.dev/packages/flutter_background_service/packages/flutter_local_notifications/versions/0.3 This Objective-C snippet, to be added to the `didFinishLaunchingWithOptions` method of `AppDelegate`, prevents 'old' periodically shown notifications from firing after an app reinstallation on iOS versions older than 10. It checks a `NSUserDefaults` flag to ensure `cancelAllLocalNotifications` is called only once upon the very first launch after installation. ```Objective-C if(![[NSUserDefaults standardUserDefaults]objectForKey:@"Notification"]){ [[UIApplication sharedApplication] cancelAllLocalNotifications]; [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"Notification"]; } ``` -------------------------------- ### Run RxDart Command Line Examples Source: https://pub.dev/packages/flutter_background_service/packages/rxdart Instructions to set up and run the command-line examples for the RxDart package, such as the Fibonacci example. ```Shell pub get dart examples/fibonacci/lib/example.dart 10 ``` -------------------------------- ### Show Repeating Local Notification Source: https://pub.dev/packages/flutter_background_service/packages/flutter_local_notifications/versions/0.4 This example illustrates how to configure a notification to repeat at a specified interval, such as every minute. The `periodicallyShow` method is used, along with platform-specific details, to ensure the notification reappears automatically after its initial display. ```Dart // Show a notification every minute with the first appearance happening a minute after invoking the method var androidPlatformChannelSpecifics = new AndroidNotificationDetails('repeating channel id', 'repeating channel name', 'repeating description'); var iOSPlatformChannelSpecifics = new IOSNotificationDetails(); var platformChannelSpecifics = new NotificationDetails( androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics); await flutterLocalNotificationsPlugin.periodicallyShow(0, 'repeating title', 'repeating body', RepeatInterval.EveryMinute, platformChannelSpecifics); ``` -------------------------------- ### Start, Execute, and Stop Docker Container Process Source: https://pub.dev/packages/flutter_background_service/packages/docker_process This example demonstrates how to use the docker_process package to start a Docker container, execute a command inside it, capture its standard output, and then stop the container. It utilizes `DockerProcess.start` to launch the container, `dp.exec` to run a command, and `dp.stop` for cleanup. ```Dart import 'package:docker_process/docker_process.dart'; Future main() async { final dp = await DockerProcess.start( image: 'image-name', name: 'running-name', readySignal: (line) => line.contains('Done.'), ); final pr = await dp.exec(['ls', '-l']); print(pr.stdout); await dp.stop(); } ``` -------------------------------- ### Complete Example: Initializing and Running Flutter Background Service Source: https://pub.dev/packages/flutter_background_service/packages/flutter_background_service/versions/2.2.1/example This comprehensive Dart code snippet demonstrates the full setup and usage of the `flutter_background_service` plugin. It includes the main application entry point, service initialization for Android and iOS, the background service's `onStart` logic for periodic tasks and inter-process communication, and a basic Flutter UI to display updates from the background service and control its state. ```Dart import 'dart:async'; import 'dart:io'; import 'dart:ui'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:flutter/material.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; import 'package:flutter_background_service_android/flutter_background_service_android.dart'; import 'package:shared_preferences/shared_preferences.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await initializeService(); runApp(const MyApp()); } Future initializeService() async { final service = FlutterBackgroundService(); 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, ), iosConfiguration: IosConfiguration( // auto start service autoStart: true, // this will be executed when app is in foreground in separated isolate onForeground: onStart, // you have to enable background fetch capability on xcode project onBackground: onIosBackground, ), ); service.startService(); } // to ensure this is executed // run app from xcode, then from xcode menu, select Simulate Background Fetch bool onIosBackground(ServiceInstance service) { WidgetsFlutterBinding.ensureInitialized(); print('FLUTTER BACKGROUND FETCH'); return true; } @pragma('vm:entry-point') void onStart(ServiceInstance service) async { // Only available for flutter 3.0.0 and later DartPluginRegistrant.ensureInitialized(); // For flutter prior to version 3.0.0 // We have to register the plugin manually SharedPreferences preferences = await SharedPreferences.getInstance(); await preferences.setString("hello", "world"); if (service is AndroidServiceInstance) { service.on('setAsForeground').listen((event) { service.setAsForegroundService(); }); service.on('setAsBackground').listen((event) { service.setAsBackgroundService(); }); } service.on('stopService').listen((event) { service.stopSelf(); }); // bring to foreground Timer.periodic(const Duration(seconds: 1), (timer) async { final hello = preferences.getString("hello"); print(hello); if (service is AndroidServiceInstance) { service.setForegroundNotificationInfo( title: "My App Service", content: "Updated at ${DateTime.now()}", ); } /// you can see this log in logcat print('FLUTTER BACKGROUND SERVICE: ${DateTime.now()}'); // test using external plugin final deviceInfo = DeviceInfoPlugin(); String? device; if (Platform.isAndroid) { final androidInfo = await deviceInfo.androidInfo; device = androidInfo.model; } if (Platform.isIOS) { final iosInfo = await deviceInfo.iosInfo; device = iosInfo.model; } service.invoke( 'update', { "current_date": DateTime.now().toIso8601String(), "device": device, }, ); }); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State createState() => _MyAppState(); } class _MyAppState extends State { String text = "Stop Service"; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Service App'), ), body: Column( children: [ StreamBuilder?>( stream: FlutterBackgroundService().on('update'), builder: (context, snapshot) { if (!snapshot.hasData) { return const Center( child: CircularProgressIndicator(), ); } final data = snapshot.data!; String? device = data["device"]; DateTime? date = DateTime.tryParse(data["current_date"]); return Column( children: [ Text(device ?? 'Unknown'), Text(date.toString()), ], ); }, ), ElevatedButton( child: const Text("Foreground Mode"), onPressed: () { FlutterBackgroundService().invoke("setAsForeground"); }, ) ] ) ) ); } } ``` -------------------------------- ### Get App Launch Details from Notification Source: https://pub.dev/packages/flutter_background_service/packages/flutter_local_notifications/versions/19.0.0-dev This snippet retrieves details about whether the application was launched by tapping on a notification created by this plugin. This information is crucial for handling deep links or specific actions when the app starts from a notification. ```Dart final NotificationAppLaunchDetails? notificationAppLaunchDetails = await flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails(); ``` -------------------------------- ### Run unit tests for vector_math package Source: https://pub.dev/packages/flutter_background_service/documentation/vector_math/latest Command to execute the unit tests for the `vector_math` package from the project's root directory. ```bash dart test ``` -------------------------------- ### Complete Flutter Background Service Example Source: https://pub.dev/packages/flutter_background_service/packages/flutter_background_service/versions/5.0.5/example This comprehensive example demonstrates how to set up and use the `flutter_background_service` plugin to run Dart code continuously in the background on both Android and iOS. It includes service initialization, notification channel setup, and handlers for background tasks and service control. ```Dart import 'dart:async'; import 'dart:io'; import 'dart:ui'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:flutter/material.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; import 'package:flutter_background_service_android/flutter_background_service_android.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:shared_preferences/shared_preferences.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await initializeService(); runApp(const MyApp()); } Future initializeService() async { final service = FlutterBackgroundService(); /// OPTIONAL, using custom notification channel id const AndroidNotificationChannel channel = AndroidNotificationChannel( 'my_foreground', // 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(); if (Platform.isIOS || Platform.isAndroid) { await flutterLocalNotificationsPlugin.initialize( const InitializationSettings( iOS: DarwinInitializationSettings(), android: AndroidInitializationSettings('ic_bg_service_small'), ), ); } 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: 'my_foreground', initialNotificationTitle: 'AWESOME SERVICE', initialNotificationContent: 'Initializing', foregroundServiceNotificationId: 888, ), iosConfiguration: IosConfiguration( // auto start service autoStart: true, // this will be executed when app is in foreground in separated isolate onForeground: onStart, // you have to enable background fetch capability on xcode project onBackground: onIosBackground, ), ); } // to ensure this is executed // run app from xcode, then from xcode menu, select Simulate Background Fetch @pragma('vm:entry-point') Future onIosBackground(ServiceInstance service) async { WidgetsFlutterBinding.ensureInitialized(); DartPluginRegistrant.ensureInitialized(); SharedPreferences preferences = await SharedPreferences.getInstance(); await preferences.reload(); final log = preferences.getStringList('log') ?? []; log.add(DateTime.now().toIso8601String()); await preferences.setStringList('log', log); return true; } @pragma('vm:entry-point') void onStart(ServiceInstance service) async { // Only available for flutter 3.0.0 and later DartPluginRegistrant.ensureInitialized(); // For flutter prior to version 3.0.0 // We have to register the plugin manually SharedPreferences preferences = await SharedPreferences.getInstance(); await preferences.setString("hello", "world"); /// OPTIONAL when use custom notification final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); if (service is AndroidServiceInstance) { service.on('setAsForeground').listen((event) { service.setAsForegroundService(); }); service.on('setAsBackground').listen((event) { service.setAsBackgroundService(); }); } service.on('stopService').listen((event) { service.stopSelf(); }); // bring to foreground Timer.periodic(const Duration(seconds: 1), (timer) async { if (service is AndroidServiceInstance) { if (await service.isForegroundService()) { /// OPTIONAL for use custom notification /// the notification id must be equals with AndroidConfiguration when you call configure() method. flutterLocalNotificationsPlugin.show( 888, 'COOL SERVICE', 'Awesome ${DateTime.now()}', const NotificationDetails( android: AndroidNotificationDetails( 'my_foreground', 'MY FOREGROUND SERVICE', icon: 'ic_bg_service_small', ``` -------------------------------- ### Install Equatable Package Source: https://pub.dev/packages/flutter_background_service/packages/equatable This snippet provides commands to install the `equatable` package using `pub get` for Dart or `flutter packages get` for Flutter projects. This fetches the package dependencies. ```Shell # Dart pub get # Flutter flutter packages get ``` -------------------------------- ### Run Sentry Dart Example Project Source: https://pub.dev/packages/flutter_background_service/packages/sentry/example Commands to set up and run the example project for the `sentry` Dart package. This process fetches necessary dependencies and then executes the main application, which is designed to throw an error and send it to Sentry.io for testing purposes. ```Shell dart pub get dart run ```