Giter VIP home page Giter VIP logo

flutter_background_service's Introduction

A flutter plugin for execute dart code in background.

Support me to maintain this plugin continously with a cup of coffee.

"Buy Me A Coffee"

Android

  • To change notification icon, just add drawable icon with name ic_bg_service_small.

WARNING:

Please make sure your project already use the version of gradle tools below:

  • in android/build.gradle classpath 'com.android.tools.build:gradle:7.4.2'
  • in android/build.gradle ext.kotlin_version = '1.8.10'
  • in android/gradle/wrapper/gradle-wrapper.properties distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-all.zip

Configuration required for Foreground Services on Android 14+ (SDK 34)

Applications that target SDK 34 and use foreground services need to include some additional configuration to declare the type of foreground service they use:

  • Determine the type or types of foreground service your app requires by consulting the documentation

  • Add the corresponding permission to your android/app/src/main/AndroidManifest.xml file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.example">
  ...
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
  <!--
    Permission to use here depends on the value you picked for foregroundServiceType - see the Android documentation.
    Eg, if you picked 'location', use 'android.permission.FOREGROUND_SERVICE_LOCATION'
  -->
  <!--
    If you need more than 1 type, you must separate each type by a pipe(|) symbol - see the Android documentation.
    Eg, android:foregroundServiceType="location|mediaPlayback"
  -->
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE_..." />
  <application
        android:label="example"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher"
        ...>

        <activity
            android:name=".MainActivity"
            android:exported="true"
            ...>

        <!--Add this-->
        <service
            android:name="id.flutter.flutter_background_service.BackgroundService"
            android:foregroundServiceType="WhatForegroundServiceTypesDoYouWant"
        />
        <!--end-->

        ...
  ...
  </application>
</manifest>
  • Add the corresponding foreground service types to your AndroidConfiguration class:
await service.configure(
    // IOS configuration
    androidConfiguration: AndroidConfiguration(
      ...
      // Add this
      foregroundServiceTypes: [AndroidForegroundType.WhatForegroundServiceTypeDoYouWant]
      // Example:
      // foregroundServiceTypes: [AndroidForegroundType.mediaPlayback]
    ),
  );

WARNING:

  • YOU MUST MAKE SURE ANY REQUIRED PERMISSIONS TO BE GRANTED BEFORE YOU START THE SERVICE
  • THE TYPES YOU PUT IN foregroundServiceTypes, MUST BE DECLARED IN MANIFEST

Using custom notification for Foreground Service

You can make your own custom notification for foreground service. It can give you more power to make notifications more attractive to users, for example adding progressbars, buttons, actions, etc. The example below is using flutter_local_notifications plugin, but you can use any other notification plugin. You can follow how to make it below:

  • Notification Channel
Future<void> main() async {
    WidgetsFlutterBinding.ensureInitialized();
    await initializeService();

    runApp(MyApp());
}

// this will be used as notification channel id
const notificationChannelId = 'my_foreground';

// this will be used for notification id, So you can update your custom notification with this id.
const notificationId = 888;

