Skip to main content

awesome_notifications_foreground_service 1.0.0-dev.7 copy "awesome_notifications_foreground_service: ^1.0.0-dev.7" to clipboard
awesome_notifications_foreground_service: ^1.0.0-dev.7 copied to clipboard

PlatformAndroid

Android foreground services for awesome_notifications: keep the app's work running, shown to the user as an awesome notification, with one call to start, update and stop it.

awesome_notifications_foreground_service #

Awesome Notifications

Flutter Firebase Discord

Open Source Love pub package Full tests workflow codecov badge

Android foreground services for awesome_notifications: keep a download, a recording or any work the user is aware of running while your app is in background, shown as an awesome notification.

A download in the app and its foreground service's notification on Android

A download started in the example app (left) and the notification of its foreground service on Android, with its progress and a Stop button (right).


Key Features: #

  • One call starts the service and shows its notification; the same call updates it, and another one stops it.
  • A regular awesome notification: every layout, image, progress bar, action button and event.
  • Every service type up to Android 15, and the four start modes.
  • Stops from the notification: a button, or a tap, that dismisses it ends the service.
  • Errors reach your app: a request Android would close the app for is answered as a PlatformException.
  • Safe everywhere: on the other platforms the calls do nothing, no check needed.

πŸ“¦ The awesome_notifications family #

Every package of the family, and where each one runs:

Package Android iOS macOS Windows Linux Web
awesome_notifications (the core) βœ… βœ… βœ… πŸ§ͺ πŸ§ͺ πŸ§ͺ
awesome_notifications_schedules βœ… βœ… βœ… πŸ§ͺ πŸ§ͺ ❌
awesome_notifications_localizations βœ… βœ… βœ… πŸ§ͺ πŸ§ͺ ⏳
awesome_notifications_fcm βœ… βœ… βœ… ⏳ ⏳ ⏳
awesome_notifications_chat βœ… βœ… βœ… ⏳ ⏳ ⏳
awesome_notifications_media βœ… βœ… βœ… πŸ§ͺ πŸ§ͺ πŸ§ͺ
awesome_notifications_calls βœ… βœ… πŸ§ͺ πŸ§ͺ πŸ§ͺ πŸ§ͺ
awesome_notifications_live_activities βœ… βœ… πŸ§ͺ πŸ§ͺ πŸ§ͺ πŸ§ͺ
awesome_notifications_foreground_service (this package) βœ… ❌ ❌ ❌ ❌ ❌

βœ… supported Β· πŸ§ͺ preview (implemented, still being validated against the 0.12.1 behavior) Β· ⏳ planned Β· ❌ not possible on this platform


πŸ“™ Table of Contents #


πŸ“± Platform support #

Platform What happens Minimum
Android A foreground service with its notification Android 7.0 (API 24)
iOS, macOS, Windows, Linux and Web Nothing: the calls complete and do nothing β€”

Foreground services only exist on Android. There is no equivalent on the other platforms, so don't count on them to keep your app running there.


πŸ›  Getting started #

dependencies:
  awesome_notifications: ^1.0.0-dev.7
  awesome_notifications_foreground_service: ^1.0.0-dev.7

Initialize the core as usual, with a channel for your service, and ask for the notification permission: without it the service runs, but Android 13+ hides its notification.

await AwesomeNotifications().initialize(
  'resource://drawable/res_notification_icon',
  [
    NotificationChannel(
      channelKey: 'services',
      channelName: 'Services',
      channelDescription: 'What the app does in background',
      // Updated often: no sound, no heads-up.
      importance: NotificationImportance.Low,
    ),
  ],
);

πŸ€– Configuring Android #

The package brings the service, but no type nor permission, so your app only asks for what it needs. Declare the types your service uses, and their permissions, in your android/app/src/main/AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    <!-- Android 14+: the permission of each type -->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC"/>

    <application>
        <service
            android:name="me.carda.awesome_notifications.core.services.ForegroundService"
            android:foregroundServiceType="dataSync"/>
    </application>
</manifest>

Separate several types with |: dataSync|location. The permission of each type is in the model reference.

Google Play asks you to declare the types your app uses, and why, when you publish it.


πŸƒ Running a foreground service #

import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:awesome_notifications_foreground_service/awesome_notifications_foreground_service.dart';

await AndroidForegroundService.startAndroidForegroundService(
  foregroundStartMode: ForegroundStartMode.stick,
  foregroundServiceType: ForegroundServiceType.dataSync,
  content: NotificationContent(
    id: 42,
    channelKey: 'services',
    title: 'Downloading',
    body: '10%',
    category: NotificationCategory.Service,
    notificationLayout: NotificationLayout.ProgressBar,
    progress: 10,
    autoDismissible: false,
  ),
  actionButtons: [
    NotificationActionButton(
      key: 'STOP',
      label: 'Stop',
      actionType: ActionType.SilentAction,
    ),
  ],
);

The call completes when the notification is shown, and fails with a PlatformException when the service can't start (see Troubleshooting).

Start it while the user is using your app: Android 12+ refuses most starts from the background.

The example/ app is a runnable, single-file demo: a simulated download with its progress.

Updating it #

Call startAndroidForegroundService again with the same id: the notification is replaced in place and the service keeps running.

Stopping it #

await AndroidForegroundService.stopForeground(42);

