This plugin is used to implement a foreground service on the Android platform.

pub package

Features

  • Can perform repetitive task with foreground service notification.
  • Provides useful utilities (minimizeApp, wakeUpScreen, etc.) that can use when performing task.
  • Provides a widget that prevents the app from closing when a foreground task is running.
  • Provides a widget that can start a foreground task when trying to minimize or close the app.
  • Can automatically resume foreground task at boot time.

Getting started

To use this plugin, add flutter_foreground_task as a dependency in your pubspec.yaml file. For example:

dependencies:
  flutter_foreground_task: ^2.2.1

After adding the flutter_foreground_task plugin to the flutter project, we need to specify the permissions and services to use for this plugin to work properly.

:baby_chick: Android

Since this plugin is based on a foreground service, we need to add the following permission to the AndroidManifest.xml file. Open the AndroidManifest.xml file and specify it between the <manifest> and <application> tags.

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

And we need to add this permission to automatically resume foreground task at boot time.

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

And specify the service inside the <application> tag as follows.

<service android:name="com.pravera.flutter_foreground_task.service.ForegroundService" />

:baby_chick: iOS

We can also launch flutter_foreground_task on iOS platform. However, it has the following limitations.

  • Works only on iOS 10.0 or later.
  • If the app is forcibly closed, the task will not work.
  • Task cannot be started automatically on device reboot.

Objective-C:

  1. To use this plugin developed in Swift language in a project using Objective-C, you need to add a bridge header. If you don't have an ios/Runner/Runner-Bridging-Header.h file in your project, check this page.

  2. Open the ios/Runner/AppDelegate.swift file and add the commented code.

#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"

// here
#import <flutter_foreground_task/FlutterForegroundTaskPlugin.h>

// here
void registerPlugins(NSObject<FlutterPluginRegistry>* registry) {
  [GeneratedPluginRegistrant registerWithRegistry:registry];
}

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];
  [FlutterForegroundTaskPlugin setPluginRegistrantCallback:registerPlugins];  // here
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

@end

Swift:

  1. Declare the import statement below in the ios/Runner/Runner-Bridging-Header.h file.
#import <flutter_foreground_task/FlutterForegroundTaskPlugin.h>
  1. Open the ios/Runner/AppDelegate.swift file and add the commented code.
import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    SwiftFlutterForegroundTaskPlugin.setPluginRegistrantCallback(registerPlugins)   // here
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

// here
func registerPlugins(registry: FlutterPluginRegistry) {
  GeneratedPluginRegistrant.register(with: registry)
}

How to use

This plugin has two ways to start a foreground task. There are two ways to start the foreground task manually and to start it when the app is minimized or closed by the WillStartForegroundTask widget.

:hatched_chick: Start manually

  1. Initialize the FlutterForegroundTask. FlutterForegroundTask.init() provides notification and task options, detailed options are as follows:
  • androidNotificationOptions: Notification options for Android platform.
  • iosNotificationOptions: Notification options for iOS platform.
  • foregroundTaskOptions: Options for setting the foreground task behavior in detail.
  • printDevLog: Whether to show the developer log. If this value is set to true, you can see logs of the activity (start, stop, etc) of the flutter_foreground_task plugin. It does not work in release mode. The default is false.
void _initForegroundTask() {
  FlutterForegroundTask.init(
    androidNotificationOptions: AndroidNotificationOptions(
      channelId: 'notification_channel_id',
      channelName: 'Foreground Notification',
      channelDescription: 'This notification appears when a foreground task is running.',
      channelImportance: NotificationChannelImportance.LOW,
      priority: NotificationPriority.LOW,
      iconData: NotificationIconData(
        resType: ResourceType.mipmap,
        resPrefix: ResourcePrefix.ic,
        name: 'launcher',
      ),
    ),
    iosNotificationOptions: IOSNotificationOptions(
      showNotification: true,
      playSound: false,
    ),
    foregroundTaskOptions: ForegroundTaskOptions(
      interval: 5000,
      autoRunOnBoot: true,
    ),
    printDevLog: true,
  );
}

@override
void initState() {
  super.initState();
  _initForegroundTask();
}
  1. Add WithForegroundTask widget to prevent the app from closing when a foreground task is running.
@override
Widget build(BuildContext context) {
  return MaterialApp(
    // A widget that prevents the app from closing when a foreground task is running.
    // Declare on top of the [Scaffold] widget.
    home: WithForegroundTask(
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter Foreground Task'),
          centerTitle: true,
        ),
        body: buildContentView(),
      ),
    ),
  );
}
  1. Write a foreground task start callback function and start the FlutterForegroundTask. FlutterForegroundTask.start() provides the following options:
  • notificationTitle: The title that will be displayed in the notification.
  • notificationText: The text that will be displayed in the notification.
  • callback: A top-level function that calls the initDispatcher function.
