A flutter plugin for execute dart code in background.

Overview

flutter_background_service

A flutter plugin for execute dart code in background.

Android

  • No additional setting required.
  • To change notification icon, just add drawable icon with name ic_bg_service_small.

iOS

  • Register plugins (optional)
import UIKit
import Flutter
import flutter_background_service // add this

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    /// add this
    static func registerPlugins(with registry: FlutterPluginRegistry) {
        GeneratedPluginRegistrant.register(with: registry)
    }
    
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {

        AppDelegate.registerPlugins(with: self)
        SwiftFlutterBackgroundServicePlugin.setPluginRegistrantCallback { registry in
            AppDelegate.registerPlugins(with: registry)
        }
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}
  • Playing audio continously

Info.plist

...
	<key>UIBackgroundModeskey>
	<array>
		<string>audiostring>
        ...
	array>
...

Then use audioplayer plugin to play audio.

...
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  FlutterBackgroundService.initialize(onStart);

  runApp(MyApp());
}

void onStart() {
  WidgetsFlutterBinding.ensureInitialized();

  final audioPlayer = AudioPlayer();

  String url =
      "https://www.mediacollege.com/downloads/sound-effects/nature/forest/rainforest-ambient.mp3";

  audioPlayer.onPlayerStateChanged.listen((event) {
    if (event == AudioPlayerState.COMPLETED) {
      audioPlayer.play(url); // repeat
    }
  });

  audioPlayer.play(url);
}
..

Usage

  • Follow the example.

Warning

The code will executed in isolated process, you can't share reference between UI and Service. Use sendData and onDataReceived to communicate between service and UI.

