workmanager 0.1.2

  • Readme
  • Changelog
  • Example
  • Installing
  • 95

Flutter Workmanager #

pub package

Flutter WorkManager is a wrapper around Android's WorkManager and iOS' performFetchWithCompletionHandler, effectively enabling headless execution of Dart code in the background.

This is especially useful to run periodic tasks, such as fetching remote data on a regular basis.

This plugin was featured in this Medium blogpost

Installation #

dependencies:
  workmanager: ^0.1.2
flutter pub get
import 'package:workmanager/workmanager.dart';

Platform Setup #

In order for background work to be scheduled correctly you should follow the Android and iOS setup first.

How to use the package? #

See sample folder for a complete working example.
Before registering any task, the WorkManager plugin must be initialized.

void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) {
    print("Native called background task: $backgroundTask"); //simpleTask will be emitted here.
    return Future.value(true);
  });
}

void main() {
  Workmanager.initialize(
    callbackDispatcher, // The top level function, aka callbackDispatcher
    isInDebugMode: true // If enabled it will post a notification whenever the task is running. Handy for debugging tasks
  );
  Workmanager.registerOneOffTask("1", "simpleTask");
  runApp(MyApp());
}

The callbackDispatcher needs to be either a static function or a top level function to be accessible as a Flutter entry point.


Customisation (Android only!) #

Not every Android WorkManager feature is ported.

Two kinds of background tasks can be registered :

  • One off task : runs only once
  • Periodic tasks : runs indefinitely on a regular basis
// One off task registration
Workmanager.registerOneOffTask(
    "1", 
    "simpleTask"
);

// Periodic task registration
Workmanager.registerPeriodicTask(
    "2", 
    "simplePeriodicTask", \
    // When no frequency is provided the default 15 minutes is set.
    // Minimum frequency is 15 min. Android will automatically change your frequency to 15 min if you have configured a lower frequency.
    frequency: Duration(hours: 1),
)

Each task must have an unique name;
This allows cancellation of a started task.
The second parameter is the String that will be send to your callbackDispatcher function, indicating the task's type.

Tagging #

You can set the optional tag property.
Handy for cancellation by tag.
This is different from the unique name in that you can group multiple tasks under one tag.

Workmanager.registerOneOffTask("1", "simpleTask", tag: "tag");

Existing Work Policy #

Indicates the desired behaviour when the same task is scheduled more than once.
The default is KEEP

Workmanager.registerOneOffTask("1", "simpleTask", existingWorkPolicy: ExistingWorkPolicy.append);

Initial Delay #

Indicates how along a task should waitbefore its first run.

Workmanager.registerOneOffTask("1", "simpleTask", initialDelay: Duration(seconds: 10));

Constraints #

Not all constraints are mapped.

Workmanager.registerOneOffTask(
    "1", 
    "simpleTask", 
    constraints: Constraints(
        networkType: NetworkType.connected,
        requiresBatteryNotLow: true,
        requiresCharging: true,
        requiresDeviceIdle: true,
        requiresStorageNotLow: true
    )
);

InputData #

Add some input data for your task. Valid value types are: int, bool, double, String and their list

 Workmanager.registerOneOffTask(
    "1",
    "simpleTask", 
    inputData: <String, dynamic>{
    'int': 1,
    'bool': true,
    'dobule': 1.0,
    'string': 'string',
    'array': [1, 2, 3],
    },
);

BackoffPolicy #

Indicates the waiting strategy upon task failure.
The default is BackoffPolicy.exponential.
You can also specify the delay.

Workmanager.registerOneOffTask("1", "simpleTask", backoffPolicy: BackoffPolicy.exponential, backoffPolicyDelay: Duration(seconds: 10));

Cancellation #

A task can be cancelled in different ways :

By Tag #

Cancels the task that was previously registered using this Tag, if any.

Workmanager.cancelByTag("tag");

By Unique Name #

Workmanager.cancelByUniqueName("<MyTask>");

All #

Workmanager.cancelAll();

0.1.2 #

  • Android:
    • Added support for inputData

0.1.1 #

  • iOS:
    • Added support for Flutter 1.9.1

0.1.0 #

  • First API stable release
  • Android:
    • Improved debug notification with result message first
    • Updated Installation README
  • iOS:
    • 🐞 Improved debug notification delivery when the app is in the background.
    • Updated Installation README

0.0.15 #

  • iOS: 🐞 Make sure all the implementers plugins are available in the background isolate by registering them first.
    This requires the user to provide us with the generated registry in the AppDelegate
  • iOS: 📝 specified minimum deployment target of iOS 10 (with Swift 4.2)

0.0.14 #

  • iOS performBackgroundFetch now actually works.

0.0.13 #

  • [‼️ BREAKING change] You will need to clear the preferences or re-install the App if you had registered jobs already on Android.
  • Android:
    • Thanks to @vanlooverenkoen
      • 🐞 cancelling all task would have failed before this version
      • 📝 Update documentation to be a bit more clear about the minimum frequency a periodic can be scheduled
    • Better debug notification support:
      • Emoji's to quickly see if a task ran successful
      • Elapsed time
      • Collapsing notifications
    • General Internal API renames to improve readability
  • iOS
    • ⬆️ Separate UserDefaults for the plugin
    • 🐞 Memory leak resources cleanup
    • 🐞 Result mapping Dart -> Swift was wrong
    • Better debug notification support:
      • Emoji's to quickly see if a task ran successful
      • Elapsed time
      • Collapsing notifications

