Giter Site home page Giter Site logo

flutter_foreground_service_plugin's Introduction

flutter_foreground_service_plugin

You Can Do this plugin with..

  • Start Foreground Service (with callback)
  • Stop Foreground Service (with callback)
  • Using infinite interval on your configurations
  • Change Notification title and contents

You Can Not Do this plugin with...

  • Change Notification Level

If you use this plugin.

  1. Add dependency to your pubspec.yaml
dependencies:
    ...

  flutter_foreground_plugin: ^0.4.0
  1. Add permission for ForegroundService to AndroidManifest.xml
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
  1. Add service for ForegroundService to AndroidManifest.xml below </activity>
<service android:name="changjoopark.com.flutter_foreground_plugin.FlutterForegroundService"/>
  1. Add use-sdk under application
    <uses-sdk
        android:minSdkVersion="23"
        tools:overrideLibrary="changjoopark.com.flutter_foreground_plugin" />
  1. Add icon image for notification.

Notification Icon Generator will be helpful.

path: android/app/src/main/res/drawable-*

  1. Write code for foreground service
void main() {
  runApp(MyApp());
  startForegroundService();

  // if you need to stop foreground service,
  // await FlutterForegroundPlugin.stopForegroundService();
}

void startForegroundService() async {
  await FlutterForegroundPlugin.setServiceMethodInterval(seconds: 5);
  await FlutterForegroundPlugin.setServiceMethod(globalForegroundService);
  await FlutterForegroundPlugin.startForegroundService(
    holdWakeLock: false,
    onStarted: () {
      print("Foreground on Started");
    },
    onStopped: () {
      print("Foreground on Stopped");
    },
    title: "Flutter Foreground Service",
    content: "This is Content",
    iconName: "ic_stat_hot_tub",
  );
}

void globalForegroundService() {
  debugPrint("current datetime is ${DateTime.now()}");
}

flutter_foreground_service_plugin's People

Contributors

andzejsw avatar cdfq152313 avatar changjoo-park avatar drobyshevalex avatar fabulousgee avatar yonatann 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

Watchers

 avatar  avatar  avatar

flutter_foreground_service_plugin's Issues

Feature requests

  1. Customize the notification (for example, using Big Text Style notification)
    image

  2. Customize or disable the notification sound (I can't update the notification showing "In N minutes" because every update triggers a sound and would be annoying to the user)

  3. Support for minimized notifications (the last one in both example pictures)

  4. I don't know how it is called, but be able to change this part of the notification:
    image

Change title and text of the notification.

Is it possible to change the title and text of the notification while the service is running? For example, I wanted to display latitude and longitude with each change.

Thanks, Deivis.

java.lang.RuntimeException: Unable to start service changjoopark.com.flutter_foreground_plugin.FlutterForegroundService@34e8f12 with null: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getAction()' on a null object reference

Got this error after running for a while

Detail ==============>

11-20 18:45:22.035 28779-28779/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: xxx, PID: 28779
java.lang.RuntimeException: Unable to start service changjoopark.com.flutter_foreground_plugin.FlutterForegroundService@34e8f12 with null: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getAction()' on a null object reference
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3057)
at android.app.ActivityThread.access$2200(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1467)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5546)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getAction()' on a null object reference
at changjoopark.com.flutter_foreground_plugin.FlutterForegroundService.onStartCommand(FlutterForegroundService.java:26)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3040)
at android.app.ActivityThread.access$2200(ActivityThread.java:165) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1467) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:150) 
at android.app.ActivityThread.main(ActivityThread.java:5546) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684) 

Close notification

I'm not sure this is an issue, maybe I just didnt found the way to do this.

The problem is that when the notification is showed, I cant close it, even later to close the app, the notification still there.
On click it opens the app. Trying to slide it just show the options icon.

Is there some way to close the notification in the moment I click on it?

Thanks in advance

MinSDK 23

uses-sdk:minSdkVersion 16 cannot be smaller than version 23 declared in library [:flutter_foreground_plugin] /Users/changjoopark/StudioProjects/live_and_real/build/flutter_foreground_plugin/intermediates/library_manifest/debug/AndroidManifest.xml as the library might be using APIs not available in 16
Suggestion: use a compatible library with a minSdk of at most 16,
	or increase this project's minSdk version to at least 23,
	or use tools:overrideLibrary="changjoopark.com.flutter_foreground_plugin" to force usage (may lead to runtime failures)

Gradle task assembleDebug failed with exit code 1

Not working when App is killed

The message on console is -:
W/FlutterJNI(13596): Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not send. Channel: com.changjoopark.flutter_foreground_plugin/callback. Response ID: 0

FlutterForegroundService.onStartCommand(FlutterForegroundService.java:36)

java.lang.IllegalArgumentException: com.entersoftware.iperiusremotedesktop: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
E/AndroidRuntime(29072): Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.

Crash when using flutter_record_screen