Comments
  • iOS package inside onStart() function throws

    iOS package inside onStart() function throws "missing plugin implementation" exception

    Hi everybody. Inside the onStart() function I'm using methods and functio from an external package. On Android everything work fine, on iOS these methods from that package throw the "missing plugin implementation" exception. But if I don't use background_service and i run these methods normally in an app widget, they work. It's like inside the onStart() function iOS doesn't find that package. Someone has got the same problem? How can I fix it?

    opened by bobosette 24
  • MissingPluginException when using external plugins (SharedPreferences, PathProvider, etc)

    MissingPluginException when using external plugins (SharedPreferences, PathProvider, etc)

    When we use external plugin in background service, MissingPluginException will be thrown. This happens because the plugin we are using is not registered in the background service isolate (flutter engine) yet. To avoiding it, we have workaround below:

    For Flutter prior to version 3.0.0, we have to call this code depending what plugins you use.

    void onStart(ServiceInstance service){
      ...
      if (Platform.isIOS) YourPluginIOS.registerWith();
      if (Platform.isAndroid) YourPluginAndroid.registerWith();
      ...
    }
    

    For Flutter version 3.0.0 and later, there is generated class to register all of plugins. So we can call like this

    void onStart(ServiceInstance service){
      ...
      DartPluginRegistrant.ensureInitialized();
      ...
    }
    
    opened by ekasetiawans 22
  • Infinite Background Task to play audio after Push Notification

    Infinite Background Task to play audio after Push Notification

    Hello, I am looking for a plugin that is able to play an audio, after a push notification, with iOS.

    I already found the way to play audio, I am using flutter_sound, that works great and I found the solution to play once the notification has arrived; I am using this solution:

    https://stackoverflow.com/questions/54646498/keep-music-app-alive-in-background-ios-and-android

    Unfortunately after 30 seconds the background process has killed and I am looking for something able to awake it.

    Can this plugin helps me with this?

    Thanks a lot, Davide.

    opened by molekola-io 18
  • Devices don't lock when service is running

    Devices don't lock when service is running

    Thanks for your awesome plugin!

    I've implemented a foreground service on Android, but in my testing I have noticed that devices won't lock automatically or even dim their screens when the service is running. It appears that this is caused by this library acquiring a full wake lock:

    https://github.com/ekasetiawans/flutter_background_service/blob/master/packages/flutter_background_service_android/android/src/main/java/id/flutter/flutter_background_service/BackgroundService.java#L53-L62

    According to the docs, a full wake lock "Ensures that the screen and keyboard backlight are on at full brightness".

    It looks like this was introduced in https://github.com/ekasetiawans/flutter_background_service/pull/92 - is it possible to override this behavior?

    opened by insertjokehere 16
  • shared_preferences/flutter_secure_storage work incorrectly

    shared_preferences/flutter_secure_storage work incorrectly

    Appeared after the update. When i run "onStart" and write data to storage. I am trying to get this data for display in application, but it does not match the data that exists in "onStart". When I restart the application, the data that was saved in "onStart" appears in the application. But the new ones are not displayed again until the next restart. flutter 3.0.5

    opened by SavchenkoAndriy 14
  • Unhandled Exception: MissingPluginException

    Unhandled Exception: MissingPluginException

    2020-10-14 12:45:59.499 13214-13271/in.canews.zeronet E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: MissingPluginException(No implementation found for method setForegroundMode on channel id.flutter/background_service_bg)
        #0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:157:7)
        <asynchronous suspension>
        #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:332:12)
        #2      FlutterBackgroundService.setForegroundMode (package:flutter_background_service/flutter_background_service.dart:87:26)
        #3      runBgIsolate (package:zeronet/others/zeronet_utils.dart:154:11)
        #4      ZeroNetStatusExt.onAction (package:zeronet/models/enums.dart:55:45)
        #5      ZeroNetStatusExt.onAction.<anonymous closure> (package:zeronet/models/enums.dart:52:8)
        #6      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:993:19)
        #7      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1111:38)
        #8      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:183:24)
        #9      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:598:11)
        #10     BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:287:5)
        #11     BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:259:7)
        #12     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:157:27)
        #13     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:362:20)
        #14     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:338:22)
        #15     RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:267:11)
        #16     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:295:7)
        #17     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:240:7)
        #18     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:213:7)
        #19     _rootRunUnary (dart:async/zone.dart:1206:13)
        #20     _CustomZone.runUnary (dart:async/zone.dart:1100:19)
        #21     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
        #22     _invoke1 (dart:ui/hooks.dart:265:10)
        #23     _dispatchPointerDataPacket (dart:ui/hooks.dart:174:5)
    

    same error for sendData method.

    opened by canewsin 13
  • Service does not start automatically after reboot

    Service does not start automatically after reboot

    The default package not working in my end tried API levels 26, 28, and 29. Working when run from the studio but when rebooting not working. Working with android as for now but will do IOS later, any suggestions?

    opened by delacernamarimar 13
  • AndroidRuntime: FATAL EXCEPTION: main

    AndroidRuntime: FATAL EXCEPTION: main

    Error Occurs Randomly while removing app from recents page.

    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: in.canews.zeronet, PID: 15410
        java.lang.RuntimeException: Unable to start service id.flutter.flutter_background_service.BackgroundService@cac545c with null: java.lang.IllegalStateException: ensureInitializationComplete must be called after startInitialization
            at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4166)
            at android.app.ActivityThread.access$1900(ActivityThread.java:224)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1919)
            at android.os.Handler.dispatchMessage(Handler.java:107)
            at android.os.Looper.loop(Looper.java:224)
            at android.app.ActivityThread.main(ActivityThread.java:7560)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
         Caused by: java.lang.IllegalStateException: ensureInitializationComplete must be called after startInitialization
            at io.flutter.embedding.engine.loader.FlutterLoader.ensureInitializationComplete(FlutterLoader.java:174)
            at id.flutter.flutter_background_service.BackgroundService.runService(BackgroundService.java:139)
            at id.flutter.flutter_background_service.BackgroundService.onStartCommand(BackgroundService.java:126)
            at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4145)
            at android.app.ActivityThread.access$1900(ActivityThread.java:224) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1919) 
            at android.os.Handler.dispatchMessage(Handler.java:107) 
            at android.os.Looper.loop(Looper.java:224) 
            at android.app.ActivityThread.main(ActivityThread.java:7560) 
            at java.lang.reflect.Method.invoke(Native Method) 
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 
    
    opened by canewsin 12
  • Background Service Preparing Android 10+

    Background Service Preparing Android 10+

    Hi everyone, I am making test of the package, all is fine but I found something that doesn work like it supposed to be, when I reboot my phone I get the notification but this notification only says Background Service Preparing, I do not know why this is happening and see that other people are having the same error. Any solution?

    Thanks

    opened by lasd14 11
  • Background other libraries

    Background other libraries

    I want to check the latest sms by timer. I can do this manually or through a listener. Tried different libraries, with any error. As far as I understand, there is no such possibility?

    Small sample:

    void onStart() async {
      WidgetsFlutterBinding.ensureInitialized();
      final service = FlutterBackgroundService();
    
    Timer.periodic(Duration(seconds: 5), (timer) async {
        SmsReceiver receiver = new SmsReceiver();
        receiver.onSmsReceived.listen((msg) => print(msg.body));
      });
    

    Error:

    Error handling 'checkPlatformOverride' custom request: method not available: ext.flutter.platformOverride
    Error handling 'checkBrightnessOverride' custom request: method not available: ext.flutter.brightnessOverride
    Error handling 'checkPlatformOverride' custom request: method not available: ext.flutter.platformOverride
    Error handling 'checkBrightnessOverride' custom request: method not available: ext.flutter.brightnessOverride
    2
    Error handling 'checkIsWidgetCreationTracked' custom request: method not available: ext.flutter.inspector.isWidgetCreationTracked
    
    E/EventChannel#plugins.babariviere.com/recvSMS(10573): Failed to open event stream
    E/EventChannel#plugins.babariviere.com/recvSMS(10573): java.lang.NullPointerException: Attempt to invoke virtual method 'int android.app.Activity.checkSelfPermission(java.lang.String)' on a null object reference
    
    opened by VisualMafia 11
  • After build apk

    After build apk

    Hi, Thank u for ur work. Everything is working well, but after build apk service in background doesnt work untill i restart phone. Before restart phone background service stay in preparing mode. After restart phone everything work well. Note: After build apk and restart phone only once all functions work well. I will be very

    opened by MohamadKattan 10
  • Provide onStopped callback for when the service is stop.

    Provide onStopped callback for when the service is stop.

    This will allow for cleaning up of resources when the service is stopped.

    For example my background opens streams to firestore in the onStart method, and there is no way for me to call close on those streams when the service is killed.

    opened by Turburlar 1
  • Get the global context while background service is running

    Get the global context while background service is running

    I'm trying to display an alert dialog inside background service when data is received through a WebSocket (when app is running in the foreground). I know background service ran in isolated process and i can't share reference.

    How to get the global context and pass this context to below method?

    showDialog( context: ?, barrierDismissible: false, builder: (BuildContext context) { return alert; }, );

    opened by bahman2000 7
  • Exception on startup on Android referring to missing permission.

    Exception on startup on Android referring to missing permission.

    Upon application startup, I am getting the following exception...

    Caller com.example.flutter_client needs to hold android.permission.SCHEDULE_EXACT_ALARM to set exact alarms.

    If this permission is required, it should be detailed in the 'usage' docs.

    opened by Turburlar 1
Releases(v0.1.12)
Owner
Eka Setiawan Saputra
no flutter, no life
Eka Setiawan Saputra
For test background service try to run ios

workmanager_example Demonstrates how to use the workmanager plugin. Getting Started This project is a starting point for a Flutter application. A few

Taylan YILDIZ 2 Sep 20, 2021
VS Code `.code-workspace` file generator

VS Code .code-workspace file generator (for monorepositories with Dart and Flutter projects) TL;DR; Create yaml file config.yaml (check #Format sectio

Mike T 1 Feb 18, 2022
A Dart build script that downloads the Protobuf compiler and Dart plugin to streamline .proto to .dart compilation.

A Dart build script that downloads the Protobuf compiler and Dart plugin to streamline .proto to .dart compilation.

Julien Scholz 10 Oct 26, 2022
🚀The Flutter dart code generator from zeplin. ex) Container, Text, Color, TextStyle, ... - Save your time.

Flutter Gen Zeplin Extension ?? The Flutter dart code generator from zeplin. ex) Container, Text, Color, TextStyle, ... - Save your time. ⬇ 1.1k Getti

