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.

example/lib/main.dart

// awesome_notifications_foreground_service example: a simulated download kept
// alive by an Android foreground service, with its progress in the notification.
import 'dart:async';

import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:awesome_notifications_foreground_service/awesome_notifications_foreground_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

const String channelKey = 'services';
const int serviceId = 42;
const Color mainColor = Color(0xFF9D50DD);

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await NotificationController.initializeLocalNotifications();
  runApp(const MyApp());
}

///  *********************************************
///     NOTIFICATION CONTROLLER
///  *********************************************
///
class NotificationController {
  static final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
  static final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey =
      GlobalKey<ScaffoldMessengerState>();

  /// The events received, the newest first.
  static final ValueNotifier<List<String>> events = ValueNotifier(const []);

  static Future<void> initializeLocalNotifications() async {
    await AwesomeNotifications().initialize(
      // The status bar icon: a white glyph on transparent.
      'resource://drawable/res_notification_icon',
      [
        NotificationChannel(
          channelKey: channelKey,
          channelName: 'Services',
          channelDescription: 'What the app does in background',
          defaultColor: mainColor,
          // Updated often: no sound, no heads-up.
          importance: NotificationImportance.Low,
        ),
      ],
      debug: true,
    );
    await AwesomeNotifications().setListeners(
      onActionReceivedMethod: onActionReceivedMethod,
      onNotificationCreatedMethod: onNotificationCreatedMethod,
      onNotificationDisplayedMethod: onNotificationDisplayedMethod,
      onDismissActionReceivedMethod: onDismissActionReceivedMethod,
    );
  }

  ///  *********************************************
  ///     EVENTS
  ///  *********************************************
  @pragma('vm:entry-point')
  static Future<void> onNotificationCreatedMethod(ReceivedNotification received) async =>
      _event('Created #${received.id}');

  @pragma('vm:entry-point')
  static Future<void> onNotificationDisplayedMethod(ReceivedNotification received) async =>
      _event('Displayed #${received.id}');

  @pragma('vm:entry-point')
  static Future<void> onActionReceivedMethod(ReceivedAction action) async {
    _event('Action #${action.id} ${action.buttonKeyPressed}');
    // The button dismisses the notification, which stops its service.
    if (action.buttonKeyPressed == 'STOP') Download.cancel();
  }

  @pragma('vm:entry-point')
  static Future<void> onDismissActionReceivedMethod(ReceivedAction action) async =>
      _event('Dismissed #${action.id}');

  static void _event(String text) => events.value = [text, ...events.value.take(19)];

  static void showMessage(String message, {Color color = mainColor}) {
    scaffoldMessengerKey.currentState
      ?..hideCurrentSnackBar()
      ..showSnackBar(SnackBar(content: Text(message), backgroundColor: color));
  }

  ///  *********************************************
  ///     REQUESTING PERMISSIONS
  ///  *********************************************
  /// Android 13+: without it the service runs, but its notification is hidden.
  static Future<bool> ensureAllowed() async {
    if (await AwesomeNotifications().isNotificationAllowed()) return true;
    return AwesomeNotifications().requestPermissionToSendNotifications();
  }

  ///  *********************************************
  ///     FOREGROUND SERVICE
  ///  *********************************************
  /// Starts the service or, with the same id, updates its notification.
  static Future<bool> startService({
    required String title,
    required String body,
    double? progress,
    ForegroundStartMode startMode = ForegroundStartMode.stick,
    String channel = channelKey,
  }) async {
    try {
      await AndroidForegroundService.startAndroidForegroundService(
        foregroundStartMode: startMode,
        foregroundServiceType: ForegroundServiceType.dataSync,
        content: NotificationContent(
          id: serviceId,
          channelKey: channel,
          title: title,
          body: body,
          category: NotificationCategory.Service,
          notificationLayout:
              progress == null ? NotificationLayout.Default : NotificationLayout.ProgressBar,
          progress: progress,
          locked: true,
          autoDismissible: false,
        ),
        actionButtons: [
          NotificationActionButton(
            key: 'STOP',
            label: 'Stop',
            actionType: ActionType.SilentAction,
            isDangerousOption: true,
          ),
        ],
      );
      return true;
    } on PlatformException catch (e) {
      showMessage('${e.code}\n${e.message}', color: Colors.red);
      return false;
    }
  }