// The callback function should always be a top-level function.
void startCallback() {
  // The initDispatcher function must be called to handle the task in the background.
  // And the code to be executed except for the variable declaration
  // must be written inside the initDispatcher function.
  FlutterForegroundTask.initDispatcher((timestamp, sendPort) async {
    final strTimestamp = timestamp.toString();
    print('timestamp: $strTimestamp');

    // Send data to the main isolate.
    sendPort?.send(timestamp);
  }, onDestroy: (timestamp) async {
    print('Dispatcher is dead.. x_x');
  });
}

class ExampleApp extends StatefulWidget {
  @override
  _ExampleAppState createState() => _ExampleAppState();
}

class _ExampleAppState extends State<ExampleApp> {
  ReceivePort? _receivePort;

  // ...

  void _startForegroundTask() async {
    _receivePort = FlutterForegroundTask.start(
      notificationTitle: 'Foreground task is running',
      notificationText: 'Tap to return to the app',
      callback: startCallback,
    );

    _receivePort?.listen((message) {
      if (message is DateTime)
        print('receive timestamp: $message');
    });
  }

  @override
  void dispose() {
    _receivePort?.close();
    super.dispose();
  }
}

If the plugin you want to use provides a stream, use it like this:

void startCallback() {
  final positionStream = Geolocator.getPositionStream();
  StreamSubscription<Position>? streamSubscription;

  FlutterForegroundTask.initDispatcher((timestamp, sendPort) async {
    if (streamSubscription != null) return;

    streamSubscription = positionStream.listen((event) {
      print('timestamp: ${timestamp.toString()}');

      FlutterForegroundTask.update(
          notificationTitle: 'Current Position',
          notificationText: '${event.latitude}, ${event.longitude}');
    });
  }, onDestroy: (timestamp) async {
    await streamSubscription?.cancel();
    print('Dispatcher is dead.. x_x');
  });
}
  1. Use FlutterForegroundTask.update() to update the foreground task. The options are the same as the start function.
// The callback function should always be a top-level function.
void startCallback() {
  int updateCount = 0;

  FlutterForegroundTask.initDispatcher((timestamp, sendPort) async {
    final strTimestamp = timestamp.toString();
    print('startCallback - timestamp: $strTimestamp');

    FlutterForegroundTask.update(
        notificationTitle: 'startCallback',
        notificationText: strTimestamp,
        callback: updateCount >= 10 ? updateCallback : null);

    updateCount++;
  }, onDestroy: (timestamp) async {
    print('Dispatcher is dead.. x_x');
  });
}

void updateCallback() {
  FlutterForegroundTask.initDispatcher((timestamp, sendPort) async {
    final strTimestamp = timestamp.toString();
    print('updateCallback - timestamp: $strTimestamp');

    FlutterForegroundTask.update(
        notificationTitle: 'updateCallback',
        notificationText: strTimestamp);
  }, onDestroy: (timestamp) async {
    print('Dispatcher is dead.. x_x');
  });
}
  1. When you have completed the required foreground task, call FlutterForegroundTask.stop().
void _stopForegroundTask() {
  FlutterForegroundTask.stop();
}

:hatched_chick: Start with WillStartForegroundTask widget

@override
Widget build(BuildContext context) {
  return MaterialApp(
    // A widget used when you want to start a foreground task when trying to minimize or close the app.
    // Declare on top of the [Scaffold] widget.
    home: WillStartForegroundTask(
      onWillStart: () {
        // Please return whether to start the foreground task.
        return true;
      },
      androidNotificationOptions: AndroidNotificationOptions(
        channelId: 'notification_channel_id',
        channelName: 'Foreground Notification',
        channelDescription: 'This notification appears when a foreground task is running.',
        channelImportance: NotificationChannelImportance.LOW,
        priority: NotificationPriority.LOW,
        iconData: NotificationIconData(
          resType: ResourceType.mipmap,
          resPrefix: ResourcePrefix.ic,
          name: 'launcher',
        ),
      ),
      iosNotificationOptions: IOSNotificationOptions(
        showNotification: true,
        playSound: false,
      ),
      foregroundTaskOptions: ForegroundTaskOptions(
        interval: 5000,
        autoRunOnBoot: false,
      ),
      printDevLog: true,
      notificationTitle: 'Foreground task is running',
      notificationText: 'Tap to return to the app',
      callback: callback,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter Foreground Task'),
          centerTitle: true,
        ),
        body: buildContentView(),
      ),
    ),
  );
}

Models