Future<void> initializeService() async {
  final service = FlutterBackgroundService();

  const AndroidNotificationChannel channel = AndroidNotificationChannel(
    notificationChannelId, // id
    'MY FOREGROUND SERVICE', // title
    description:
        'This channel is used for important notifications.', // description
    importance: Importance.low, // importance must be at low or higher level
  );

  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);

  await service.configure(
    androidConfiguration: AndroidConfiguration(
      // this will be executed when app is in foreground or background in separated isolate
      onStart: onStart,

      // auto start service
      autoStart: true,
      isForegroundMode: true,

      notificationChannelId: notificationChannelId, // this must match with notification channel you created above.
      initialNotificationTitle: 'AWESOME SERVICE',
      initialNotificationContent: 'Initializing',
      foregroundServiceNotificationId: notificationId,
    ),
    ...
  • Update notification info
Future<void> onStart(ServiceInstance service) async {
  // Only available for flutter 3.0.0 and later
  DartPluginRegistrant.ensureInitialized();

  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  // bring to foreground
  Timer.periodic(const Duration(seconds: 1), (timer) async {
    if (service is AndroidServiceInstance) {
      if (await service.isForegroundService()) {
        flutterLocalNotificationsPlugin.show(
          notificationId,
          'COOL SERVICE',
          'Awesome ${DateTime.now()}',
          const NotificationDetails(
            android: AndroidNotificationDetails(
              notificationChannelId,
              'MY FOREGROUND SERVICE',
              icon: 'ic_bg_service_small',
              ongoing: true,
            ),
          ),
        );
      }
    }
  });
}

Using Background Service Even when The Application Is Closed

You can use this feature in order to execute code in background. Very useful to fetch realtime data from a server and push notifications.

Must Know:

  • isForegroundMode: false : The background mode requires running in release mode and requires disabling battery optimization so that the service stays up when the user closes the application.
  • isForegroundMode: true : Displays a silent notification when used according to Android's Policy
  • Simple implementation using Socket.io
import 'dart:async';
import 'dart:ui';
import 'package:socket_io_client/socket_io_client.dart' as io;
import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';

Future<void> main() async {
    WidgetsFlutterBinding.ensureInitialized();
    await initializeService();

    runApp(MyApp());
}

void startBackgroundService() {
  final service = FlutterBackgroundService();
  service.startService();
}

void stopBackgroundService() {
  final service = FlutterBackgroundService();
  service.invoke("stop");
}

Future<void> initializeService() async {
  final service = FlutterBackgroundService();

  await service.configure(
    iosConfiguration: IosConfiguration(
      autoStart: true,
      onForeground: onStart,
      onBackground: onIosBackground,
    ),
    androidConfiguration: AndroidConfiguration(
      autoStart: true,
      onStart: onStart,
      isForegroundMode: false,
      autoStartOnBoot: true,
    ),
  );
}

@pragma('vm:entry-point')
Future<bool> onIosBackground(ServiceInstance service) async {
  WidgetsFlutterBinding.ensureInitialized();
  DartPluginRegistrant.ensureInitialized();

  return true;
}

@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {
  final socket = io.io("your-server-url", <String, dynamic>{
    'transports': ['websocket'],
    'autoConnect': true,
  });
  socket.onConnect((_) {
    print('Connected. Socket ID: ${socket.id}');
    // Implement your socket logic here
    // For example, you can listen for events or send data
  });

  socket.onDisconnect((_) {
    print('Disconnected');
  });
   socket.on("event-name", (data) {
    //do something here like pushing a notification
  });
  service.on("stop").listen((event) {
    service.stopSelf();
    print("background process is now stopped");
  });

  service.on("start").listen((event) {});

  Timer.periodic(const Duration(seconds: 1), (timer) {
    socket.emit("event-name", "your-message");
    print("service is successfully running ${DateTime.now().second}");
  });
}

iOS

  • Enable background_fetch capability in xcode (optional), if you wish ios to execute IosConfiguration.onBackground callback.

  • For iOS 13 and Later (using BGTaskScheduler), insert lines below into your ios/Runner/Info.plist

<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
    <string>dev.flutter.background.refresh</string>
</array>
  • You can also using your own custom identifier In ios/Runner/AppDelegate.swift add line below
import UIKit
import Flutter
import flutter_background_service_ios // add this

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    /// Add this line
    SwiftFlutterBackgroundServicePlugin.taskIdentifier = "your.custom.task.identifier"

    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

Usage

  • Call FlutterBackgroundService.configure() to configure handler that will be executed by the Service.

It's highly recommended to call this method in main() method to ensure the callback handler updated.

  • Call FlutterBackgroundService.start to start the Service if autoStart is not enabled.

  • Since the Service using Isolates, You won't be able to share reference between UI and Service. You can communicate between UI and Service using invoke() and on(String method).

Migration

  • sendData() renamed to invoke(String method)
  • onDataReceived() renamed to on(String method)
  • Now you have to use ServiceInstance object inside onStart method instead of creating a new FlutterBackgroundService object. See the example project.
  • Only use FlutterBackgroundService class in UI Isolate and ServiceInstance in background isolate.

FAQ

Why the service not started automatically?

Some android device manufacturers have a custom android os for example MIUI from Xiaomi. You have to deal with that policy.

Service killed by system and not respawn?

Try to disable battery optimization for your app.

My notification icon not changed, how to solve it?

Make sure you had created notification icons named ic_bg_service_small and placed in res/drawable-mdpi, res/drawable-hdpi, res/drawable-xhdpi, res/drawable-xxhdpi for PNGs file, and res/drawable-anydpi-v24 for XML (Vector) file.

Service not running in Release Mode

Add @pragma('vm:entry-point') to the onStart() method. Example:

@pragma('vm:entry-point')
void onStart(ServiceInstance service){
  ...
}

Service terminated when app is in background (minimized) on iOS

Keep in your mind, iOS doesn't have a long running service feature like Android. So, it's not possible to keep your application running when it's in background because the OS will suspend your application soon. Currently, this plugin provide onBackground method, that will be executed periodically by Background Fetch capability provided by iOS. It cannot be faster than 15 minutes and only alive about 15-30 seconds.

Discord

Click here to join to my discord channels

flutter_background_service's People

Contributors

agent3bood avatar asashour avatar babyninja1 avatar berkekbgz avatar byon8 avatar canewsin avatar codingwithsaeed avatar ekasetiawans avatar gnassro avatar guyluz11 avatar hasanm08 avatar hbedford avatar helmlover avatar henrikkee avatar hiruthicshass avatar insertjokehere avatar j3s avatar luisfelipeas5 avatar mohammedhasna2015 avatar pmatatias avatar prkay avatar raghavsatyadev avatar rfaasilva avatar sarthakydv avatar wackymax avatar widavies avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

flutter_background_service's Issues

onDataReceived is not firing

code -

void onStart() {
  WidgetsFlutterBinding.ensureInitialized();
  final service = FlutterBackgroundService();
  service.onDataReceived.listen((event) {
   print('initiating listener');
    if (event["action"] == "setAsForeground") {
      print('about to go foreground');
      service.setForegroundMode(true);
      return;
    }

    if (event["action"] == "setAsBackground") {
      service.setForegroundMode(false);
    }
  });

  // bring to foreground
  service.setForegroundMode(true);

  Timer.periodic(Duration(seconds: 1), (timer) {
    service.setNotificationInfo(
      title: "My App Service",
      content: "Updated at ${DateTime.now()}",
    );

    service.sendData(
      {"action": 'setAsForeground'},
    );
  });
}

the print statements never get called. Why is that?

Callback error: type 'HeadlessTask' is not a subtype of type 'String' of 'taskId'

Hi,
With the background service I do the things I want in the background periodically once a minute. The application runs successfully for hours on android device. But sometimes it gives this error . The application does not crash completely, but I am still worried, what could be the reason?

I/flutter (22601): [BackgroundFetch _headlessCallbackDispather] ‼️ Callback error: type 'HeadlessTask' is not a subtype of type 'String' of 'taskId' I/flutter (22601): #0 _TypeError._throwNew (dart:core-patch/errors_patch.dart:98:34) I/flutter (22601): #1 _headlessCallbackDispatcher.<anonymous closure> (package:background_fetch/background_fetch.dart:652:15) I/flutter (22601): #2 _headlessCallbackDispatcher.<anonymous closure> (package:background_fetch/background_fetch.dart:638:41) I/flutter (22601): #3 MethodChannel._handleAsMethodCall package:flutter/…/services/platform_channel.dart:435 I/flutter (22601): #4 MethodChannel.setMethodCallHandler.<anonymous closure> package:flutter/…/services/platform_channel.dart:382 I/flutter (22601): #5 _DefaultBinaryMessenger.handlePlatformMessage package:flutter/…/services/binding.dart:284 I/flutter (22601): #6 _invoke3.<anonymous closure> (dart:ui/hooks.dart:223:15) I/flutter (22601): #7 _rootRun (dart:async/zone.dart:1354:13) I/flutter (22601): #8 _CustomZone.run (dart:async/zone.dart:1258:19) I/flutter (22601): #9 _CustomZone.runGuarded (dart:async/zone.dart:1162:7) I/flutter (22601): #10 _invoke3 (dart:ui/hooks.dart:222:10) I/flutter (22601): #11 PlatformDispatcher._dispatchPlatformMessage (dart:ui/platform_dispatcher.dart:520:7) I/flutter (22601): #12 _dispatchPlatformMessag

navigator to method onStart

hi,I want to access the context via the onStart method. To navigate. What do you suggest?
FlutterBackgroundService.initialize(onStart);

E/BackgroundService: callback handle not found

2021-06-05 08:21:46.045 17905-17905/? E/BackgroundService: callback handle not found

Other Log :

2021-06-05 08:30:53.035 1790-2065/? I/ActivityManager: Force stopping in.canews.pythonide appid=10547 user=0: from pid 22792
2021-06-05 08:30:53.041 1790-2065/? I/ActivityManager: Force stopping in.canews.pythonide appid=10547 user=11: from pid 22792
2021-06-05 08:30:53.346 1790-2118/? I/ActivityTaskManager: START u0 {act=android.intent.action.RUN flg=0x30000000 cmp=in.canews.pythonide/.MainActivity (has extras)} from uid 2000
2021-06-05 08:30:53.373 1790-1861/? I/ActivityManager: Start proc 6651:in.canews.pythonide/u0a547 for pre-top-activity {in.canews.pythonide/in.canews.pythonide.MainActivity}
2021-06-05 08:30:53.399 6651-6651/? I/chatty: uid=10547(in.canews.pythonide) identical 2 lines
2021-06-05 08:30:53.420 6651-6651/? I/TetheringManager: registerTetheringEventCallback:in.canews.pythonide
2021-06-05 08:30:53.437 6651-6651/? W/anews.pythonide: type=1400 audit(0.0:142110): avc: denied { read } for name="max_map_count" dev="proc" ino=17290730 scontext=u:r:untrusted_app_29:s0:c35,c258,c512,c768 tcontext=u:object_r:proc_max_map_count:s0 tclass=file permissive=0 app=in.canews.pythonide
2021-06-05 08:30:53.462 1790-2115/? D/UntrustedWifiNetworkFactory: got request NetworkRequest [ TRACK_DEFAULT id=10045, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED Uid: 10547 AdministratorUids: [] RequestorUid: 10547 RequestorPackageName: in.canews.pythonide] ] with score 60 and providerId 6
2021-06-05 08:30:53.462 1790-2170/? D/WIFI_AWARE_FACTORY: got request NetworkRequest [ TRACK_DEFAULT id=10045, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED Uid: 10547 AdministratorUids: [] RequestorUid: 10547 RequestorPackageName: in.canews.pythonide] ] with score 60 and providerId 6
2021-06-05 08:30:53.462 1790-2171/? D/Ethernet: got request NetworkRequest [ TRACK_DEFAULT id=10045, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED Uid: 10547 AdministratorUids: [] RequestorUid: 10547 RequestorPackageName: in.canews.pythonide] ] with score 60 and providerId 6
2021-06-05 08:30:53.463 2811-2811/? D/PhoneSwitcherNetworkRequstListener: got request NetworkRequest [ TRACK_DEFAULT id=10045, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED Uid: 10547 AdministratorUids: [] RequestorUid: 10547 RequestorPackageName: in.canews.pythonide] ] with score 60 and providerId 6
2021-06-05 08:30:53.463 1790-2115/? D/WifiNetworkFactory: got request NetworkRequest [ TRACK_DEFAULT id=10045, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED Uid: 10547 AdministratorUids: [] RequestorUid: 10547 RequestorPackageName: in.canews.pythonide] ] with score 60 and providerId 6
2021-06-05 08:30:53.498 6651-22921/? D/DownloadWorker: DownloadWorker{url=https://cdn.jsdelivr.net/gh/ngosang/trackerslist/trackers_best_ip.txt,filename=null,savedDir=/data/data/in.canews.pythonide/files/trackers,header=,isResume=false
2021-06-05 08:30:53.498 6651-22922/? D/DownloadWorker: DownloadWorker{url=https://cdn.jsdelivr.net/gh/ngosang/trackerslist/trackers_all_ip.txt,filename=null,savedDir=/data/data/in.canews.pythonide/files/trackers,header=,isResume=false
2021-06-05 08:30:53.629 1790-1858/? I/ActivityTaskManager: Displayed in.canews.pythonide/.MainActivity: +275ms
2021-06-05 08:30:53.652 1790-2094/? W/InputDispatcher: channel '73ea9e7 in.canews.pythonide/in.canews.pythonide.MainActivity (server)' ~ Consumer closed input channel or an error occurred.  events=0xd
2021-06-05 08:30:53.652 1790-2094/? E/InputDispatcher: channel '73ea9e7 in.canews.pythonide/in.canews.pythonide.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
2021-06-05 08:30:53.653 1790-4001/? D/ConnectivityService: ConnectivityService NetworkRequestInfo binderDied(NetworkRequest [ TRACK_DEFAULT id=10045, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED Uid: 10547 AdministratorUids: [] RequestorUid: 10547 RequestorPackageName: in.canews.pythonide] ], android.os.BinderProxy@b17dfc4)
2021-06-05 08:30:53.653 1790-3060/? I/WindowManager: WIN DEATH: Window{73ea9e7 u0 in.canews.pythonide/in.canews.pythonide.MainActivity}
2021-06-05 08:30:53.653 1790-2118/? I/ActivityManager: Process in.canews.pythonide (pid 6651) has died: fg  TOP 
2021-06-05 08:30:53.653 1790-3060/? W/InputDispatcher: Attempted to unregister already unregistered input channel '73ea9e7 in.canews.pythonide/in.canews.pythonide.MainActivity (server)'
2021-06-05 08:30:53.657 1790-2118/? W/ActivityManager: Scheduling restart of crashed service in.canews.pythonide/androidx.work.impl.background.systemjob.SystemJobService in 1000ms for connection
2021-06-05 08:30:53.658 1790-2118/? W/ActivityTaskManager: Force removing ActivityRecord{8ee3228 u0 in.canews.pythonide/.MainActivity t3466}: app died, no saved state
2021-06-05 08:30:58.361 1165-22810/? I/iorapd: Perfetto TraceBuffer saved to file: /data/misc/iorapd/in.canews.pythonide/4/in.canews.pythonide.MainActivity/raw_traces/1622862058359173889.perfetto_trace.pb
2021-06-05 08:31:03.743 1790-1861/? I/ActivityManager: Start proc 22993:in.canews.pythonide/u0a547 for service {in.canews.pythonide/androidx.work.impl.background.systemjob.SystemJobService}
2021-06-05 08:31:03.801 22993-22993/? I/chatty: uid=10547(in.canews.pythonide) identical 2 lines
2021-06-05 08:31:03.821 22993-22993/? I/TetheringManager: registerTetheringEventCallback:in.canews.pythonide

timer periodic doesn't work correctly

hello,
I wanna create an app that has a periodic notification, but when I set the timer.periodic in onStart, it doesn't work correctly on lockScreen,
I use the async method and database in the timer.periodic
please help

Can't get recive data to UI

Hi , im stuck in this issue when i try to receive data from native . I do as same as your example but my widget can't listen value from stream . It's have value when i log it

PlatformException on initialize

FlutterBackgroundService.initialize is failing with an error message of: Unhandled Exception: PlatformException(100, Failed read arguments, null, null) at line 62. I'm running version 0.1.5 on android.

I'm working on finding any information to guide me to an answer to what's going on. Right now I'm guessing it has something to do with my android configurations. Any help is appreciated!

SharedPreference

Can't use Shared Preferences inside it. can anyone please help how can i use sharedpref inside it

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?

Run Timer in the background

Hi there just came across this plugin, would it be possible to run a timer in the background? The timer is activated from the app.

Background service on IOS

Hello. I was successfully able to integrate my services on android on your plugin. Now there is a task to repeat this on iOS. It was possible to start the background mode of your plugin while the application is running in the foreground, but when I turn it off, the service turns off. Tell me, have you found some optimal solution for this?
IOS still doesn't allow doing anything in the background and need to use APNS?
Could you suggest some solution for my application, I need to check the status of the site in the background, but at least once a minute?

I see you have dealt with this issue a lot, I think you have also come across this - I will be very grateful if you give the broadest possible answer.

background service not stopping

I can able to successfully start the bg service, but I tried stopping in many ways its not stopping

platform : IOS (emulator)

// init
var service = null;
ActivityMap() {
  WidgetsFlutterBinding.ensureInitialized();
  service = FlutterBackgroundService();
  service.setForegroundMode(false);
}
.
.
.
.
// cancelling in some other function inside the same class
void cancelBg(){
  service.stopBackgroundService();
  service.sendData({"action": "stopService"});
  
  FlutterBackgroundService().stopBackgroundService();
  FlutterBackgroundService().sendData({"action": "stopService"});
}

still the below print giving true

var isRunning = await service.isServiceRunning();
print("status: " + isRunning.toString());

multiple background tasks

I have to use a background task on 3 different pages. this task is running a counter. When I start this task on one page, counters start running on all pages. How can I separate the tasks from each other? Thank you

W/FlutterJNI(31225): Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not send. Channel: plugins.flutter.io/connectivity_status. Response ID: 0

I want to my app check connectivity to process something in background. but when I killed app, it output this message:

W/FlutterJNI(31225): Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not send. Channel: plugins.flutter.io/connectivity_status. Response ID: 0

How to fix this??

Thanks!!!

background service is not working

background service is not working , but foreground service is work perfectly , and service not auto started after boot completed and Nought (7.0)

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

Support Desktop plattforms and Web

Now that Flutter supports the web and desktop platforms, support to them should be added too. Maybe some people have ideas how to reach there?

For the web, using a ServiceWorker?

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.

`question` How to Remove the Notification, That may always occur?

Hey @ekasetiawans I Loved your ❤️ towards the People who opens the issue inside the flutter_background_service
like how you assisted @arpitjacob in this issue #3.

Thanks up for the Love for the Opensource, and understanding how weird is using the Work manager plugin is.
Work manager is just don't work up properly with the Hive Db or local Storages, And with this Package, I think I could Create Limitless Things.. Thanks Up @ekasetiawans for understanding the need of this Developer. 💡

Question
Do we have a way, to remove the disturbing notification that comes to the top, which just doesn't remove by itself.

Cannot change notification icon.

Hello, I am not able to change the notification icon.
Adding a ic_bg_service_small.xml or ic_bg_service_small.png to the drawable folder or even to every drawable folder(hdpi,mdpi...) does not change the icon.

Unhandled Exception: MissingPluginException(No implementation found for method sendData on channel id.flutter/background_service_bg)

I am using particularly for android background service. If I followed same implementation like mention in example its working well. onStart method in main.dart.

I am receiving the error, If I want to use onStart other then in main.dart, either in a separate service or in any other widget class.

  Unhandled Exception: MissingPluginException(No implementation found for method sendData on channel id.flutter/background_service_bg)
 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:7)

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.