  static Future<void> stopService() => AndroidForegroundService.stopForeground(serviceId);
}

///  *********************************************
///     SIMULATED DOWNLOAD
///  *********************************************
///
class Download {
  static final ValueNotifier<double?> progress = ValueNotifier(null);
  static Timer? _timer;

  static Future<void> start() async {
    if (!await NotificationController.ensureAllowed()) return;
    cancel();
    if (!await _show(0)) return;
    progress.value = 0;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) async {
      final next = (progress.value ?? 0) + 4;
      if (next >= 100) {
        cancel();
        await NotificationController.stopService();
        await AwesomeNotifications().createNotification(
          content: NotificationContent(
            id: serviceId + 1,
            channelKey: channelKey,
            title: 'Download finished',
            body: 'The service stopped by itself',
          ),
        );
        return;
      }
      progress.value = next;
      await _show(next);
    });
  }

  static Future<bool> _show(double value) => NotificationController.startService(
        title: 'Downloading',
        body: '${value.round()}%',
        progress: value,
      );

  static void cancel() {
    _timer?.cancel();
    _timer = null;
    progress.value = null;
  }
}

///  *********************************************
///     APP
///  *********************************************
///
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Awesome Service',
      navigatorKey: NotificationController.navigatorKey,
      scaffoldMessengerKey: NotificationController.scaffoldMessengerKey,
      theme: ThemeData(colorSchemeSeed: mainColor),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: mainColor,
        foregroundColor: Colors.white,
        title: const Text('Foreground service'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(24),
        children: [
          const _Section('Download'),
          ValueListenableBuilder<double?>(
            valueListenable: Download.progress,
            builder: (_, value, _) => Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                LinearProgressIndicator(value: (value ?? 0) / 100),
                const SizedBox(height: 4),
                Text(value == null ? 'Stopped' : '${value.round()}%', textAlign: TextAlign.center),
              ],
            ),
          ),
          const _Button('Start the download', Download.start),
          _Button('Stop the download', () async {
            Download.cancel();
            await NotificationController.stopService();
          }),
          const _Section('Service'),
          for (final mode in ForegroundStartMode.values)
            _Button('Start: ${mode.name}', () async {
              if (!await NotificationController.ensureAllowed()) return;
              if (await NotificationController.startService(
                  title: 'Service is running', body: mode.name, startMode: mode)) {
                NotificationController.showMessage('Started: ${mode.name}');
              }
            }),
          const _Button('Stop', NotificationController.stopService),
          const _Section('Refused requests'),
          const Text('Wrong on purpose: the service never starts, and the error reaches the '
              'app instead of closing it.'),
          _Button(
              'Unknown channel',
              () => NotificationController.startService(
                  title: 'Service', body: 'Never shown', channel: 'unknown')),
          _Button('No title nor body',
              () => NotificationController.startService(title: '', body: '')),
          const _Section('Events'),
          ValueListenableBuilder<List<String>>(
            valueListenable: NotificationController.events,
            builder: (_, events, _) => Text(events.isEmpty ? 'None yet' : events.join('\n')),
          ),
        ],
      ),
    );
  }
}

class _Section extends StatelessWidget {
  final String title;

  const _Section(this.title);

  @override
  Widget build(BuildContext context) => Padding(
        padding: const EdgeInsets.only(top: 24, bottom: 8),
        child: Text(title, style: Theme.of(context).textTheme.titleMedium),
      );
}

class _Button extends StatelessWidget {
  final String label;
  final Future<void> Function() onPressed;

  const _Button(this.label, this.onPressed);

  @override
  Widget build(BuildContext context) => Padding(
        padding: const EdgeInsets.only(top: 8),
        child: FilledButton.tonal(onPressed: onPressed, child: Text(label)),
      );
}
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