Hi,
It crash when using flutter_screen_recording plugin:

"
I/flutter ( 2065): Foreground on Started
E/MediaRecorder( 2065): setAudioSource called in an invalid state(4)
I/System.out( 2065): Error onMethodCall startRecordScreen
I/System.out( 2065): null
I/flutter ( 2065): Foreground on Started
I/System.out( 2065): 1280 720
I/System.out( 2065): file --- /storage/emulated/0/DCIM/Title.mp4
D/AndroidRuntime( 2065): Shutting down VM
E/AndroidRuntime( 2065): FATAL EXCEPTION: main
E/AndroidRuntime( 2065): Process: com.example.flutterthe_a_app, PID: 2065
E/AndroidRuntime( 2065): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=333, result=-1, data=Intent { (has extras) }} to activity {com.example.flutterthe_a_app/com.example.flutterthe_a_app.MainActivity}: java.lang.SecurityException: Media projections require a foreground service of type ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
E/AndroidRuntime( 2065): at android.app.ActivityThread.deliverResults(ActivityThread.java:5015)
E/AndroidRuntime( 2065): at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056)
E/AndroidRuntime( 2065): at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
E/AndroidRuntime( 2065): at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
E/AndroidRuntime( 2065): at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
E/AndroidRuntime( 2065): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
E/AndroidRuntime( 2065): at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime( 2065): at android.os.Looper.loop(Looper.java:223)
E/AndroidRuntime( 2065): at android.app.ActivityThread.main(ActivityThread.java:7656)
E/AndroidRuntime( 2065): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime( 2065): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
E/AndroidRuntime( 2065): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
E/AndroidRuntime( 2065): Caused by: java.lang.SecurityException: Media projections require a foreground service of type ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
E/AndroidRuntime( 2065): at android.os.Parcel.createExceptionOrNull(Parcel.java:2373)
E/AndroidRuntime( 2065): at android.os.Parcel.createException(Parcel.java:2357)
E/AndroidRuntime( 2065): at android.os.Parcel.readException(Parcel.java:2340)
E/AndroidRuntime( 2065): at android.os.Parcel.readException(Parcel.java:2282)
E/AndroidRuntime( 2065): at android.media.projection.IMediaProjection$Stub$Proxy.start(IMediaProjection.java:231)
E/AndroidRuntime( 2065): at android.media.projection.MediaProjection.(MediaProjection.java:59)
E/AndroidRuntime( 2065): at android.media.projection.MediaProjectionManager.getMediaProjection(MediaProjectionManager.java:119)
E/AndroidRuntime( 2065): at com.isvisoft.flutter_screen_recording.FlutterScreenRecordingPlugin.onActivityResult(FlutterScreenRecordingPlugin.kt:66)
E/AndroidRuntime( 2065): at io.flutter.embedding.engine.FlutterEnginePluginRegistry$FlutterEngineActivityPluginBinding.onActivityResult(FlutterEnginePluginRegistry.java:691)
E/AndroidRuntime( 2065): at io.flutter.embedding.engine.FlutterEnginePluginRegistry.onActivityResult(FlutterEnginePluginRegistry.java:378)
E/AndroidRuntime( 2065): at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onActivityResult(FlutterActivityAndFragmentDelegate.java:625)
E/AndroidRuntime( 2065): at io.flutter.embedding.android.FlutterActivity.onActivityResult(FlutterActivity.java:583)
E/AndroidRuntime( 2065): at android.app.Activity.dispatchActivityResult(Activity.java:8305)
E/AndroidRuntime( 2065): at android.app.ActivityThread.deliverResults(ActivityThread.java:5008)
E/AndroidRuntime( 2065): ... 11 more
E/AndroidRuntime( 2065): Caused by: android.os.RemoteException: Remote stack trace:
E/AndroidRuntime( 2065): at com.android.server.media.projection.MediaProjectionManagerService$MediaProjection.start(MediaProjectionManagerService.java:479)
E/AndroidRuntime( 2065): at android.media.projection.IMediaProjection$Stub.onTransact(IMediaProjection.java:135)
E/AndroidRuntime( 2065): at android.os.Binder.execTransactInternal(Binder.java:1154)
E/AndroidRuntime( 2065): at android.os.Binder.execTransact(Binder.java:1123)
E/AndroidRuntime( 2065):
I/Process ( 2065): Sending signal. PID: 2065 SIG: 9
Lost connection to device.
"

I did all the things you required, I'm using flutter_screen_recording version 1.1.1
AND have to use your 0.4.0 version due to flutter_screen_recording dependcies.

Thanks in advance :)!

How do I use infinite interval on configurations ?

I would like to lauch the Forground service for an infinite time.
I tried to do it by calling FlutterForegroundPlugin.setServiceMethod(foregroundServiceFunction); without calling FlutterForegroundPlugin.setServiceMethodInterval(), but this doesn't work. I also tried to set 'second' to 0, it doesn't work either.