Icon change

Hello I can't change icon. I created an Icon named ic_bg_service_small but the icon is the same when the service is running.
How can I fix it?

Stop service once the app is closed

Is it possible to stop this service once the user closes the app?
I am building a timer and I am setting the setForegroundMode to true in order to show the notification.
Once the user has closed the app I need to end all of the background processes.

Is it possible to create a method similar to setForegroundMode that we can call when we initialize the service that will kill the background process once the app is closed?

Error compiling with minimun IOS 10

hi...
i have this issue

Compiling for iOS 9.0, but module 'flutter_background_service' has a minimum deployment target of iOS 10.0: /Users/cesarquattro/Library/Developer/Xcode/DerivedData/Runner-eiedghkkuhmwrmhbelwprmptnqzh/Build/Products/Debug-iphonesimulator/flutter_background_service/flutter_background_service.framework/Modules/flutter_background_service.swiftmodule/x86_64-apple-ios-simulator.swiftmodule

i cant build in 9.0 because google_maps and firebase require minimum IOS 10

what can i do???

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) 

slow running of the service

When service.sendData and service.setNotificationInfo are used at the same time, my time counter runs slowly. how can i fix this? Thank you

FATAL EXCEPTION Context.startForegroundService() did not then call Service.startForeground()

I am getting a random exception from the plugin.
It is hard to reproduce but it happens very often. It happens even if I just leave the app doing nothing or if I hot reload.
Sometimes it happens, sometimes it does not. But it happens even if I don't emit any events, just browse the app.
Also crashes in production.
Here are the logs:

