foreground_service 1.1.5

  • Readme
  • Changelog
  • Example
  • Installing
  • 90

foreground_service (Flutter v.1.12.x or later) #

Create Android foreground service/notification

Prep (Android side): #

Android foreground services require a notification to be displayed,
and notifications require an icon.

For this plugin to work, the icon needs to be in this specific location:

res/drawable/org_thebus_foregroundserviceplugin_notificationicon

(take a look at the /example app if you're confused)

Use (Flutter/Dart side): #

To start the service, call ForegroundService.startForegroundService([serviceFunction])

serviceFunction will then be executed periodically, but "minimum/best-effort"
i.e. it will try to make the interval between function executions *at least* that long

Doesn't work? #

As long as you're calling ForegroundService.startForegroundService,
"flutter run" should show error messages that indicate what's wrong/missing

i.e. messages beginning with E/ForegroundServicePlugin indicate an error from the plugin

Caution: #

ForegroundService.notification.get* methods may give unexpected values.

Once notifications are sent out, there's no way to retrieve the "current" data.

To work around this, the plugin keeps a version of the notification around.
This version may not have been "sent out" yet, however.

Disclaimer:

Most of the fancy stuff is shamelessly pilfered from the android_alarm_manager plugin

1.1.5 #

Properly re-hook service after app kill+relaunch

1.1.4 #

Actually return the default behavior, as was supposed to happen in 1.1.2

1.1.3 #

Allow ForegroundService plugin functions to be called from within designated service function

1.1.2 #

Return default behavior to continue running service after app is killed Alternate behavior might be desirable, so expose setContinueRunningAfterAppKilled method (only works with Android v2 embedding/Flutter 1.12.x+)

1.1.1 #

Correct releaseWakeLock method name typo

1.1.0+2 #

Remove author from pubspec (deprecated)

1.1.0+1 #

Update example/readme to reflect Flutter 1.12.x changes

1.1.0 #

Add foreground service permission/service to manifest in plugin

1.0.0 #

Implemented FlutterPlugin interface for Flutter 1.12.x

0.3.1 #

Updated Kotlin to v1.3.50, Gradle to v3.5.3

0.3.0 #

Add option to get a wake lock

Either by passing true to second parameter of startForegroundService or by calling new method getWakeLock()

0.2.1 #

Should no longer crash due to @UiThread exception.

0.2.0 #

Add functions to check service started status & stop service

0.1.1+1 #

Slightly updated readme

0.1.1 #

Fix bug (class would try to init Instant regardless of api level)

0.1.0+2 #

Try to fix wording. ("No" got left behind on a separate line, so it look liked it said "iOS support planned" at a glance).

0.1.0+1 #

Typo

0.1.0 #

1st version. Should suffice to take care of the simple case/bare necessities: Change title, Change text, Change icon, Change priority, and most importantly run a dart function within the context of a foreground service.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:foreground_service/foreground_service.dart';

void main() {
  runApp(MyApp());

  maybeStartFGS();
}

//use an async method so we can await
void maybeStartFGS() async {
  if (!(await ForegroundService.foregroundServiceIsStarted())) {
    await ForegroundService.setServiceIntervalSeconds(5);

    //necessity of editMode is dubious (see function comments)
    await ForegroundService.notification.startEditMode();

    await ForegroundService.notification
        .setTitle("Example Title: ${DateTime.now()}");
    await ForegroundService.notification
        .setText("Example Text: ${DateTime.now()}");

    await ForegroundService.notification.finishEditMode();

    await ForegroundService.startForegroundService(foregroundServiceFunction);
    await ForegroundService.getWakeLock();
  }
}

void foregroundServiceFunction() {
  debugPrint("The current time is: ${DateTime.now()}");
  ForegroundService.notification.setText("The time was: ${DateTime.now()}");
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _appMessage = "";

  @override
  void initState() {
    super.initState();
  }

  void _toggleForegroundServiceOnOff() async {
    final fgsIsRunning = await ForegroundService.foregroundServiceIsStarted();
    String appMessage;

    if (fgsIsRunning) {
      await ForegroundService.stopForegroundService();
      appMessage = "Stopped foreground service.";
    } else {
      maybeStartFGS();
      appMessage = "Started foreground service.";
    }

    setState(() {
      _appMessage = appMessage;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
            child: Column(
          children: <Widget>[
            Text('Foreground Service Example',
                style: TextStyle(fontWeight: FontWeight.bold)),
            Padding(padding: EdgeInsets.all(8.0)),
            Text(_appMessage, style: TextStyle(fontStyle: FontStyle.italic))
          ],
          mainAxisAlignment: MainAxisAlignment.center,
        )),
        floatingActionButton: Column(
          children: <Widget>[
            FloatingActionButton(
              child: Text("F"),
              onPressed: _toggleForegroundServiceOnOff,
              tooltip: "Toggle Foreground Service On/Off",
            )
          ],
          mainAxisAlignment: MainAxisAlignment.end,
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  foreground_service: ^1.1.5

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:foreground_service/foreground_service.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
81
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
90
Learn more about scoring.

We analyzed this package on Apr 6, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6
  • Flutter: 1.12.13+hotfix.8

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test