A Flutter plugin which allows you to execute code in the background on Android and iOS.

Overview

Flutter Workmanager

pub package Build status

Flutter WorkManager is a wrapper around Android's WorkManager, iOS' performFetchWithCompletionHandler and iOS BGAppRefreshTask, 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

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"); //Android only (see below)
  runApp(MyApp());
}

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

The workmanager runs on a separate isolate from the main flutter isolate. Ensure to initialize all dependencies inside the Workmanager().executeTask.

Debugging tips

Wrap the code inside your Workmanager().executeTask in a try and catch in order to catch any exceptions thrown.

void callbackDispatcher() {
  Workmanager().executeTask((task, inputData) {

    int? totalExecutions;
    final _sharedPreference = await SharedPreferences.getInstance(); //Initialize dependency

    try { //add code execution
      totalExecutions = _sharedPreference.getInt("totalExecutions");
      _sharedPreference.setInt("totalExecutions", totalExecutions == null ? 1 : totalExecutions+1);
    } catch(err) {
      Logger().e(err.toString()); // Logger flutter package, prints error on the debug console
      throw Exception(err);
    }

    return Future.value(true);
  });
}

Android tasks are identified using their taskName, whereas two default constants are provided for iOS background operations, depending on whether background fetch or BGTaskScheduler is used: Workmanager.iOSBackgroundTask & Workmanager.iOSBackgroundProcessingTask.


Work Result