I/dset.testApp_de(17971): Thread[7,tid=17982,WaitingInMainSignalCatcherLoop,Thread*=0x7de9511000,peer=0x13bc02c8,"Signal Catcher"]: reacting to signal 3
I/dset.testApp_de(17971):
I/dset.testApp_de(17971): Wrote stack traces to tombstoned
D/AndroidRuntime(17971): Shutting down VM
E/AndroidRuntime(17971): FATAL EXCEPTION: main
E/AndroidRuntime(17971): Process: com.pump.testApp_dev, PID: 17971
E/AndroidRuntime(17971): android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{e5c4382 u0 com.pump.testApp_dev/id.flutter.flutter_background_service.BackgroundService}
E/AndroidRuntime(17971): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1976)
E/AndroidRuntime(17971): 	at android.os.Handler.dispatchMessage(Handler.java:107)
E/AndroidRuntime(17971): 	at android.os.Looper.loop(Looper.java:224)
E/AndroidRuntime(17971): 	at android.app.ActivityThread.main(ActivityThread.java:7590)
E/AndroidRuntime(17971): 	at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(17971): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
E/AndroidRuntime(17971): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
I/Process (17971): Sending signal. PID: 17971 SIG: 9
Lost connection to device.

I am using the plugin to show a timer sometimes, but by default I need to hide the notification since no timer is running, here is my setup:

void timerListener() async {
  WidgetsFlutterBinding.ensureInitialized();
  final service = FlutterBackgroundService();
  //hide the notification 
  service.setForegroundMode(false);
}

No need to specify other details of the implementation since the bug happens even if I don't use the timer / emit any events.

cannot find symbol import io.flutter.FlutterInjector

flutter debug console output :

flutter/.pub-cache/hosted/pub.dartlang.org/flutter_background_service-0.0.1+16/android/src/main/java/id/flutter/flutter_background_service/BackgroundService.java:25: error: cannot find symbol
import io.flutter.FlutterInjector;
                 ^
  symbol:   class FlutterInjector
  location: package io.flutter

Flutter 1.20.1 • channel stable
Dart 2.9.0

display app in lock screen

hi,
I want to display a page at a specific time when my app is locked in flutter, but I can't,
please help me

isServiceRunning

isServiceRunning returns true even though the service is not running. How can i fix this ? Thank you!

flutter background service and geofences

hey guys, did anyone manage to make this package work with any geofence monitoring package? I'm trying to build an application that sends the user a notification when they get near a specific location (even with the app closed), I tried to do something simple until now with geolocator, but without any success because as soon as the app is minimized it stops the location service, and for what I saw until now, it's not possible to use this with geolocator... I would be very happy if you could share with me some experience with this type of feature, I'm a beginner developer in a rollercoaster of a task lol!
thanks!!