Could you tell me how to do that ?
Thank you very much.

does not work when app killed by the user

I'm not sure if its the intended behavior or not but the callback does not fire if the user kills the app, the notification is always showing but it does nothing.

i tried with two tasks :

and in both cases, the plugin does not work when the app is killed (even if the foreground notification is still showing in the tray)

"extra: my use case is to run a callback periodically that check if the GPS is enabled, if yes update a document in firebase if not notify the user (this should work even if the user killed the app accidentally)"

Dynamically update notification content?

Is it possible to dynamically update the notification content property of FlutterForegroundPlugin.startForegroundService()?

For example:

var number = 0; 

void globalForegroundService() {
  number++;
}

void startForegroundService() async {
   await FlutterForegroundPlugin.setServiceMethodInterval(seconds:` 1);
   await FlutterForegroundPlugin.setServiceMethod(globalForegroundService);
   await FlutterForegroundPlugin.startForegroundService(
    holdWakeLock: false,
    onStarted: () {
      print("Foreground on Started");
    },
    onStopped: () {
      print("Foreground on Stopped");
    },
    title: "Flutter Foreground Service",
    content: number.toString(),
    iconName: "ic_stat_hot_tub",
  );
}

In the content session I would pass the number variable and the notification would reflect the changes each time the number is increased. So far I haven't had any luck with it.

Stops when back button is pressed

When the back button is pressed the app is closed and the foreground service is stopped. But this is not with the music applications which use the foreground service.

Not working when the app is killed.

W/FlutterJNI( 2357): Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not send. Channel: com.changjoopark.flutter_foreground_plugin/callback. Response ID: 0

FlutterForegroundPlugin.java uses or overrides a deprecated API

Issue

We migrated to flutter 2.0. Now we're getting the following warning, while building our app:

Note: C:\Users\<USER>\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\flutter_foreground_plugin-0.8.0\android\src\main\java\changjoopark\com\flutter_foreground_plugin\FlutterForegroundPlugin.java uses or overrides a deprecated API.

Environment

  • flutter 2.2.0
  • flutter_foreground_plugin: 0.6.0 + 0.8.0

error: FlutterForegroundPlugin() has private access in FlutterForegroundPlugin

When building an app with this dependency in Release mode you get the below error during build time.

C:\Users\User1\IdeaProjects\ecrumbs_flutter\android\app\src\main\java\io\flutter\plugins\GeneratedPl
uginRegistrant.java:26: error: FlutterForegroundPlugin() has private access in FlutterForegroundPlug
in
    flutterEngine.getPlugins().add(new changjoopark.com.flutter_foreground_plugin.FlutterForegroundP
lugin());
                                   ^
1 error

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileReleaseJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more l
og output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 19s
Running Gradle task 'assembleRelease'...
Running Gradle task 'assembleRelease'... Done                      80.6s
Gradle task assembleRelease failed with exit code 1

Flutter doctor output

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.0.3, on Microsoft Windows [Version 10.0.19041.867], locale en-US)
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    X Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/windows#android-setup for more details.
[√] Chrome - develop for the web
[√] Android Studio (version 4.1.0)
[√] IntelliJ IDEA Community Edition (version 2019.2)
[√] IntelliJ IDEA Community Edition (version 2020.2)
[√] VS Code, 64-bit edition (version 1.52.1)
[√] Connected device (3 available)

! Doctor found issues in 1 category.

Example throws an error

C:\flutter\musicplayer\android\app\src\main\java\io\flutter\plugins\GeneratedPluginRegistrant.java:21: error: FlutterForegroundPlugin() has private access in FlutterForegroundPlugin
flutterEngine.getPlugins().add(new changjoopark.com.flutter_foreground_plugin.FlutterForegroundPlugin());
^
1 error

The prefix "tools" for attribute "tools:overrideLibrary" associated with an element type "uses-sdk" is not bound.

Hi there,

I'm getting the following error using flutter_foreground_plugin: ^0.8.0. Any ideas?

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':app:generateDebugBuildConfig'.

Failed to calculate the value of task ':app:generateDebugBuildConfig' property 'buildConfigPackageName'.
Failed to query the value of property 'packageName'.
> org.xml.sax.SAXParseException; systemId: file:/Users/danielmintz/go/SRC/ibikeride/android/app/src/main/AndroidManifest.xml; lineNumber: 103; columnNumber: 78; The prefix "tools" for attribute "tools:overrideLibrary" associated with an element type "uses-sdk" is not bound.

Flutter Doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.0.6, on macOS 11.4 20F71 darwin-x64, locale en-GB)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.1)
[✓] VS Code (version 1.56.2)
[✓] Connected device (2 available)

• No issues found!

Update the version on pub.dev

Please update the plugin on pub.dev as it is on GitHub. minSdk versions aren't match. Also I assume this plugin has no support for iOS, am I correct?

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.