The Workmanager().executeTask(... block supports 3 possible outcomes:

  1. Future.value(true): The task is successful.
  2. Future.value(false): The task did not complete successfully and needs to be retried. On Android, the retry is done automatically. On iOS (when using BGTaskScheduler), the retry needs to be scheduled manually.
  3. Future.error(...): The task failed.

On Android, the BackoffPolicy will configure how WorkManager is going to retry the task.

Refer to the example app for a successful, retrying and a failed task.

Customisation (iOS - BGTaskScheduler only)

iOS supports One off tasks with a few basic constraints:

Workmanager().registerOneOffTask(
  "1", // Ignored on iOS
  simpleTaskKey, // Ignored on iOS
  initialDelay: Duration(minutes: 30),
  constraints: Constraints(
    // connected or metered mark the task as requiring internet
    networkType: NetworkType.connected,
    // require external power
    requiresCharging: true,
  ),
  inputData: ... // fully supported
);

Tasks registered this way will appear in the callback dispatcher using as Workmanager.iOSBackgroundProcessingTask.

For more information see the BGTaskScheduler documentation.

Customisation (Android)

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 sent 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

Constraints are mapped at best effort to each platform. Android's WorkManager supports most of the specific constraints, whereas iOS tasks are limited.

  • NetworkType Constrains the type of network required for your work to run. For example, Connected. The NetworkType lists various network conditions. .connected & .metered will be mapped to requiresNetworkConnectivity on iOS.
  • RequiresBatteryNotLow (Android only) When set to true, your work will not run if the device is in low battery mode. Enabling the battery saving mode on the android device prevents the job from running
  • RequiresCharging When set to true, your work will only run when the device is charging.
  • RequiresDeviceIdle (Android only) When set to true, this requires the user’s device to be idle before the work will run. This can be useful for running batched operations that might otherwise have a - negative performance impact on other apps running actively on the user’s device.
  • RequiresStorageNotLow (Android only) When set to true, your work will not run if the user’s storage space on the device is too low.
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: {
    'int': 1,
    'bool': true,
    'double': 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();
Comments
  • 🐞[iOS] MissingPluginException in example app

    🐞[iOS] MissingPluginException in example app

    • [x] I have read the README
    • [x] I have done the setup for Android
    • [x] I have done the setup for iOS
    • [x] I have ran the sample app and it does not work there

    Version

    | Technology | Version | | ------------------- | ------------- | | Workmanager version | 0.2.3 | | Xcode version | 11.5 | | Swift version | 5.0 | | iOS deployment target | 13.5.1 (iPhone SE 1st Generation) |

    Describe the error

    When running the example app on a real iOS device through XCode (by pressing the "Run" icon), the app throws an exception when pressing the "Start the Flutter background service" button. Subsequently, background fetch won't work and the dispatch method is never called.

    The exception in XCode's console is:

    2020-07-15 23:46:23.059914+0200 Runner[9411:4096136] [VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: MissingPluginException(No implementation found for method initialize on channel be.tramckrijte.workmanager/foreground_channel_work_manager)
    #0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:154:7)
    <asynchronous suspension>
    #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
    #2      Workmanager.initialize (package:workmanager/src/workmanager.dart:100:30)
    #3      _MyAppState.build.<anonymous closure> (package:workmanager_example/main.dart:87:33)
    #4      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:779:19)
    #5      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:862:36)
    #6      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
    #7      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:504:11)
    #8      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:282:5)
    #9      BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:217:7)
    #10     PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:475:9)
    #11     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
    #12     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:122:9)
    #13     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
    #14     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:120:18)
    #15     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:106:7)
    #16     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
    #17     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
    #18     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
    #19     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
    #20     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
    #21     _rootRunUnary (dart:async/zone.dart:1196:13)
    #22     _CustomZone.runUnary (dart:async/zone.dart:1085:19)
    #23     _CustomZone.runUnaryGuarded (dart:async/zone.dart:987:7)
    #24     _invoke1 (dart:ui/hooks.dart:275:10)
    #25     _dispatchPointerDataPacket (dart:ui/hooks.dart:184:5)
    

    Unfortunately I can not provide any debug information, when starting the app through flutter run, as there seems to be a bug with iOS hiding important exceptions from frameworks like flutter (see https://github.com/flutter/flutter/issues/41133), so the only way to fetch information (at least the one I know about) is through XCode.

    Except from running flutter pub get and flutter build ios (to resolve initial build error in XCode) I didn't changed anything in the example app.

    Though, there is one thing I noticed that's different from the iOS setup guide: After unchecking and re-checking the capability "Background fetch" in XCode, following block is not added to file project.pbxproj (which, as I understood, should be added automatically by XCode):

    SystemCapabilities = {
    	com.apple.BackgroundModes = {
    		enabled = 1;
    	};
    };
    

    Unfortunately, adding it manually does not seem to have any effect.

    Output of flutter doctor -v

    [✓] Flutter (Channel stable, v1.17.5, on Mac OS X 10.15.5 19F101, locale en-GB)
        • Flutter version 1.17.5 at /opt/flutter
        • Framework revision 8af6b2f038 (2 weeks ago), 2020-06-30 12:53:55 -0700
        • Engine revision ee76268252
        • Dart version 2.8.4
    
    [✗] Android toolchain - develop for Android devices
        ✗ Unable to locate Android SDK.
          Install Android Studio from:
          https://developer.android.com/studio/index.html
          On first launch it will assist you in installing the Android SDK
          components.
          (or visit https://flutter.dev/docs/get-started/install/macos#android-setup
          for detailed instructions).
          If the Android SDK has been installed to a custom location, set
          ANDROID_SDK_ROOT to that location.
          You may also want to add it to your PATH environment variable.
    
    
     
    [✓] Xcode - develop for iOS and macOS (Xcode 11.5)
        • Xcode at /Applications/Xcode.app/Contents/Developer
        • Xcode 11.5, Build version 11E608c
        • CocoaPods version 1.9.3
    
    [!] Android Studio (not installed)
        • Android Studio not found; download from
          https://developer.android.com/studio/index.html
          (or visit https://flutter.dev/docs/get-started/install/macos#android-setup
          for detailed instructions).
    
    [✓] VS Code (version 1.47.1)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.12.2
    
     
    [✓] Connected device (1 available)            
        • iPhone xxx xxxxxxxx • a196bfcb78b38a0f88a8xxxxxxxxxxxxxxxxxxx • ios •
          iOS 13.5.1
    
    bug iOS 
    opened by gebsl 52
  •  Unhandled method registerOneOffTask in iOS

    Unhandled method registerOneOffTask in iOS

    it's works fine in my android but for iOS I always get below errors:

    Unhandled Exception: PlatformException(unhandledMethod("registerOneOffTask") error, Unhandled method registerOneOffTask, null)
    #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
    #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:316:33)
    <asynchronous suspension>
    #2      Workmanager.registerOneOffTask (package:workmanager/src/workmanager.dart:123:32)
    <asynchronous suspension>
    #3      main.<anonymous closure>.<anonymous closure> (package:my_app/main.dart:83:19)
    #4      _rootRun (dart:async/zone.dart:1120:38)
    #5      _CustomZone.run (dart:async/zone.dart:1021:19)
    #6      _CustomZone.runGuarded (dart:async/zone.dart:923:7)
    #7      _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:963:23)
    #8      _rootRun (dart:async/zone.dart:1124:13)
    #9      _CustomZone.run (dart:async/zone.dart:1021:19)
    #10     _CustomZone.bindCallback.<anonymous closure> 
    

    in my AppDelegate.swift file

    import workmanager
    
    @UIApplicationMain
    @objc class AppDelegate: FlutterAppDelegate {
    
      override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
      ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)
    
        UNUserNotificationCenter.current().delegate = self
        //UIApplication.shared.setMinimumBackgroundFetchInterval(TimeInterval(60*15))
    
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
      }
    }
    
    extension AppDelegate: UNUserNotificationCenterDelegate {
    
        func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
            completionHandler(.alert) // shows banner even if app is in foreground
        }
    }
    

    any ideas?

    thanks!

    bug iOS RTM 
    opened by winsonet 34
  • Http Network call is not working  (Flutter Android)

    Http Network call is not working (Flutter Android)

    Hi ,

    I am using workmanager for syncing data from server using http plugin in flutter android . but nothing is happening when http is called . below i am attaching my sample for code for reference

    Sample Code :

    import 'dart:io';
    
    import 'package:workmanager/workmanager.dart';
    import 'package:http/http.dart' as http;
    
    const httpSync = "httpSync";
    demoBackgroundSync() {
      Workmanager.initialize(startJobs, isInDebugMode: false);
      Workmanager.registerOneOffTask("3", httpSync,
          initialDelay: Duration(seconds: 5),
          constraints: Constraints(
              networkType: NetworkType.connected,
              requiresBatteryNotLow: true,
              // requiresCharging: true,
              // requiresDeviceIdle: true,
              requiresStorageNotLow: true));
    }
    
    startJobs() {
      Workmanager.executeTask((task, inputData) {
        switch (task) {
          case httpSync:
            httpSyncApis();
            break;
        }
        print(
            "Native called background task: $task"); //simpleTask will be emitted here.
        return Future.value(true);
      });
    }
    Map<String, String> requestHeaders = {
            HttpHeaders.contentTypeHeader: 'application/json',
            HttpHeaders.acceptHeader: 'application/json',
            // "Access-Control-Allow-Origin": "*",
            // "Access-Control-Allow-Methods": "POST,GET,DELETE,PUT,OPTIONS"
            //  'Authorization': '<Your token>'
          };
    void httpSyncApis() async{
    
        print('Api Request  : Started');
    // till here code works but after this step nothing happening 
      var response = await http
              .get(
                'http://dummy.restapiexample.com/api/v1/employees',
                headers: requestHeaders,
              )
              .timeout(const Duration(seconds: 300));
        
        print('Response Code : ${response.statusCode}');
        print('Response Body : ${response.body}');
    }
    
    

    console logs :

    D/HostConnection(24188): HostConnection::get() New Host Connection established 0xbaf2a4a0, tid 24365
    D/HostConnection(24188): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0
    D/EGL_emulation(24188): eglMakeCurrent: 0xd5e1b4a0: ver 3 0 (tinfo 0xe9589cf0)
    I/flutter (24188): Api Request  : Started
    I/flutter (24188): Native called background task: httpSync
    I/WM-WorkerWrapper(24188): Worker result SUCCESS for Work [ id=740eaba7-dc42-4a24-b6a4-906c1218d13c, tags={ be.tramckrijte.workmanager.BackgroundWorker } ]
    
    help wanted android answered 
    opened by VarmaTech 30
  •  NoSuchMethodError: No top-level getter 'callbackDispatcher' declared.

    NoSuchMethodError: No top-level getter 'callbackDispatcher' declared.

    This is how I setup in my project.

    PageA

    IconButton(
         icon: Icon(Icons.done),
         onPressed: () {
          _bloc.submit();
    })
    

    bloc

    static void callbackDispatcher() {
      Workmanager.executeTask((task, inputData) {
        print(
            "Native called background task: "); //simpleTask will be emitted here.
        return Future.value(true);
      });
    }
    
       Future submit() async {
         final title = _title.value;    
         Workmanager.initialize(callbackDispatcher, isInDebugMode: true);
         Workmanager.registerOneOffTask(title, Consts.UPLOAD_IMAGE);     
        }
    

    Everytime I press the iconbutton in pageA, I will get this error:

    call E/flutter ( 6710): [ERROR:flutter/shell/common/shell.cc(199)] Dart Error: Unhandled exception: E/flutter ( 6710): NoSuchMethodError: No top-level getter 'callbackDispatcher' declared. E/flutter ( 6710): Receiver: top-level E/flutter ( 6710): Tried calling: callbackDispatcher E/flutter ( 6710): #0 NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:202:5) E/flutter ( 6710): [ERROR:flutter/runtime/dart_isolate.cc(461)] Could not resolve main entrypoint function. E/flutter ( 6710): [ERROR:flutter/shell/common/engine.cc(212)] Could not run the isolate. E/flutter ( 6710): [ERROR:flutter/shell/common/engine.cc(137)] Engine not prepare and launch isolate. E/flutter ( 6710): [ERROR:flutter/shell/common/shell.cc(437)] Could not launch engine with configuration.

    opened by tony123S 23
  • ❓How to schedule a Periodic Task

    ❓How to schedule a Periodic Task

    I've been trying to use the package, but I couldn't find out where to put the code to perform the desired Task. As I understood from the working example and from the plugin implementation, I would have to write a custom class that extends the Worker and override the doWork function, but when installing the package by pubspec I wasn't able to find out where to put it.

    bug question 
    opened by kterto 21
  • 🐞[Unable to make field private final java.lang.String java.io.File.path accessible: module java.base does not

    🐞[Unable to make field private final java.lang.String java.io.File.path accessible: module java.base does not "opens java.io" to unnamed module @fb04536]

    • [x] I have read the README
    • [x] I have done the setup for Android
    • [x] I have done the setup for iOS
    • [x] I have ran the sample app and it does not work there

    Version

    | Technology | Version | | ------------------- | ------------- | | Workmanager version | 0.5.0-dev.4 | | Xcode version | 12.5 | | Swift version | 5 | | iOS deployment target| 12 |

    Describe the error

    FAILURE: Build failed with an exception.
    
    * What went wrong:
    Execution failed for task ':app:processDebugMainManifest'.
    > Unable to make field private final java.lang.String java.io.File.path accessible: module java.base does not "opens java.io" to unnamed module @fb04536
    
    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
    
    * Get more help at https://help.gradle.org
    
    BUILD FAILED in 27s
    Exception: Gradle task assembleDebug failed with exit code 1
    

    Output of flutter doctor -v

    [✓] Flutter (Channel stable, 2.0.6, on macOS 11.3.1 20E241 darwin-x64, locale en)
        • Flutter version 2.0.6 at /Users/ganaa/flutter
        • Framework revision 1d9032c7e1 (8 weeks ago), 2021-04-29 17:37:58 -0700
        • Engine revision 05e680e202
        • Dart version 2.12.3
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
        • Android SDK at /Users/ganaa/Library/Android/sdk
        • Platform android-30, build-tools 30.0.3
        • Java binary at: /Library/Java/JavaVirtualMachines/jdk-16.0.1.jdk/Contents/Home/bin/java
        • Java version Java(TM) SE Runtime Environment (build 16.0.1+9-24)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS
        • Xcode at /Applications/Xcode.app/Contents/Developer
        • Xcode 12.5, Build version 12E262
        • CocoaPods version 1.10.1
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [!] Android Studio (not installed)
        • Android Studio not found; download from https://developer.android.com/studio/index.html
          (or visit https://flutter.dev/docs/get-started/install/macos#android-setup for detailed instructions).
    
    [✓] VS Code (version 1.57.1)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.23.0
    
    [✓] Connected device (3 available)
        • sdk gphone x86 arm (mobile) • emulator-5554 • android-x86    • Android 11 (API 30) (emulator)
        • macOS (desktop)             • macos         • darwin-x64     • macOS 11.3.1 20E241 darwin-x64
        • Chrome (web)                • chrome        • web-javascript • Google Chrome 91.0.4472.106
    
    bug 
    opened by gangzhaorige 18
  • 🐞[Android, Task was cancelled in periodic run]

    🐞[Android, Task was cancelled in periodic run]

    • [x] I have read the README
    • [x] I have done the setup for Android
    • [ ] I have ran the sample app and it does not work there

    Version

    | Technology | Version | | ------------------- | ------------- | | Workmanager version | 0.2.2 |

    Describe the error

    I run the code on Android (periodic), but it works for the first time only, all further runs failed with an error:

    My code:

    void backgroundTrackerInitialize() {
      Workmanager.cancelAll();
      Workmanager.initialize(callbackDispatcher, isInDebugMode: true);
      Workmanager.registerPeriodicTask(
        "1",
        "refreshLocationAndNetworkStatus",
        frequency: Duration(minutes: 15)
      );
    }
    
    void callbackDispatcher() {
      Workmanager.executeTask((task, parameters) async {
        print('task:getposition');
    
        print('task:finished');
    
        return Future.value(true);
      });
    }
    

    image

    Error output:

    I/WM-WorkerWrapper( 7011): java.util.concurrent.CancellationException: Task was cancelled.
    I/WM-WorkerWrapper( 7011): 	at androidx.work.impl.utils.futures.AbstractFuture.cancellationExceptionWithCause(AbstractFuture.java:1184)
    I/WM-WorkerWrapper( 7011): 	at androidx.work.impl.utils.futures.AbstractFuture.getDoneValue(AbstractFuture.java:514)
    I/WM-WorkerWrapper( 7011): 	at androidx.work.impl.utils.futures.AbstractFuture.get(AbstractFuture.java:475)
    I/WM-WorkerWrapper( 7011): 	at androidx.work.impl.WorkerWrapper$2.run(WorkerWrapper.java:284)
    I/WM-WorkerWrapper( 7011): 	at androidx.work.impl.utils.SerialExecutor$Task.run(SerialExecutor.java:91)
    I/WM-WorkerWrapper( 7011): 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    I/WM-WorkerWrapper( 7011): 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    I/WM-WorkerWrapper( 7011): 	at java.lang.Thread.run(Thread.java:923)
    

    In example project all work fine, but if I copy/paste code from example project to my project I get same error. Any ideas?

    Output of flutter doctor -v

    
    [√] Flutter (Channel stable, v1.17.3, on Microsoft Windows [Version 10.0.18363.900], locale en-US)
        • Flutter version 1.17.3 at C:\ide\flutter
        • Framework revision b041144f83 (7 days ago), 2020-06-04 09:26:11 -0700
        • Engine revision ee76268252
        • Dart version 2.8.4
    
     
    [√] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
        • Android SDK at C:\Users\truer\AppData\Local\Android\Sdk
        • Platform android-29, build-tools 29.0.3
        • ANDROID_HOME = C:\Users\truer\AppData\Local\Android\Sdk
        • Java binary at: C:\ide\androidstudio\jre\bin\java
        • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)
        • All Android licenses accepted.
    
    [√] Android Studio (version 3.6)
        • Android Studio at C:\ide\androidstudio
        • Flutter plugin version 44.0.2
        • Dart plugin version 192.7761
        • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)
    
    [√] Connected device (1 available)
        • sdk gphone x86 arm • emulator-5554 • android-x86 • Android 10 (API 29) (emulator)
    
    bug android 
    opened by trueromanus 18
  • [flutter_workmanager] Give support for Flutter null-safety

    [flutter_workmanager] Give support for Flutter null-safety

    • Updates all versions to null-safety beta support.
    • Converts dart code to give support for null-safety.
    • Changed test-cases to support null-safety.

    Testing instructions:

    Add the following to your pubspec.yaml:

    dependency_overrides:
      workmanager:
        git:
          url: https://github.com/parthdave93/flutter_workmanager.git
          ref: parthdave93/null_safety_migration
    

    Pre-launch Checklist

    The title of the PR starts with the name of the plugin surrounded by square brackets, e.g. [shared_preferences] I read the Contributor Guide and followed the process outlined there for submitting PRs. I read the Tree Hygiene wiki page, which explains my responsibilities. I read and followed the Flutter Style Guide and the C++, Objective-C, Java-style guides. I added new tests to check the change I am making or the feature I am adding, or Hixie said the PR is tested exempt. I updated pubspec.yaml with an appropriate new version according to the pub versioning philosophy. I updated CHANGELOG.md to add a description of the change. I updated/added relevant documentation (doc comments with ///). All existing and new tests are passing.

    opened by parthdave93 17
  • MissingPluginException(No implementation found for method initialize on channel be.tramckrijte.workmanager/foreground_channel_work_manager

    MissingPluginException(No implementation found for method initialize on channel be.tramckrijte.workmanager/foreground_channel_work_manager

    • [x] I have read the README
    • [x] I have done the setup for Android
    • [x] I have done the setup for iOS
    • [x] I have ran the sample app and it does not work there

    Version

    | Technology | Version | | ------------------- | ------------- | | Workmanager version | ^0.2.3 | | Xcode version | 11.6 | | Swift version | | | iOS deployment target| |

    Describe the error [VERBOSE-2:ui_dart_state.cc(177)] Unhandled Exception: MissingPluginException(No implementation found for method initialize on channel be.tramckrijte.workmanager/foreground_channel_work_manager) #0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:157:7) #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:332:12) #2 Workmanager.initialize (package:workmanager/src/workmanager.dart:100:30) #3 _MyAppState.build. (package:workmanager_example/main.dart:87:33)

    Optionally provide the least amount of code that shows this behaviour. Ideally in the sample app. Above error comes from your example project. I launched your project in my iOS simulator. As soon as I clicked button "Start the Flutter background service" I got above error. I'd had the same problem when I tried to add workmanager package my Flutter project after following all instructions. Please let me know how to make this work.

    Output of flutter doctor -v [✓] Flutter (Channel stable, 1.22.0, on Mac OS X 10.15.5 19F101, locale en-CA) • Flutter version 1.22.0 at /Users/borismisic/Developer/SDKs/flutter • Framework revision d408d302e2 (3 weeks ago), 2020-09-29 11:49:17 -0700 • Engine revision 5babba6c4d • Dart version 2.10.0

    [✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2) • Android SDK at /Users/borismisic/Library/Android/sdk • Platform android-30, build-tools 30.0.2 • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593) • All Android licenses accepted.

    [✓] Xcode - develop for iOS and macOS (Xcode 11.6) • Xcode at /Applications/Xcode.app/Contents/Developer • Xcode 11.6, Build version 11E708 • CocoaPods version 1.9.3

    [✓] Android Studio (version 4.0) • Android Studio at /Applications/Android Studio.app/Contents • Flutter plugin version 50.0.1 • Dart plugin version 193.7547 • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)

    [✓] Connected device (4 available) • Android SDK built for x86 (mobile) • emulator-5554 • android-x86 • Android 10 (API 29) (emulator) • iPhone 8 (mobile) • 86CECABE-4A8C-4622-9789-56F866DD0B7D • ios • com.apple.CoreSimulator.SimRuntime.iOS-13-6 (simulator) • iPhone 11 (mobile) • 265C0D76-578B-4365-87E7-B04FFE5B8834 • ios • com.apple.CoreSimulator.SimRuntime.iOS-13-6 (simulator) • iPhone SE (2nd generation) (mobile) • A1B22118-9D9A-4FA2-B6B7-ECA34922CCAF • ios • com.apple.CoreSimulator.SimRuntime.iOS-13-6 (simulator) ! Error: Boris’s iPhone is not connected. Xcode will continue when Boris’s iPhone is connected. (code -13)

    • No issues found!

    bug 
    opened by misici234 17
  • NO Such Module workmanager on IOS side

    NO Such Module workmanager on IOS side

    • [x] I have read the README
    • [x] I have done the setup for Android
    • [x] I have done the setup for iOS

    0.2.0

    please help guyss...

    i have been follow all way on ios side and i have been read for all documentation but still got error

    [✓] Flutter (Channel stable, 1.20.4, on Mac OS X 10.15.6 19G2021, locale en-ID)
        • Flutter version 1.20.4 at /Users/congfandi/development/flutter
        • Framework revision fba99f6cf9 (7 days ago), 2020-09-14 15:32:52 -0700
        • Engine revision d1bc06f032
        • Dart version 2.9.2
    
     
    [✓] Android toolchain - develop for Android devices (Android SDK version 30.0.0)
        • Android SDK at /Users/congfandi/Library/Android/sdk
        • Platform android-30, build-tools 30.0.0
        • Java binary at: /Applications/Android
          Studio.app/Contents/jre/jdk/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build
          1.8.0_242-release-1644-b3-6222593)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 12.0)
        • Xcode at /Applications/Xcode.app/Contents/Developer
        • Xcode 12.0, Build version 12A7209
        • CocoaPods version 1.9.3
    
    [✓] Android Studio (version 4.0)
        • Android Studio at /Applications/Android Studio.app/Contents
        • Flutter plugin version 49.0.2
        • Dart plugin version 193.7547
        • Java version OpenJDK Runtime Environment (build
          1.8.0_242-release-1644-b3-6222593)
    
    [✓] VS Code (version 1.49.1)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.14.1
    
    [✓] Connected device (1 available)
        • sdk gphone x86 (mobile) • emulator-5554 • android-x86 • Android 11 (API
          30) (emulator)
    
    Screen Shot 2020-09-22 at 05 12 31 bug 
    opened by congfandi 17
  • Conflicts with other plugins

    Conflicts with other plugins

    I assume this issue could be relevant not only for flutter_webview_plugin ,but still. I have listeners attached to flutter_webview_plugin. For example onUrlChanged and onStateChanged. All works fine until I call Workmanager.initialize(). No errors. Just listeners stops working.

    bug help wanted question android 
    opened by estevez-dev 17
  • 🐞[Workmanager().cancelAll() is not working, please check]

    🐞[Workmanager().cancelAll() is not working, please check]

    • [x] I have read the README
    • [x] I have done the setup for Android
    • [x] I have done the setup for iOS
    • [x] I have ran the sample app and it does not work there

    Version

    | Technology | Version | | ------------------- | ------------- | | Workmanager version | 0.5.1 | | Xcode version | 14.2 | | Swift version | 5.7 | | iOS deployment target| - 10.0 |

    Describe the error Describe error Error occur for the version only on the workmanager().cancelAll() is not working, it not stop during stopping it.

    Output of flutter doctor -v

    bug 
    opened by engineer-ece 0
  • 🐞iOS: registerOneOffTask never registers with callbackDispatcher

    🐞iOS: registerOneOffTask never registers with callbackDispatcher

    • [x] I have read the README
    • [x] I have done the setup for Android
    • [x] I have done the setup for iOS
    • [x] I have ran the sample app and it does not work there

    Version

    | Technology | Version | | ------------------- | ------------- | | Workmanager version | 0.5.0 | | Xcode version | 14.1 | | Swift version | 5.7.1 | | iOS deployment target| 11.0 |

    Describe the error

    Have followed all the directions in the iOS setup and guides but am unable to get the plugin to work correctly. No errors are thrown - the callback dispatcher is just never called. The code works without fault on Android. The test environment is a physical device (iPhone XS running iOS 16.1.2) and is being debugged from XCode. The Info.plist has been configured with the correct task indentifier and backgroundFetch seems to work as expected and triggers the callbackDispatcher, but registering a one off task doesn't.

    callbackDispatcher as top level function:

    void callbackDispatcher() {
      Workmanager().executeTask((taskName, inputData) {
        stderr.writeln(
            'Flutter VM, BACKGROUND TASK: Background task called! $taskName, extra data: $inputData');
    
        return Future.value(true);
      });
    }
    

    my AppDelegate.swift:

    @UIApplicationMain
    @objc class AppDelegate: FlutterAppDelegate {
    
      override func userNotificationCenter(_ center: UNUserNotificationCenter,
                                             willPresent notification: UNNotification,
                                             withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
             completionHandler(.alert) // shows banner even if app is in foreground
         }
        
      
    
      override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
      ) -> Bool {
          // This is required to make any communication available in the action isolate.
            UNUserNotificationCenter.current().delegate = self
            FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { (registry) in
              GeneratedPluginRegistrant.register(with: registry)
            }
            //WorkmanagerPlugin.register(with: self!.registrar(forPlugin: "com.v2software.onchocks.onchocks-background-logging"))
            WorkmanagerPlugin.registerTask(withIdentifier: "com.v2software.onchocks.onchocks-background-logging")
          
            UIApplication.shared.setMinimumBackgroundFetchInterval(TimeInterval(60*15))
            GeneratedPluginRegistrant.register(with: self)
            if #available(iOS 10.0, *) {
                UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
            }
          
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
      }
    }
    

    I'm calling registerOneOffTask from a Popupmenuitem:

    PopupMenuItem(
                                  child: const Text('Record flight'),
                                  onTap: () async {
                                    print('Registering new task');
                                    try {
                                      await Workmanager().registerOneOffTask(
                                          'com.v2software.onchocks.onchocks-background-logging',
                                          'com.v2software.onchocks.onchocks-background-logging',
                                          tag: 'ThisIsANewTag',
              
                                          inputData: {
                                            'user': user?.user.uid,
                                            'registeredEvent': true,
                                          },
                                          initialDelay: Duration.zero,
                                          existingWorkPolicy:
                                              ExistingWorkPolicy.replace);
                                    } catch (err) {
                                      print(err.toString());
                                    }
                                  },
                                ),
    

    When calling the onTap function this is the debug output:

    2022-12-12 21:03:51.281401+1030 Runner[3948:242838] flutter: Registering new task
    2022-12-12 21:04:17.589698+1030 Runner[3948:254976] [tcp] tcp_input [C2.1.1:3] flags=[R] seq=4218016391, ack=0, win=0 state=LAST_ACK rcv_nxt=4218016391, snd_una=1941703970
    2022-12-12 21:04:17.592510+1030 Runner[3948:254976] [tcp] tcp_input [C2.1.1:3] flags=[R] seq=4218016391, ack=0, win=0 state=CLOSED rcv_nxt=4218016391, snd_una=1941703970
    2022-12-12 21:04:17.593167+1030 Runner[3948:254976] [tcp] tcp_input [C2.1.1:3] flags=[R] seq=4218016391, ack=0, win=0 state=CLOSED rcv_nxt=4218016391, snd_una=1941703970
    

    I noticed that the callback will fire at a very random time (not associated with any input or background fetch) and the task will be in the queue but missing the input data.

    I was expecting behaviour similar to what I am seeing in Android where the callback function is triggered nearly immediately upon registering the task. Am I missunderstanding the functionality of this package or have I missused it?

    **[✓] Flutter (Channel stable, 3.0.3, on macOS 13.0.1 22A400 darwin-x64, locale en-AU) • Flutter version 3.0.3 at /Users/ChrisBrislin/Developer/flutter • Upstream repository https://github.com/flutter/flutter.git • Framework revision 676cefaaff (6 months ago), 2022-06-22 11:34:49 -0700 • Engine revision ffe7b86a1e • Dart version 2.17.5 • DevTools version 2.12.2

    [✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0) • Android SDK at /Users/ChrisBrislin/Library/Android/sdk • Platform android-33, build-tools 33.0.0 • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7281165) • All Android licenses accepted.

    [✓] Xcode - develop for iOS and macOS (Xcode 14.1) • Xcode at /Applications/Xcode.app/Contents/Developer • CocoaPods version 1.11.3

    [✓] Chrome - develop for the web • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

    [✓] Android Studio (version 2020.3) • Android Studio at /Applications/Android Studio.app/Contents • Flutter plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/6351-dart • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7281165)

    [✓] IntelliJ IDEA Community Edition (version 2021.3.2) • IntelliJ at /Applications/IntelliJ IDEA CE.app • Flutter plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/6351-dart

    [✓] VS Code (version 1.74.0) • VS Code at /Applications/Visual Studio Code.app/Contents • Flutter extension version 3.54.0

    [✓] Connected device (4 available) • Chris iphone (mobile) • 00008020-001870340E92002E • ios • iOS 16.1.2 20B110 • iPhone 14 (mobile) • 91A06788-785D-40B3-AEA8-77AED473ECCF • ios • com.apple.CoreSimulator.SimRuntime.iOS-16-1 (simulator) • macOS (desktop) • macos • darwin-x64 • macOS 13.0.1 22A400 darwin-x64 • Chrome (web) • chrome • web-javascript • Google Chrome 108.0.5359.98

    [✓] HTTP Host Availability • All required HTTP hosts are available

    • No issues found!**

    bug 
    opened by ChristopherBrislin 2
  • Interact with app when running in foreground?

    Interact with app when running in foreground?

    Hello,

    as per title, is there any way to exchange data between the worker isolate and the app main thread when the latter is running in the foreground?

    opened by iazel 2
  • Android Studio run won't find callback when cable unpluged

    Android Studio run won't find callback when cable unpluged

    While using Android Studio, if you run the application when clicking the Run button (green arrow on top) it will compile, install and run the application and everything works, but as soon as you unplug the cable (or sever the connection with Android Studio) all scheduled functions will just not run. Although if you kill the application and run it from the smartphone normally, everything works as planned.

    Also using flutter run, or install the application via adb (debug or release) and then run it from the smartphone works as expected.

    opened by RicardoGSGraca 1
  • Improvement on iOS

    Improvement on iOS

    Hi

    I added BGAppRefresh on iOS as periodic task - this will have normally more calls than a refresh-task.

    • time for a AppRefresh is limited to 29sec Also I updated readme and and example Added backgroundrefresh-permission-check and open iOS device-settings if not permitted on iOS (init work manager)
    opened by xunreal75 6