The notification leaves with the service. Stopping an id that isn't running does nothing.

Run one service at a time: they share the same Android service, so starting another id replaces the notification shown, and stopping either one stops the service.

Buttons and events #

The notification emits the same events as any other: onNotificationCreatedMethod, onNotificationDisplayedMethod and onActionReceivedMethod.

An action that dismisses the notification stops its service, as the Stop button above. To keep it running, use autoDismissible: false or ActionType.KeepOnTop. A reply typed in the notification keeps it running too.

dismiss and cancel don't stop the service: use stopForeground.

Start mode #

What Android does with the service after ending your app to free memory:

ForegroundStartMode Android
stick (default) Recreates the service, but with no notification to show: it stops
stickCompatibility As stick, without the guarantee of being recreated
notStick Doesn't recreate the service
redeliverIntent Recreates the service and shows its notification again

With redeliverIntent the notification comes back, but your Dart code only runs again when your app does.

Time limits #

  • Android 14+: a shortService stops after about 3 minutes.
  • Android 15+: a dataSync or a mediaProcessing stops after 6 hours in a day.

The service stops itself at the limit.


πŸ” How it works #

  • The notification is built before the service starts, through the core and the other add-ons, so an invalid request never starts it and images don't delay it.
  • The service lives in your app's process: while it runs, Android keeps the process, and your Dart code keeps running in background.
  • It ends when the user removes the app from the recents (android:stopWithTask="true").
  • A schedule is ignored: a foreground service starts now.

πŸ— Model reference #

AndroidForegroundService #

Method What it does
startAndroidForegroundService Starts the service, or updates its notification (same id)
stopForeground(id) Stops the service of that notification
startForeground Deprecated: takes the Android values of AndroidForegroundServiceConstants

startAndroidForegroundService #

Field Type Default Notes
content NotificationContent β€” Needs a title or a body, and an existing channel
actionButtons List<NotificationActionButton>? null
foregroundStartMode ForegroundStartMode stick
foregroundServiceType ForegroundServiceType none Android 10+; must be in your manifest

ForegroundServiceType #

Type Permission (Android 14+) Available from
none β€” always: no type is given to Android
manifest the ones of the types declared Android 10: every type of your manifest
camera FOREGROUND_SERVICE_CAMERA Android 10
connectedDevice FOREGROUND_SERVICE_CONNECTED_DEVICE Android 10
dataSync FOREGROUND_SERVICE_DATA_SYNC Android 10
location FOREGROUND_SERVICE_LOCATION Android 10
mediaPlayback FOREGROUND_SERVICE_MEDIA_PLAYBACK Android 10
mediaProjection FOREGROUND_SERVICE_MEDIA_PROJECTION Android 10
microphone FOREGROUND_SERVICE_MICROPHONE Android 10
phoneCall FOREGROUND_SERVICE_PHONE_CALL Android 10
health FOREGROUND_SERVICE_HEALTH Android 14
remoteMessaging FOREGROUND_SERVICE_REMOTE_MESSAGING Android 14
shortService β€” Android 14
specialUse FOREGROUND_SERVICE_SPECIAL_USE Android 14
systemExempted FOREGROUND_SERVICE_SYSTEM_EXEMPTED Android 14, system apps
mediaProcessing FOREGROUND_SERVICE_MEDIA_PROCESSING Android 15

A type newer than the device's Android is treated as none. Some types also need the permission of what they use (location, camera, microphone…): see the Android documentation.


πŸ” Migrating from 0.12.1 #

AndroidForegroundService is the same: add this package and change the import.

// 0.12.1
import 'package:awesome_notifications/android_foreground_service.dart';
// 1.0.0
import 'package:awesome_notifications_foreground_service/awesome_notifications_foreground_service.dart';

The <service> in your manifest keeps its name. What was fixed:

  • await startAndroidForegroundService(…) never completed;
  • ForegroundStartMode.redeliverIntent always failed;
  • an invalid request closed the app (an unknown channel, no title nor body, a notification hidden by displayOnForeground, a type missing in the manifest): now it is answered as an error;
  • the app crashed when Android recreated the service.

🩺 Troubleshooting #

The details of the PlatformException tell what is wrong:

details Why
arguments.invalid.notificationContent.<channelKey> The channel doesn't exist
arguments.invalid.foreground.intent No title nor body
arguments.invalid.foreground.display displayOnForeground / displayOnBackground hides the notification
arguments.invalid.foreground.serviceType The type isn't in your AndroidManifest.xml
unexpectedError Android refused it; message tells why
  • unexpectedError: a permission of the type is missing or wasn't granted, or the service was started from the background (Android 12+).
  • The service runs but no notification appears. Ask for the notification permission (Android 13+).
  • The notification is a circle or a square. Use a small icon with transparency.
  • The app is closed by Android when starting from the background. Declare the type and its permission: without the permission, Android can't be answered in time.
0
likes
150
points
--
downloads
screenshot

Documentation

API reference

Publisher

unverified uploader

Android foreground services for awesome_notifications: keep the app's work running, shown to the user as an awesome notification, with one call to start, update and stop it.

License

Apache-2.0 (license)

Dependencies

awesome_notifications, flutter

More

Packages that depend on awesome_notifications_foreground_service

Packages that implement awesome_notifications_foreground_service