NAVER 49 Oct 12, 2022
A Dart package to web scraping data from websites easily and faster using less code lines.

Chaleno A flutter package to webscraping data from websites This package contains a set of high-level functions that make it easy to webscrap websites

António Nicolau 30 Dec 29, 2022
Basic Dart reverse shell code

dart_rs Basic Dart reverse shell based on this one by Potato-Industries. Pretty self explanatory. You’ll need Windows. I used a Windows 7 64-bit VM. F

null 21 Oct 2, 2022
Provides API to generate Dart source code

DartWriter DartWriter provides API to generate Dart source code. It can make your job easier while developing flutter/dart tools. You can also generat

Ahmet ÇELİK 11 Oct 24, 2022
Dart Code Generator for generating mapper classes

Smartstruct - Dart bean mappings - the easy nullsafe way! Code generator for generating type-safe mappers in dart, inspired by https://mapstruct.org/

Nils 28 Nov 29, 2022
A Dart testing utility for asserting that some code emits a compilation error.

A Dart testing utility for asserting that some code emits a compilation error.

Remi Rousselet 32 Dec 11, 2022
AsyncCallQueue is a Dart class which provides a queuing mechanism to prevent concurrent access to asynchronous code.

async_call_queue AsyncCallQueue is a Dart class which provides a queuing mechanism to prevent concurrent access to asynchronous code. Getting Started