Releases(0.5.0)
Owner
Flutter Community
A central place for all community made Flutter packages. To get started, see the README of the 'community' repository.
Flutter Community
Schedule & run Dart code in the background on both Android & iOS

flt_worker The flt_worker plugin allows you to schedule and execute Dart-written background tasks in a dedicated isolate, by utilizing the WorkManager

Yingxin Wu 26 Nov 27, 2022
A Flutter plugin to get location updates in the background for both Android and iOS

Background Location A Flutter plugin to get location updates in the background for both Android and iOS (Requires iOS 10.0+). Uses CoreLocation for iO

Ali Almoullim 181 Jan 4, 2023
A flutter plugin about qr code or bar code scan , it can scan from file、url、memory and camera qr code or bar code .Welcome to feedback your issue.

r_scan A flutter plugin about qr code or bar code scan , it can scan from file、url、memory and camera qr code or bar code .Welcome to feedback your iss

PengHui Li 112 Nov 11, 2022
Makes it possible to safely execute and retry a Future inside a StatelessWidget

futuristic Makes it possible to safely execute and retry a Future inside a StatelessWidget. See the Mainstream package for a similar API for working w

Martin Rybak 28 Sep 15, 2022
Flutter plugin that allows you to keep the device screen awake on Android, iOS, macOS, Windows, and web.