:chicken: AndroidNotificationOptions

Notification options for Android platform.

Property Description
channelId Unique ID of the notification channel.
channelName The name of the notification channel. This value is displayed to the user in the notification settings.
channelDescription The description of the notification channel. This value is displayed to the user in the notification settings.
channelImportance The importance of the notification channel. The default is NotificationChannelImportance.DEFAULT.
priority Priority of notifications for Android 7.1 and lower. The default is NotificationPriority.DEFAULT.
enableVibration Whether to enable vibration when creating notifications. The default is false.
playSound Whether to play sound when creating notifications. The default is false.
showWhen Whether to show the timestamp when the notification was created in the content view. The default is false.
visibility Control the level of detail displayed in notifications on the lock screen. The default is NotificationVisibility.VISIBILITY_PUBLIC.
iconData The data of the icon to display in the notification. If the value is null, the app launcher icon is used.

:chicken: NotificationIconData

Data for setting the notification icon.

Property Description
resType The resource type of the notification icon. If the resource is in the drawable folder, set it to ResourceType.drawable, if the resource is in the mipmap folder, set it to ResourceType.mipmap.
resPrefix The resource prefix of the notification icon. If the notification icon name is ic_simple_notification, set it to ResourcePrefix.ic and set name to simple_notification.
name Notification icon name without prefix.

:chicken: ResourceType

The resource type of the notification icon.

Value Description
drawable A resources in the drawable folder. The drawable folder is where all kinds of images are stored.
mipmap A resources in the mipmap folder. The mipmap folder is usually where the launcher icon image is stored.

:chicken: ResourcePrefix

The resource prefix of the notification icon.

Value Description
ic A resources with the ic_ prefix.
img A resources with the img_ prefix.

:chicken: IOSNotificationOptions

Notification options for iOS platform.

Property Description
showNotification Whether to show notifications. The default is true.
playSound Whether to play sound when creating notifications. The default is false.

:chicken: ForegroundTaskOptions

Data class with foreground task options.

Property Description
interval The task call interval in milliseconds. The default is 5000.
autoRunOnBoot Whether to automatically run foreground task on boot. The default is false.

:chicken: NotificationChannelImportance

The importance of the notification channel. See https://developer.android.com/training/notify-user/channels?hl=ko#importance

Value Description
NONE A notification with no importance: does not show in the shade.
MIN Min notification importance: only shows in the shade, below the fold.
LOW Low notification importance: shows in the shade, and potentially in the status bar (see shouldHideSilentStatusBarIcons()), but is not audibly intrusive.
DEFAULT Default notification importance: shows everywhere, makes noise, but does not visually intrude.
HIGH Higher notification importance: shows everywhere, makes noise and peeks. May use full screen intents.
MAX Max notification importance: same as HIGH, but generally not used.

:chicken: NotificationPriority

Priority of notifications for Android 7.1 and lower.

Value Description
MIN No sound and does not appear in the status bar.
LOW No sound.
DEFAULT Makes a sound.
HIGH Makes a sound and appears as a heads-up notification.
MAX Same as HIGH, but used when you want to notify notification immediately.

:chicken: NotificationVisibility

The level of detail displayed in notifications on the lock screen.

Value Description
VISIBILITY_PUBLIC Show this notification in its entirety on all lockscreens.
VISIBILITY_SECRET Do not reveal any part of this notification on a secure lockscreen.
VISIBILITY_PRIVATE Show this notification on all lockscreens, but conceal sensitive or private information on secure lockscreens.

Utility methods

:lollipop: minimizeApp

Minimize the app to the background.

import 'package:flutter_foreground_task/flutter_foreground_task.dart';

void function() {
  FlutterForegroundTask.minimizeApp();
}

:lollipop: wakeUpScreen

Wake up the screen of a device that is turned off.

import 'package:flutter_foreground_task/flutter_foreground_task.dart';

void function() {
  FlutterForegroundTask.wakeUpScreen();
}

:lollipop: isIgnoringBatteryOptimizations

Returns whether the app has been excluded from battery optimization.

import 'package:flutter_foreground_task/flutter_foreground_task.dart';

void function() async {
  var isIgnoring = await FlutterForegroundTask.isIgnoringBatteryOptimizations;
}

:lollipop: openIgnoreBatteryOptimizationSettings

Open the settings page where you can set ignore battery optimization.

import 'package:flutter_foreground_task/flutter_foreground_task.dart';

void function() async {
  var isIgnoring = await FlutterForegroundTask.openIgnoreBatteryOptimizationSettings();
}

Support

If you find any bugs or issues while using the plugin, please register an issues on GitHub. You can also contact us at hwj930513@naver.com.