Flutter 2.0.6 compatibility: fixes UnsatisfiedLinkError when running as foreground service with autostart

When applying this plugin (configuration for foreground service with autostart) to a newly generated flutter project with version 2.0.6, and then reboots the device, one gets the following exception:

05-15 12:48:50.424  8879  8879 E AndroidRuntime: FATAL EXCEPTION: main
05-15 12:48:50.424  8879  8879 E AndroidRuntime: Process: yourpackage.flutter_project, PID: 8879
05-15 12:48:50.424  8879  8879 E AndroidRuntime: java.lang.UnsatisfiedLinkError: No implementation found for io.flutter.view.FlutterCallbackInformation io.flutter.embedding.engine.FlutterJNI.nativeLookupCallbackInformation(long) (tried Java_io_flutter_embedding_engine_FlutterJNI_nativeLookupCallbackInformation and Java_io_flutter_embedding_engine_FlutterJNI_nativeLookupCallbackInformation__J)
05-15 12:48:50.424  8879  8879 E AndroidRuntime:        at io.flutter.embedding.engine.FlutterJNI.nativeLookupCallbackInformation(Native Method)
05-15 12:48:50.424  8879  8879 E AndroidRuntime:        at io.flutter.view.FlutterCallbackInformation.lookupCallbackInformation(FlutterCallbackInformation.java:30)
05-15 12:48:50.424  8879  8879 E AndroidRuntime:        at id.flutter.flutter_background_service.BackgroundService.runService(BackgroundService.java:178)
05-15 12:48:50.424  8879  8879 E AndroidRuntime:        at id.flutter.flutter_background_service.BackgroundService.onStartCommand(BackgroundService.java:163)
05-15 12:48:50.424  8879  8879 E AndroidRuntime:        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4320)
05-15 12:48:50.424  8879  8879 E AndroidRuntime:        at android.app.ActivityThread.access$1800(ActivityThread.java:237)
05-15 12:48:50.424  8879  8879 E AndroidRuntime:        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1951)
05-15 12:48:50.424  8879  8879 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:106)
05-15 12:48:50.424  8879  8879 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:223)
05-15 12:48:50.424  8879  8879 E AndroidRuntime:        at android.app.ActivityThread.main(ActivityThread.java:7660)
05-15 12:48:50.424  8879  8879 E AndroidRuntime:        at java.lang.reflect.Method.invoke(Native Method)
05-15 12:48:50.424  8879  8879 E AndroidRuntime:        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
05-15 12:48:50.424  8879  8879 E AndroidRuntime:        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

The exception itself is not tragic, but this is even displayed to the user, on every restart.
The reason seems to be that the backend service is running while the foreground service holding the callback (dart implementation of actual app) is not yet started. This (app start) seems to only happen after the user clicks on the notification.

I have already developed a fix for this, PR will follow soon!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.