Wakelock Wakelock is Flutter plugin that allows you to keep the device screen awake, i.e. prevent the screen from sleeping. Supported platforms Platfo

null 341 Jan 4, 2023
Automatically generate profile picture with random first name and background color. But you can still provide pictures if you have them. As the default color, based on the name of the first letter. :fire: :fire: :fire:

FLUTTER PROFILE PICTURE Automatically generate profile picture with random first name and background color. But you can still provide pictures if you

Aditya Dharmawan Saputra 10 Dec 20, 2022
dos downloader app is developed for downloading video. You can download video from YouTube and Facebook. You can also play video on background

dosdownloader Dos downloader app is developed for downloading video. You can download video from YouTube and Facebook. You can also play video on back

Md Abir Ahsan Tahmim 1 Dec 8, 2021
Write iOS&Android Code using Dart. This package liberates you from redundant glue code and low performance of Flutter Channel.

Dart_Native Dart_Native operates as both a code generator tool and a bridge to communicate between Dart and native APIs. Replaces the low-performing F

DartNative 893 Jan 4, 2023
A flutter plugin that brings an in-background android app to the foreground

bg_launcher A flutter plugin that brings an in-background android app to the foreground (Android only) Restrictions on starting activities from the ba

Iheb Briki 5 Nov 25, 2022
A Video Player For Vimeo Videos in Flutter. This plugin allows us to play video from Vimeo and it supports Android and iOS platforms.