0.0.12 #

  • 🐞 expose setPluginRegistrantCallback to the old rusty Java people

0.0.11 #

  • Better README and docs
    • Everything now refers to the top level callback as the callbackDispatcher
    • Some typo's
    • Link to Medium blog post
  • Adds unit tests to the project since the many issues with enum parsing
    • Fixes an issue with the parsing of the NetworkType
  • Project restructure to a src folder

0.0.10 #

  • I should test a little better before publishing to pub.dev.
    • Fixes all enum parsing issues with ExistingWorkPolicy and BackoffPolicy

0.0.9 #

  • A bugfix were parsing the BackOffPolicy was still wrong.

0.0.8 #

  • A bugfix were parsing of the ExistingWorkPolicy and BackoffPolicy went rogue. Addresses #9

0.0.7 #

  • This version is the first version to support iOS with the help of the Background Fetch API.
    • Only recurring tasks can be scheduled by iOS.
    • If you want to respond to iOS background triggers you should add the extra case Workmanager.iOSBackgroundTask to your switch case.
  • [‼️ BREAKING change]
    • Workmanager.defaultCallbackDispatcher becomes Workmanager.executeTask
  • This version was used as referenced in the Medium blogpost

0.0.6+2 #

  • Fixes a bug in which you could not use other plugins inside a EchoCallbackFunction.
    • Fixes #6

    • Fixes #4

    • [‼️ BREAKING change] A user should extend a custom Application and register it in its AndroidManifest.xml

      class App : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
          override fun onCreate() {
              super.onCreate()
              WorkmanagerPlugin.setPluginRegistrantCallback(this)
          }
      
          override fun registerWith(reg: PluginRegistry?) {
              GeneratedPluginRegistrant.registerWith(reg)
          }
      }
      
      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="be.tramckrijte.workmanager_example">
      
          <!-- io.flutter.app.FlutterApplication is an android.app.Application that
               calls FlutterMain.startInitialization(this); in its onCreate method.
               In most cases you can leave this as-is, but you if you want to provide
               additional functionality it is fine to subclass or reimplement
               FlutterApplication and put your custom class here. -->
          <application
              android:name=".App" <!-- Replace io.flutter.app.FlutterApplication with .App -->
              android:icon="@mipmap/ic_launcher"
              android:label="workmanager_example"
              tools:replace="android:name">
              <activity
                  android:name=".MainActivity"
                  android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
                  android:hardwareAccelerated="true"
                  android:launchMode="singleTop"
                  android:theme="@style/LaunchTheme"
                  android:windowSoftInputMode="adjustResize">
                  <!-- This keeps the window background of the activity showing
                       until Flutter renders its first frame. It can be removed if
                       there is no splash screen (such as the default splash screen
                       defined in @style/LaunchTheme). -->
                  <meta-data
                      android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
                      android:value="true" />
                  <intent-filter>
                      <action android:name="android.intent.action.MAIN" />
                      <category android:name="android.intent.category.LAUNCHER" />
                  </intent-filter>
              </activity>
          </application>
      </manifest>
      

0.0.6+1 #

  • This version is the first version to support iOS with the help of the Background Fetch API.
    • Only recurring tasks can be scheduled by iOS.
    • If you want to respond to iOS background triggers you should add the extra case Workmanager.iOSBackgroundTask to your switch case.
  • [‼️ BREAKING change]
    • Workmanager.defaultCallbackDispatcher becomes Workmanager.executeTask

0.0.6 #

  • Expose a WorkManagerHelper to the native.
    • This makes it easier if you also have some native code that wants to schedule the Echo Worker

0.0.5 #

  • The description was too big so you lose points for that too...

0.0.4 #

  • Provide a better description so package scores higher on Pub

0.0.3 #

  • Add Dart documentation

0.0.2 #

  • Remove the need to register a custom Application on Android side. (Everything still works in testing)

0.0.1 #

  • Initial Release:
    • Schedule One off task
    • Schedule Periodic task
      • Fixed delay
    • Initial delay
    • Constraints
      • Support for 1 network type
      • requires battery not low
      • requires charging
      • requires device idle
      • requires storage not low
    • back off policy

example/README.md

workmanager_example #

Demonstrates how to use the workmanager plugin.

Getting Started #

This project is a starting point for a Flutter application.

A few resources to get you started if this is your first Flutter project:

For help getting started with Flutter, view our online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference.

Use this package as a library

1. Depend on it

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


dependencies:
  workmanager: ^0.1.2

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:workmanager/workmanager.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
89
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]
95
Learn more about scoring.

We analyzed this package on Oct 11, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.5.1
  • pana: 0.12.21
  • Flutter: 1.9.1+hotfix.4

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Dependencies

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