Ron Booth 2 Jan 18, 2022
The Dart code generator for your package versions. 🎯

The Dart code generator for your package versions. There is no way to get the package version from the code in the Dart ecosystem. Installation Add bu

Daichi Furiya 12 Dec 14, 2022
null 2 Apr 17, 2022
Reflectable is a Dart library that allows programmers to eliminate certain usages of dynamic reflection by specialization of reflective code to an equivalent implementation using only static techniques

Reflectable is a Dart library that allows programmers to eliminate certain usages of dynamic reflection by specialization of reflective code to an equivalent implementation using only static techniques. The use of dynamic reflection is constrained in order to ensure that the specialized code can be generated and will have a reasonable size.

Google 318 Dec 31, 2022
A dart package for decode and encode emv QR code

A dart package for decode and encode emv QR code

Laoitdev Open 4 Nov 15, 2022
Starter project and code generator for Flutter/Redux

Flutter Redux Starter/Code Generator Videos Short video ~ 1 minute Long video ~ 10 minutes We're using this approach to develop the Flutter app for In

Hillel Coren 278 Dec 12, 2022
The Flutter code generator for your assets, fonts, colors, … — Get rid of all String-based APIs.

The Flutter code generator for your assets, fonts, colors, … — Get rid of all String-based APIs. Inspired by SwiftGen. Motivation Using asset path str

FlutterGen 1.1k Jan 6, 2023
Examples of Flutter Code Generation.

Flutter Code Generation Examples Code generation packages/tools used in the app: flutter_localization/intl build_runner flutter_gen/flutter_gen_runner

Mangirdas Kazlauskas 19 Oct 11, 2022
Official Git of flutter code-push made by Chimera inc. If you want to get more info or seek for biz corporation, you can contact [email protected].

中文版 Chimera Flutter Code Push Chimera is a Dart compiler developed by ourselves, which generates interpretable and executable bytecode to implement co

Waytoon 21 Oct 6, 2022
Swagger/OpenAPI code generator based on Chopper and JsonAnnotation for Flutter

Code partially generated with chopper ?? Build dart types from Swagger/OpenAPI schemas SwaggerDartCodeGenerator is a code generator that looks for *.s

null 187 Jan 5, 2023