vimeo_video_player A Video Player For Vimeo Videos in Flutter. This plugin allow us to play video from vimeo and it's supports Android and iOS platfor

MindInventory 26 Dec 8, 2022
This is the code for the POAPin app, which is written in Flutter and currently supports iOS, Android, and Web platforms.

POAPin This is the code for the POAPin app, which is written in Flutter and currently supports iOS, Android, and Web platforms. ?? Get the app Platfor

Glory Lab 17 Nov 7, 2022
This project was writed with pure dart code,which means it's support both iOS and Android.

This project was writed with pure dart code,which means it's support both iOS and Android. Screenshot Todo show/hide animation Usage You can find the

吴述军 Brant 377 Dec 24, 2022
Background upload plugin for flutter

Flutter Uploader A plugin for creating and managing upload tasks. Supports iOS and Android. This plugin is based on WorkManager in Android and NSURLSe

Flutter Community 178 Jan 3, 2023
A Flutter plugin for updating location in background.

background_locator A Flutter plugin for getting location updates even when the app is killed. Refer to wiki page for install and setup instruction or

REKAB 270 Dec 29, 2022
A Flutter sensor plugin which provide easy access to the Pitch and Roll on Android and iOS devices.

Flutter Aeyrium Sensor Plugin Aeyrium Sensor Plugin A Flutter sensor plugin which provide easy access to the Pitch and Roll on Android and iOS devices

Aeyrium 58 Nov 3, 2022
WooCommerce App template that uses Flutter. Integrated to work with WooCommerce stores, connect and create an IOS and Android app from Flutter for IOS and Android

WooCommerce App: Label StoreMax Label StoreMax - v5.3.1 Official WooSignal WooCommerce App About Label StoreMax Label StoreMax is an App Template for

WooSignal 314 Jan 9, 2023
A Flutter package which allows you to work with MethodChannels in Isolate.

A Flutter package which allows you to work with MethodChannels in Isolate. Also it provides simplified multiplatform Isolate API.

Zemlaynikin Max 19 Jan 4, 2023
A user-friendly money management app which allows you to keep track of transactions seamlessly

See the first version of 'Mvelopes' - Money Management Application which I completed as my first project and published on Play Store. 'Mvelopes' is a user-friendly money management app which allows you to keep track of transactions seamlessly. - Features - Technology • Reminder • Flutter • Notification • Hive • Manage income & expenses

Mushthak 16 Dec 8, 2022
A ListView that allows you to group list items and support headers like iOS UITableView section.

GroupListView package for Flutter. A ListView that allows you to group list items and support headers like iOS UITableView section. Features List Item

Daniel Ioannou 73 Nov 21, 2022