Giter Club home page Giter Club logo

flutter_background_fetch's People

Contributors

abdelaziz-mahdy avatar bierbaumtim avatar christocracy avatar dballance avatar donny88 avatar emirchus avatar ethael avatar ginoterlouw avatar ilyosbekkk avatar kuhnroyal avatar transistorsoft-pkg avatar trueb2 avatar yunowo 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flutter_background_fetch's Issues

[BUG] Building release apk fails - Plugin 'com.android.library' not found.

Your Environment

  • Plugin version: 0.3.2
  • Platform: Android
  • OS version: MacOS Catalina
  • Flutter info (flutter info, flutter doctor):
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel dev, v1.10.14, on Mac OS X 10.15 19A602, locale en-US)

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[✓] Xcode - develop for iOS and macOS (Xcode 11.1)
[✓] Android Studio (version 3.5)
[✓] VS Code (version 1.39.2)
[✓] Connected device (2 available)

• No issues found!
  • Plugin config

To Reproduce
Steps to reproduce the behavior:

  1. Run flutter build apk --release

Debug logs

FAILURE: Build failed with an exception.

* Where:
Build file '/Users/m/Github/flutter/.pub-cache/hosted/pub.dartlang.org/background_fetch-0.3.2/android/build.gradle' line: 3

* What went wrong:
A problem occurred evaluating root project 'background_fetch'.
> Plugin with id 'com.android.library' not found.

* 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 0s


The plugin background_fetch could not be built due to the issue above.

Additional context
After updating to background_fetch 0.3.2, I am encountering this error when building a release apk or app bundle. If I switch back to an older release, such as 0.1.2, this error goes away and I can successfully build.
If I run the app in debug mode on an emulator or physical device using 0.3.2, it runs successfully. If I build an apk using --debug instead of --release, it builds successfully.

registerHeadlessTask doesn't work with me

Your Environment

Plugin version: 0.2.0
Platform: iOS or Android
OS version: 9
Device manufacturer / model: Xiaomi note 6
Flutter info (flutter info, flutter doctor):
Plugin config

To Reproduce
Steps to reproduce the behavior:

close the application
I receive nothing

Debug logs
[ I have an issue I can't debug but I run the app and wait 15 min to receive the result]

Additional context
Add any other context about the problem here.

Here is my Andriod Application.java

package com.mowakeb.hepsitezim;

import com.transistorsoft.flutter.backgroundfetch.BackgroundFetchPlugin;
import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class Application  extends FlutterApplication implements PluginRegistry.PluginRegistrantCallback {
    @Override
    public void onCreate() {
        super.onCreate();
        BackgroundFetchPlugin.setPluginRegistrant(this);
    }

    @Override
    public void registerWith(PluginRegistry registry) {
        GeneratedPluginRegistrant.registerWith(registry);
    }
}

my main
``

void main() async {


  // Enable integration testing with the Flutter Driver extension.
  // See https://flutter.io/testing/ for more info.
  runApp(new LoginPage());




  // Register to receive BackgroundFetch events after app is terminated.
  // Requires {stopOnTerminate: false, enableHeadless: true}
  BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
}

and finally the function

/// This "Headless Task" is run when app is terminated.
void backgroundFetchHeadlessTask() async {
  print('[BackgroundFetch] Headless event received.');

  SharedPreferences prefs = await SharedPreferences.getInstance();

  // Read fetch_events from SharedPreferences
  List<String> events = [];
  String json = prefs.getString(EVENTS_KEY);
  if (json != null) {
    events = jsonDecode(json).cast<String>();
  }
  // Add new event.
  events.insert(0, new DateTime.now().toString() + ' [Headless]');
  // Persist fetch events in SharedPreferences
  prefs.setString(EVENTS_KEY, jsonEncode(events));

  BackgroundFetch.finish();
}

How to use HTTP requests on "backgroundFetchHeadlessTask" method

hi,How to use HTTP requests on "backgroundFetchHeadlessTask" method
i use the package:dio/dio.dart ,When the program works in the foreground,it's ok!
But when APP completes its exit, it prompts a timeout,Not succeeding, always prompting timeouts
thanks!

Question about 'providing a short period of background running-time'

Is it known how lengthy a 'short period of background running-time' is with real world experiences on the 2 major platforms?

Are processes interrupted or killed when the 'short period' is exceeded? And if this is the case, do we get notified by the OS (on both platforms) if a running background task is about to be killed?

Is there any in-depth information about this?

How would one handle/survive killed background tasks, is there a known recovery strategy?

I am considering the use of flutter_background_fetch for my use-case which is to periodically upload a few megabytes of data, but it is vital this upload process should not be interrupted.

Thanks a lot for providing this plugin!

[BUG] Not working on some phone

Your Environment

  • Plugin version: background_fetch: ^0.2.0
  • Platform: iOS or Android
  • OS version: 7.0
  • Device manufacturer / model:techno spark
  • Flutter info (flutter info, flutter doctor):
  • Plugin config

To Reproduce
Steps to reproduce the behavior:

  1. close the app
  2. adb shell cmd jobscheduler run -f <your.application.id> 999
    Noting happen, I try it in my friend phone and in a emulator it works

Debug logs

  • ios XCode logs,
  • Android: nothing

Additional context
Add any other context about the problem here.

Does it run at exact specified time

Hey, I would like to know whether this plugin is able to run at exact specified time and in a periodic way and can be stopped from background. My use case is to fetch user location from GPS and store in SQFlite and does it handle Wake locks and device restarts? More important is will it be able to run on Chinese Rom mobiles like Mi, Honor?

Establishing platform channel during headless task [Android]

I'm not sure this belongs in the "Bug" category because the plugin works great!

However, I am having trouble processing the data during a headless task. Specifically, I would like to send the data to the native side for processing via flutter's platform message channel.

The data cannot be received natively because the message channel and handler are setup when the app is initialized (E.g. MainActivity's onCreate) but headless tasks run in the background and MainActivity is never created.

How do I setup the platform channel to be available both when the app is initialized as well as in the background through the background_fetch headless task?

Thanks!

[Initial Version]

The plugin is almost ready for release to those watching this repo.

[BUG] Finished with error: Gradle task assembleProductionDebug failed with exit code 1

Your Environment

  • Plugin version: 0.3.2
  • Platform: iOS or Android - Android
  • OS version: Windows 10
  • Device manufacturer / model: NA
  • Flutter info (flutter info, flutter doctor):

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.9.1+hotfix.2, on Microsoft Windows [Version 10.0.17763.805], locale en-US)

[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[√] Android Studio (version 3.5)
[√] Connected device (1 available)

• No issues found!

  • Plugin config

To Reproduce
Follow Headless Mechanism Steps
Steps to reproduce the behavior:

  1. Added Application.kt file
  2. Amend AndroidManifest.xml - I think this is were issue lays, since there is already android:name tag with value io.flutter.app.FlutterApplication
  3. When application is compiled, I have got

Finished with error: Gradle task assembleProductionDebug failed with exit code 1

ttempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference

2019-02-04 21:51:12.201 31983-31983/com.webstersys.touch E/EventBus: Could not dispatch event: class com.transistorsoft.locationmanager.event.HeadlessEvent to subscribing class class com.transistorsoft.flutter.backgroundgeolocation.HeadlessTask
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
at com.transistorsoft.flutter.backgroundgeolocation.HeadlessTask.initFlutterView(HeadlessTask.java:164)
at com.transistorsoft.flutter.backgroundgeolocation.HeadlessTask.onHeadlessEvent(HeadlessTask.java:91)
at java.lang.reflect.Method.invoke(Native Method)
at org.greenrobot.eventbus.EventBus.invokeSubscriber(EventBus.java:485)
at org.greenrobot.eventbus.EventBus.invokeSubscriber(EventBus.java:479)
at org.greenrobot.eventbus.HandlerPoster.handleMessage(HandlerPoster.java:67)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
2019-02-04 21:51:12.201 31983-31983/com.webstersys.touch D/EventBus: No subscribers registered for

android.os.DeadObjectException

08-27 12:34:28.875  1000  1408  5845 I WindowManager: WIN DEATH: Window{5b1e9ac u0 com.play.playapp/com.play.playapp.MainActivity}
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: Exception when unbinding service com.play.playapp/com.transistorsoft.flutter.backgroundfetch.HeadlessJobService
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: android.os.DeadObjectException
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at android.os.BinderProxy.transactNative(Native Method)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at android.os.BinderProxy.transact(Binder.java:1127)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at android.app.IApplicationThread$Stub$Proxy.scheduleUnbindService(IApplicationThread.java:1100)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at com.android.server.am.ActiveServices.removeConnectionLocked(ActiveServices.java:3028)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at com.android.server.am.ActiveServices.unbindServiceLocked(ActiveServices.java:1815)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at com.android.server.am.ActivityManagerService.unbindService(ActivityManagerService.java:21438)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at android.app.ContextImpl.unbindService(ContextImpl.java:1707)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at com.android.server.job.JobServiceContext.closeAndCleanupJobLocked(JobServiceContext.java:783)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at com.android.server.job.JobServiceContext.onServiceDisconnected(JobServiceContext.java:452)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at android.app.LoadedApk$ServiceDispatcher.doDeath(LoadedApk.java:1749)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1764)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at android.os.Handler.handleCallback(Handler.java:874)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at android.os.Handler.dispatchMessage(Handler.java:100)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at android.os.Looper.loop(Looper.java:198)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at com.android.server.SystemServer.run(SystemServer.java:479)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at com.android.server.SystemServer.main(SystemServer.java:307)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at java.lang.reflect.Method.invoke(Native Method)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
08-27 12:34:28.893  1000  1408  1408 W ActivityManager: 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:856)

Background task doesn't run after a while[BUG]

Your Environment

  • Plugin version: 1.21
  • Platform: Android
  • OS version: 8.0.0
  • Device manufacturer / model: OnePlus 3T
  • Flutter info (flutter info, flutter doctor): Doctor summary (to see all details, run flutter doctor -v):
    [√] Flutter (Channel stable, v1.2.1, on Microsoft Windows [Version 10.0.17134.706], locale de-DE)
    [√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    [!] Android Studio (version 3.0)
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.
    [√] Android Studio (version 3.2)
    [√] VS Code (version 1.33.1)
    [!] Connected device
    ! No devices available

! Doctor found issues in 2 categories.

  • Plugin config

To Reproduce
Steps to reproduce the behavior:

  1. BackgroundFetchConfig(
    minimumFetchInterval: 15,
    stopOnTerminate: false,
    startOnBoot: true,
    enableHeadless: true)
  2. call background task
  3. don't use the app for a day

Is it possible to use WorkManager?

Hello. Actually startOnBoot using jobscheduler doesn't work for non system apps.
Is it possible to use WorkManager instead of jobscheduler/alermmanager?
It works after reboot and all android api versions.
You dont have to switch jobscheduler and alermmanager internally anymore.

java.lang.IllegalArgumentException: No such service ComponentInfo{com.trackees.tracks/com.transistorsoft.tsbackgroundfetch.FetchJobService}

I am new to flutter. Getting below error when trying to use this plugin (Not using headless). Followed all steps mentioned in doc.

E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(24484): Failed to handle method call
 **E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(24484): java.lang.IllegalArgumentException: No such service ComponentInfo{com.trackees.tracks/com.transistorsoft.tsbackgroundfetch.FetchJobService}
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(24484): 	at android.os.Parcel.readException(Parcel.java:2008)**
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(24484): 	at android.os.Parcel.readException(Parcel.java:1950)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(24484): 	at android.app.job.IJobScheduler$Stub$Proxy.schedule(IJobScheduler.java:180)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(24484): 	at android.app.JobSchedulerImpl.schedule(JobSchedulerImpl.java:44)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(24484): 	at com.transistorsoft.tsbackgroundfetch.BackgroundFetch.start(BackgroundFetch.java:95)

[BUG] iOS Background Activity not working

Your Environment

  • Plugin version: 0.1.2
  • Platform: iOS
  • OS version: 12.1.4
  • Device manufacturer / model: iPhone 6 / iPhone 8
  • Flutter info (flutter info, flutter doctor):
[✓] Flutter (Channel beta, v1.3.8, on Mac OS X 10.14.3 18D109, locale en-GB)
    • Flutter version 1.3.8 at /Users/gmf/Documents/dev/flutter
    • Framework revision e5b1ed7a7f (3 weeks ago), 2019-03-06 14:23:37 -0800
    • Engine revision f4951df193
    • Dart version 2.2.1 (build 2.2.1-dev.0.0 571ea80e11)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/gmf/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
    • All Android licenses accepted.

[✓] iOS toolchain - develop for iOS devices (Xcode 10.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 10.1, Build version 10B61
    • ios-deploy 1.9.4
    • CocoaPods version 1.6.1

[✓] Android Studio (version 3.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 33.3.1
    • Dart plugin version 182.5215
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[✓] VS Code (version 1.32.3)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 2.24.0
  • Plugin config
 BackgroundFetchConfig(
                minimumFetchInterval: 20,
                stopOnTerminate: false,
                enableHeadless: true,
                startOnBoot: true),
            _onBackgroundFetch)

Problem:
Hi,
I am creating this post because on iOS the background fetch doesn't seem to be running. On Android it's working perfectly, with the App sleeping or closed, but on iOS nothing happens. There is any way of testing or debugging this? With the Simulate tool, it works well and executes exactly what its expected. Can you give me some info? There is any other configuration needed? The Background Fetch works when sleeping and closed ?

Best Regards

[BUG] PlatFormException due to no service.

Your Environment

  • Plugin version: 0.3.1
  • Platform: iOS or Android : Android
  • OS version: API 28
  • Device manufacturer / model: Emulator (Pixel3A)
  • Flutter info (flutter info, flutter doctor): $ flutter doctor
    Doctor summary (to see all details, run flutter doctor -v):
    [√] Flutter (Channel stable, v1.9.1+hotfix.2, on Microsoft Windows [Version 10.0.18362.356], locale en-IN)

[√] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[√] Android Studio (version 3.5)
[√] VS Code (version 1.38.1)
[√] Connected device (1 available)

• No issues found!

  • Plugin config : BackgroundFetch.configure(
    BackgroundFetchConfig(
    minimumFetchInterval: 15,
    stopOnTerminate: false,
    enableHeadless: false,
    requiresBatteryNotLow: false,
    requiresCharging: false,
    requiresStorageNotLow: false,
    requiresDeviceIdle: false,
    requiredNetworkType: BackgroundFetchConfig.NETWORK_TYPE_ANY),

To Reproduce
Steps to reproduce the behavior:

  1. Copy the example app.
  2. remove the 3 variables _status, _enable, _events and add bgStatus (does same thing as _status)
  3. run in debug-mode (Error occurred in release mode as well)
  4. Exception -> Exception has occurred.
    PlatformException (PlatformException(error, No such service ComponentInfo{com.baseapp.powersense/com.transistorsoft.tsbackgroundfetch.FetchJobService}, null))

Debug logs

  • ios XCode logs,
  • Android: $ adb logcat
    $ adb logcat *:S flutter:V, TSBackgroundFetch:V
    --------- beginning of crash
    --------- beginning of main
    09-30 16:48:32.193 3902 3902 W TSBackgroundFetch: - Configuration error: {forceReload: false, jobService: null} is incompatible with stopOnTerminate: false: Enforcing stopOnTerminate: true.
    09-30 16:48:32.193 3902 3902 D TSBackgroundFetch: - configure: {
    09-30 16:48:32.193 3902 3902 D TSBackgroundFetch: "minimumFetchInterval": 15,
    09-30 16:48:32.193 3902 3902 D TSBackgroundFetch: "stopOnTerminate": true,
    09-30 16:48:32.193 3902 3902 D TSBackgroundFetch: "requiredNetworkType": 1,
    09-30 16:48:32.193 3902 3902 D TSBackgroundFetch: "requiresBatteryNotLow": false,
    09-30 16:48:32.193 3902 3902 D TSBackgroundFetch: "requiresCharging": false,
    09-30 16:48:32.193 3902 3902 D TSBackgroundFetch: "requiresDeviceIdle": false,
    09-30 16:48:32.193 3902 3902 D TSBackgroundFetch: "requiresStorageNotLow": false,
    09-30 16:48:32.193 3902 3902 D TSBackgroundFetch: "startOnBoot": false,
    09-30 16:48:32.193 3902 3902 D TSBackgroundFetch: "forceReload": false
    09-30 16:48:32.193 3902 3902 D TSBackgroundFetch: }
    09-30 16:48:32.204 3902 3902 D TSBackgroundFetch: - start
    09-30 16:48:32.213 3902 4113 I flutter : [BackgroundFetch] configure ERROR: Throw of null.
    09-30 16:48:32.213 3902 4113 E flutter : [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type 'NullThrownError' is not a subtype of type 'int'
    09-30 16:48:32.213 3902 4113 E flutter : #0 _MyAppState.initPlatformState.. (package:powersense/main.dart:90)
    09-30 16:48:32.213 3902 4113 E flutter : #1 State.setState (package:flutter/src/widgets/framework.dart:1141)
    09-30 16:48:32.213 3902 4113 E flutter : #2 _MyAppState.initPlatformState. (package:powersense/main.dart:89)
    09-30 16:48:32.213 3902 4113 E flutter : #3 _rootRunUnary (dart:async/zone.dart:1132)
    09-30 16:48:32.213 3902 4113 E flutter : #4 _CustomZone.runUnary (dart:async/zone.dart:1029)
    09-30 16:48:32.213 3902 4113 E flutter : #5 _FutureListener.handleError (dart:async/future_impl.dart:155)
    09-30 16:48:32.213 3902 4113 E flutter : #6 Future._propagateToListeners.handleError (dart:async/future_impl.dart:690)
    09-30 16:48:32.213 3902 4113 E flutter : #7 Future._propagateToListeners (dart:async/future_impl.dart:711)
    09-30 16:48:32.213 3902 4113 E flutter : #8 Future._completeError (dart:async/future_impl.dart:530)
    09-30 16:48:32.213 3902 4113 E flutter : #9 Future._asyncCompleteError. (dart:async/future_impl.dart:578)
    09-30 16:48:32.213 3902 4113 E flutter : #10 _rootRun (dart:async/zone.dart:1124)
    09-30 16:48:32.213 3902 4113 E flutter : #11 _CustomZone.run (dart:async/zone.dart:1021)
    09-30 16:48:32.213 3902 4113 E flutter : #12 _CustomZone.runGuarded (dart:async/zone.dart:923)
    09-30 16:48:32.213 3902 4113 E flutter : #13 _CustomZone.bindCallbackGuarded. (dart:async/zone.dart:963)
    09-30 16:48:32.213 3902 4113 E flutter : #14 _microtaskLoop (dart:async/schedule_microtask.dart:41)
    09-30 16:48:32.213 3902 4113 E flutter : #15 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50)
    09-30 16:48:32.213 3902 4113 E flutter :

Additional context
Add any other context about the problem here.
i'm trying to fetch shared preferences and call a REST api after SharedPref to compare a single value in order to send notification to the user.

Cant configure headless task

Your Environment

  • Plugin version: 0.2.0
  • Platform: Android
  • OS version: 28
  • Device manufacturer / model: Oneplus 6
  • Flutter info (flutter info, flutter doctor): No issues
  • Plugin config

Debug logs
2019-05-02 12:17:15.324 1191-1191/? E/LoadedApk: Unable to instantiate appComponentFactory
java.lang.ClassNotFoundException: Didn't find class "androidx.core.app.CoreComponentFactory" on path: DexPathList[[],nativeLibraryDirectories=[/data/app/com.google.android.gms-25uIRN7aQhfDvg4LoudGgA==/lib/arm64, /data/app/com.google.android.gms-25uIRN7aQhfDvg4LoudGgA==/base.apk!/lib/arm64-v8a, /system/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:169)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.LoadedApk.createAppFactory(LoadedApk.java:226)
at android.app.LoadedApk.updateApplicationInfo(LoadedApk.java:346)
at android.app.ActivityThread.handleDispatchPackageBroadcast(ActivityThread.java:5524)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at com.android.server.SystemServer.run(SystemServer.java:482)
at com.android.server.SystemServer.main(SystemServer.java:322)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:838)
2019-05-02 12:17:15.325 1191-1191/? E/LoadedApk: Unable to instantiate appComponentFactory
java.lang.ClassNotFoundException: Didn't find class "androidx.core.app.CoreComponentFactory" on path: DexPathList[[],nativeLibraryDirectories=[/data/app/com.google.android.gms-25uIRN7aQhfDvg4LoudGgA==/lib/arm64, /data/app/com.google.android.gms-25uIRN7aQhfDvg4LoudGgA==/base.apk!/lib/arm64-v8a, /system/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:169)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.LoadedApk.createAppFactory(LoadedApk.java:226)
at android.app.LoadedApk.updateApplicationInfo(LoadedApk.java:346)
at android.app.ActivityThread.handleDispatchPackageBroadcast(ActivityThread.java:5524)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at com.android.server.SystemServer.run(SystemServer.java:482)
at com.android.server.SystemServer.main(SystemServer.java:322)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:838)

Additional context
App gets stuck on "installing build". Error only occurs when setting the android:name to .Application in Manifest.

Null pointer exception in background fetch in android.app.Activity.getApplication()

Your Environment

  • Plugin version: latest
  • Platform: iOS or Android Android
  • OS version:
  • Device manufacturer / model:
  • Flutter info (flutter info, flutter doctor):
  • Plugin config

To Reproduce
Steps to reproduce the behavior:

  1. Background fetch headless task

Debug logs

  • ios XCode logs,

  • Android: $ adb logcat
    08-05 10:00:13.515 16163 16163 E AndroidRuntime: java.lang.RuntimeException: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.Application android.app.Activity.getApplication()' on a null object reference
    Additional context
    Add any other context about the problem here.

  • Application.java

import com.transistorsoft.flutter.backgroundfetch.BackgroundFetchPlugin;

import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class Application extends FlutterApplication implements PluginRegistry.PluginRegistrantCallback {
  @Override
  public void onCreate() {
    super.onCreate();
    BackgroundFetchPlugin.setPluginRegistrant(this);
  }

  @Override
  public void registerWith(PluginRegistry registry) {
    GeneratedPluginRegistrant.registerWith(registry);
  }
}

[BUG] java.lang.IllegalArgumentException: No such service

Your Environment

  • Plugin version: 33.3.1
  • Platform: Android
  • OS version: 9
  • Device manufacturer / model: Pixel 3 XL
  • Flutter info (flutter info, flutter doctor):
[✓] Flutter (Channel stable, v1.0.0, on Mac OS X 10.14.3 18D109, locale en-US)
    • Flutter version 1.0.0 at /Users/bryandixon/development/flutter
    • Framework revision 5391447fae (3 months ago), 2018-11-29 19:41:26 -0800
    • Engine revision 7375a0f414
    • Dart version 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)

[✓] Android toolchain - develop for Android devices (Android SDK 28.0.3)
    • Android SDK at /Users/bryandixon/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling
      support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
    • All Android licenses accepted.

[✓] iOS toolchain - develop for iOS devices (Xcode 10.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 10.1, Build version 10B61
    • ios-deploy 1.9.4
    • CocoaPods version 1.5.3

[✓] Android Studio (version 3.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 33.3.1
    • Dart plugin version 182.5215
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[✓] Connected device (1 available)
    • Pixel 3 XL • 89AY04YTA • android-arm64 • Android 9 (API 28)

• No issues found!
  • Plugin config

To Reproduce
Steps to reproduce the behavior:

1. Future<void> initPlatformState() async {
    BackgroundFetch.configure(BackgroundFetchConfig(
        minimumFetchInterval: 15,
        stopOnTerminate: false,
        enableHeadless: true
    ), () async {
      _fetchData(); //my async method that I want to run periodically in the background
      BackgroundFetch.finish();
    });
  }
2. Started App
3. Seems like it can't find the merged service definition in the Android Manifest

Debug logs

Syncing files to device Pixel 3 XL...
D/TSBackgroundFetch(17880): - configure: {
D/TSBackgroundFetch(17880):   "minimumFetchInterval": 15,
D/TSBackgroundFetch(17880):   "stopOnTerminate": false,
D/TSBackgroundFetch(17880):   "startOnBoot": false,
D/TSBackgroundFetch(17880):   "forceReload": false,
D/TSBackgroundFetch(17880):   "jobService": "com.transistorsoft.flutter.backgroundfetch.HeadlessJobService"
D/TSBackgroundFetch(17880): }
D/TSBackgroundFetch(17880): - start
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): Failed to handle method call
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): java.lang.IllegalArgumentException: No such service ComponentInfo{com.example.myapp/com.transistorsoft.tsbackgroundfetch.FetchJobService}
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at android.os.Parcel.createException(Parcel.java:1954)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at android.os.Parcel.readException(Parcel.java:1918)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at android.os.Parcel.readException(Parcel.java:1868)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at android.app.job.IJobScheduler$Stub$Proxy.schedule(IJobScheduler.java:184)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at android.app.JobSchedulerImpl.schedule(JobSchedulerImpl.java:44)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at com.transistorsoft.tsbackgroundfetch.BackgroundFetch.start(BackgroundFetch.java:95)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at com.transistorsoft.tsbackgroundfetch.BackgroundFetch.configure(BackgroundFetch.java:67)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at com.transistorsoft.flutter.backgroundfetch.BackgroundFetchPlugin.configure(BackgroundFetchPlugin.java:119)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at com.transistorsoft.flutter.backgroundfetch.BackgroundFetchPlugin.onMethodCall(BackgroundFetchPlugin.java:63)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:200)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at io.flutter.view.FlutterNativeView.handlePlatformMessage(FlutterNativeView.java:163)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at android.os.MessageQueue.next(MessageQueue.java:326)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at android.os.Looper.loop(Looper.java:160)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at android.app.ActivityThread.main(ActivityThread.java:6718)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): Caused by: android.os.RemoteException: Remote stack trace:
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at com.android.server.job.JobSchedulerService$JobSchedulerStub.enforceValidJobRequest(JobSchedulerService.java:2494)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at com.android.server.job.JobSchedulerService$JobSchedulerStub.schedule(JobSchedulerService.java:2556)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at android.app.job.IJobScheduler$Stub.onTransact(IJobScheduler.java:60)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 	at android.os.Binder.execTransact(Binder.java:731)
E/MethodChannel#com.transistorsoft/flutter_background_fetch/methods(17880): 

Additional context
Add any other context about the problem here.
Seems similar to issue: #13
I've tried version 0.1.2 (solution for issue #13), '^0.1.0', and the pull requested version for AndroidX and all of them give the above error.

Obsolete variables with new gradle version

If this isn't a bug, sorry, but when a run following the documentation and the gradle version is 4.10.2, it run's ok.
But if i update de version of gradle to 5.4.1, flutter give me the following error:

**API 'variantOutput.getProcessResources()' is obsolete and has been replaced with 'variantOutput.getProcessResourcesProvider()

API 'variant.getMergeAssets()' is obsolete and has been replaced with 'variant.getMergeAssetsProvider()'.**

i'd like to know if there's a way to solve this?
Thank's !

backgroundfetch/HeadlessTask.java uses or overrides a deprecated API.

  • Plugin version: 0.3.2
  • Platform: Android
  • OS version: Mac OS 10.15
  • Device manufacturer / model: Nexus S API 28 (emulator)
  • Flutter info (flutter info, flutter doctor):
[✓] Flutter (Channel stable, v1.9.1+hotfix.4, on Mac OS X 10.15.1 19B88, locale en-GB)
 
[!] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    ! Some Android licenses not accepted.  To resolve this, run: flutter doctor --android-licenses
[✓] Xcode - develop for iOS and macOS (Xcode 11.2)
[!] Android Studio (not installed)
[✓] IntelliJ IDEA Ultimate Edition (version 2019.2.4)
[✓] VS Code (version 1.40.0)
[✓] Connected device (1 available)
  • Plugin config
BackgroundFetch.configure(BackgroundFetchConfig(
        minimumFetchInterval: 15,
        stopOnTerminate: false,
        enableHeadless: false,
        requiresBatteryNotLow: false,
        requiresCharging: false,
        requiresStorageNotLow: false,
        requiresDeviceIdle: false,
        requiredNetworkType: BackgroundFetchConfig.NETWORK_TYPE_NONE
    )

To Reproduce
Steps to reproduce the behavior:

  1. Created new Flutter project
  2. Follow https://pub.dev/packages/background_fetch
  3. Run emulator
  4. Start debugging on it

Debug logs

Launching lib/main.dart on Android SDK built for x86 in debug mode...
Note: /Users/***/Bin/flutter/.pub-cache/hosted/pub.dartlang.org/background_fetch-0.3.2/android/src/main/java/com/transistorsoft/flutter/backgroundfetch/HeadlessTask.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Built build/app/outputs/apk/debug/app-debug.apk.

[BUG][Android] After killing application not getting any background call

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.0.0, on Microsoft Windows [Version 6.3.9600], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK 28.0.3)
[√] Android Studio (version 3.3)
[√] Connected device (1 available)

• No issues found!

To Reproduce
Steps to reproduce the behavior:

  1. Just run the app see the log when app is on foreground its working fine
  2. When we killed application there no work done after termination of app
  1. I am doing flutter cloud_storage database entry on firebase console when user killed like below
 Future<void> initPlatformState() async {
    // Configure BackgroundFetch.
    BackgroundFetch.configure(BackgroundFetchConfig(
        minimumFetchInterval: 15,
        stopOnTerminate: false,
        forceReload: true,
        startOnBoot: true,
        enableHeadless: true
    ), () async {
      // This is the fetch-event callback.
      print('[BackgroundFetch] Event received');
      setState(() {
        _events.insert(0, new DateTime.now());

       // My firebase data addition code when we are getting background call.
        addData();
      });
      // IMPORTANT:  You must signal completion of your fetch task or the OS can punish your app
      // for taking too long in the background.
      BackgroundFetch.finish();
    }).then((int status) {
      print('[BackgroundFetch] SUCCESS: $status');
      setState(() {
        _status = status;
      });
    }).catchError((e) {
      print('[BackgroundFetch] ERROR: $e');
      setState(() {
        _status = e;
      });
    });

    // Optionally query the current BackgroundFetch status.
    int status = await BackgroundFetch.status;
    setState(() {
      _status = status;
    });
    if (!mounted) return;
  }

Get notified when new data in backgroundFetch is available

Is your feature request related to a problem? Please describe.
With BackgroundFetch I check for new updates, when there are some updates I would like to notify my app as long as it is running and in foreground.

Describe the solution you'd like
I my opinion a Stream of the status would be the simplest solution. When a backgroundFetch is completed with BackgroundFetch.finish and the app is running, the new status is pushed to the stream.

Describe alternatives you've considered
An alternative would be to add a callback.

[BUG] Headless Task keep stopping the app

Your Environment

Plugin version: ^0.2.0
Platform: Android
OS version: emulator running on API 29
Device manufacturer / model: emulator
Flutter info flutter doctor:

[✓] Flutter (Channel stable, v1.9.1+hotfix.2, on Mac OS X 10.14.6 18G95, locale en-GB)
    • Flutter version 1.9.1+hotfix.2 at /Users/amazliah/flutter
    • Framework revision 2d2a1ffec9 (2 weeks ago), 2019-09-06 18:39:49 -0700
    • Engine revision b863200c37
    • Dart version 2.5.0

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at /Users/amazliah/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-29, build-tools 29.0.2
    • ANDROID_HOME = /Users/amazliah/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
    ! Some Android licenses not accepted.  To resolve this, run: flutter doctor --android-licenses

[✓] Xcode - develop for iOS and macOS (Xcode 10.3)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 10.3, Build version 10G8
    • CocoaPods version 1.7.5

[✓] Android Studio (version 3.5)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 39.0.3
    • Dart plugin version 191.8423
    • Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)

[!] IntelliJ IDEA Community Edition (version 2019.1.1)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    ✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.
    • For information about installing plugins, see
      https://flutter.dev/intellij-setup/#installing-the-plugins

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

[✓] Connected device (3 available)
    • Android SDK built for x86 • emulator-5554                            • android-x86 • Android 10 (API 29) (emulator)
    • Amitai’s iPhone           • 7edd26a6799275901fd814f834d50eea0707af99 • ios         • iOS 12.1.4
    • iPhone Xʀ                 • 992F0FBD-B1E7-41B9-B8B5-5A5546709EE2     • ios         • com.apple.CoreSimulator.SimRuntime.iOS-12-4 (simulator)

! Doctor found issues in 2 categories.
Process finished with exit code 0

Plugin config

BackgroundFetch.configure(
        BackgroundFetchConfig(
            minimumFetchInterval: 15,
            stopOnTerminate: false,
            enableHeadless: true,
            startOnBoot: true), () async {
      // This is the fetch-event callback.
      print('[BackgroundFetch] Event received hfdhfdhdhfdhdh');

      Firestore.instance
          .collection('steps')
          .document('1')
          .setData({'value': DateTime.now()});

      // IMPORTANT:  You must signal completion of your fetch task or the OS can punish your app
      // for taking too long in the background.
      BackgroundFetch.finish();
    }).then((int status) {
      print('[BackgroundFetch] configure success: $status');
    }).catchError((e) {
      print('[BackgroundFetch] configure ERROR: $e');
    });

To Reproduce
Steps to reproduce the behavior:

  1. Run the app on emulator
  2. Close the app
  3. Force background fetch with adb shell cmd jobscheduler run -f com.example.amitai_awesome_app 999
  4. Log at emulator as app gives error popup, also logs give error

Debug logs

Process: com.example.amitai_awesome_app, PID: 24213
java.lang.RuntimeException: java.lang.NullPointerException: Attempt to invoke interface method 'void io.flutter.plugin.common.PluginRegistry$PluginRegistrantCallback.registerWith(io.flutter.plugin.common.PluginRegistry)' on a null object reference
at android.app.job.JobServiceEngine$JobHandler.handleMessage(JobServiceEngine.java:112)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void io.flutter.plugin.common.PluginRegistry$PluginRegistrantCallback.registerWith(io.flutter.plugin.common.PluginRegistry)' on a null object reference
at com.transistorsoft.flutter.backgroundfetch.HeadlessTask.initFlutterView(HeadlessTask.java:133)
at com.transistorsoft.flutter.backgroundfetch.HeadlessTask.(HeadlessTask.java:47)
at com.transistorsoft.flutter.backgroundfetch.HeadlessJobService.onStartJob(HeadlessJobService.java:38)
at android.app.job.JobService$1.onStartJob(JobService.java:62)
at android.app.job.JobServiceEngine$JobHandler.handleMessage(JobServiceEngine.java:108)

Additional context

I'm trying to use headless task of my android emulator but when I'm forcing a background fetch after closing the app, it's crashing.

My Application.kt

package com.example.amitai_awesome_app

import com.transistorsoft.flutter.backgroundfetch.BackgroundFetchPlugin;

import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugins.GeneratedPluginRegistrant;

class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
  override fun onCreate() {
    super.onCreate();
    BackgroundFetchPlugin.setPluginRegistrant(this);
  }

  override fun registerWith(registry: PluginRegistry) {
    GeneratedPluginRegistrant.registerWith(registry);
  }
}

The headless task code is:

/// This "Headless Task" is run when app is terminated.
void backgroundFetchHeadlessTask() async {
  print('[BackgroundFetch] Headless event received.');

  BackgroundFetch.finish();
}

Headless Background Task can not be executed

Hi,
if the barcode scan library (barcode_scan: ^0.0.8) is used,
the following exception occurs after the background task is triggered (adb shell cmd jobscheduler run -f 999)

java.lang.RuntimeException: java.lang.IllegalStateException: registrar.activity() must not be null
02-25 11:32:42.472 11461 11461 E AndroidRuntime: at android.app.job.JobServiceEngine$JobHandler.handleMessage(JobServiceEngine.java:112)
02-25 11:32:42.472 11461 11461 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:108)
02-25 11:32:42.472 11461 11461 E AndroidRuntime: at android.os.Looper.loop(Looper.java:166)
02-25 11:32:42.472 11461 11461 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:7425)
02-25 11:32:42.472 11461 11461 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
02-25 11:32:42.472 11461 11461 E AndroidRuntime: at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
02-25 11:32:42.472 11461 11461 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
02-25 11:32:42.472 11461 11461 E AndroidRuntime: Caused by: java.lang.IllegalStateException: registrar.activity() must not be null
02-25 11:32:42.472 11461 11461 E AndroidRuntime: at com.apptreesoftware.barcodescan.BarcodeScanPlugin$Companion.registerWith(BarcodeScanPlugin.kt:19)
02-25 11:32:42.472 11461 11461 E AndroidRuntime: at com.apptreesoftware.barcodescan.BarcodeScanPlugin.registerWith(Unknown Source:2)
02-25 11:32:42.472 11461 11461 E AndroidRuntime: at io.flutter.plugins.GeneratedPluginRegistrant.registerWith(GeneratedPluginRegistrant.java:22)
02-25 11:32:42.472 11461 11461 E AndroidRuntime: at com.example.xyz.Application.registerWith(Application.java:17)
02-25 11:32:42.472 11461 11461 E AndroidRuntime: at com.transistorsoft.flutter.backgroundfetch.HeadlessTask.initFlutterView(HeadlessTask.java:133)
02-25 11:32:42.472 11461 11461 E AndroidRuntime: at com.transistorsoft.flutter.backgroundfetch.HeadlessTask.(HeadlessTask.java:47)
02-25 11:32:42.472 11461 11461 E AndroidRuntime: at com.transistorsoft.flutter.backgroundfetch.HeadlessJobService.onStartJob(HeadlessJobService.java:38)
02-25 11:32:42.472 11461 11461 E AndroidRuntime: at android.app.job.JobService$1.onStartJob(JobService.j
02-25 11:32:42.472 11461 11461 E AndroidRuntime: at android.app.job.JobServiceEngine$JobHandler.handleMessage(JobServiceEngine.java)

The Task will not be excecuted.
Thanks for your help.

[BUG] Incompatibility with other plugins

Your Environment

  • Plugin version: 0.2.0
  • Platform: Android
  • OS version: Windows
  • Device manufacturer / model:
  • Plugin config: --> Example folder

To Reproduce
Steps to reproduce the behavior:

  1. Open the example project
  2. Add image_picker: 0.4.12+1 as a dependency
  3. Install app
  4. Close app (minimizinig is not enough)
  5. Trigger a headless background fetch event => adb shell cmd jobscheduler run -f com.transistorsoft.flutter.backgroundfetch.backgroundfetchexample 999
  6. See error below

Debug logs

04-10 10:56:12.838 16400 16400 D TSBackgroundFetch: - Background Fetch event received
04-10 10:56:12.850 16400 16400 D TSBackgroundFetch: - finish
04-10 10:56:12.850 16400 16400 D TSBackgroundFetch: - jobFinished
04-10 10:56:12.865 16400 16400 D TSBackgroundFetch: HeadlessJobService onStartJob
04-10 10:56:12.866 16400 16400 D TSBackgroundFetch: 💀 [HeadlessTask]
04-10 10:56:13.247 16400 16400 E JobServiceEngine: Error while executing job: 998
04-10 10:56:13.248 16400 16400 D AndroidRuntime: Shutting down VM
04-10 10:56:13.257 16400 16400 E AndroidRuntime: FATAL EXCEPTION: main
04-10 10:56:13.257 16400 16400 E AndroidRuntime: Process: com.transistorsoft.flutter.backgroundfetch.backgroundfetchexample, PID: 16400
04-10 10:56:13.257 16400 16400 E AndroidRuntime: java.lang.RuntimeException: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.app.Activity.getExternalFilesDir(java.lang.String)' on a null object reference
04-10 10:56:13.257 16400 16400 E AndroidRuntime:        at android.app.job.JobServiceEngine$JobHandler.handleMessage(JobServiceEngine.java:112)
04-10 10:56:13.257 16400 16400 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:106)
04-10 10:56:13.257 16400 16400 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:164)
04-10 10:56:13.257 16400 16400 E AndroidRuntime:        at android.app.ActivityThread.main(ActivityThread.java:6494)
04-10 10:56:13.257 16400 16400 E AndroidRuntime:        at java.lang.reflect.Method.invoke(Native Method)
04-10 10:56:13.257 16400 16400 E AndroidRuntime:        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
04-10 10:56:13.257 16400 16400 E AndroidRuntime:        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
04-10 10:56:13.257 16400 16400 E AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.app.Activity.getExternalFilesDir(java.lang.String)' on a null object reference
04-10 10:56:13.257 16400 16400 E AndroidRuntime:        at io.flutter.plugins.imagepicker.ImagePickerPlugin.registerWith(ImagePickerPlugin.java:27)
04-10 10:56:13.257 16400 16400 E AndroidRuntime:        at io.flutter.plugins.GeneratedPluginRegistrant.registerWith(GeneratedPluginRegistrant.java:17)
04-10 10:56:13.257 16400 16400 E AndroidRuntime:        at com.transistorsoft.flutter.backgroundfetch.backgroundfetchexample.Application.registerWith(Application.java:17)
04-10 10:56:13.257 16400 16400 E AndroidRuntime:        at com.transistorsoft.flutter.backgroundfetch.HeadlessTask.initFlutterView(HeadlessTask.java:133)
04-10 10:56:13.257 16400 16400 E AndroidRuntime:        at com.transistorsoft.flutter.backgroundfetch.HeadlessTask.<init>(HeadlessTask.java:47)
04-10 10:56:13.257 16400 16400 E AndroidRuntime:        at com.transistorsoft.flutter.backgroundfetch.HeadlessJobService.onStartJob(HeadlessJobService.java:38)
04-10 10:56:13.257 16400 16400 E AndroidRuntime:        at android.app.job.JobService$1.onStartJob(JobService.java:71)
04-10 10:56:13.257 16400 16400 E AndroidRuntime:        at android.app.job.JobServiceEngine$JobHandler.handleMessage(JobServiceEngine.java:108)
04-10 10:56:13.257 16400 16400 E AndroidRuntime:        ... 6 more
04-10 10:56:13.273   767   782 I ActivityManager: Showing crash dialog for package com.transistorsoft.flutter.backgroundfetch.backgroundfetchexample u0
04-10 10:56:13.281   767   781 W BroadcastQueue: Background execution not allowed: receiving Intent { act=android.intent.action.DROPBOX_ENTRY_ADDED flg=0x10 (has extras) } to com.google.android.gms/.stats.service.DropBoxEntryAddedReceiver
04-10 10:56:13.281   767   781 W BroadcastQueue: Background execution not allowed: receiving Intent { act=android.intent.action.DROPBOX_ENTRY_ADDED flg=0x10 (has extras) } to com.google.android.gms/.chimera.GmsIntentOperationService$PersistentTrustedReceiver

Do you have any ideas how to fix this? :)

Do not splash screen at each run

First, thank you for this great package!

Each time that the background runs I see the splash screen appears and disappears (if I am using the cellphone).

There is a way to change some parameter to avoid the splash screen to be shown?

Thanks

[mounted value becomes false inside _onBackgroundFetch callback. Due to this i am unable to run setState(() {}). ]

Your Environment

  • Plugin version: background_fetch: ^0.2.0
  • Platform: Android
  • OS version: Android 7.0
  • Device manufacturer / model: Redmi Note 6
  • Flutter info (flutter info, flutter doctor):

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, v1.7.8+hotfix.4, on Linux, locale en_IN)

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[✓] Android Studio (version 3.4)
[!] VS Code (version 1.34.0)
✗ Flutter extension not installed; install from
https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[✓] Connected device (1 available)

  • Plugin config

To Reproduce
Steps to reproduce the behavior:
Calling setState((){}); throws below error when setState() called from BackgroundFetch callback

BackgroundFetch.configure(BackgroundFetchConfig(
        minimumFetchInterval: 15,
        stopOnTerminate: false,
        enableHeadless: true,
        forceReload: false
    ), () async {
      // This is the fetch-event callback.
      print('[BackgroundFetch] Event received');
      //throws error
      setState(() {
        print('@@@@@ background fetch callback - setState worked');
        _events.insert(0, new DateTime.now().toString());
      });     
      BackgroundFetch.finish();
    }).then((int status) {
      print('[BackgroundFetch] SUCCESS: $status');
      setState(() {
        _status = status;
      });
    }).catchError((e) {
      print('[BackgroundFetch] ERROR: $e');
      setState(() {
        _status = e;
      });
    });
    int status = await BackgroundFetch.status;
    setState(() {
      _status = status;
    });
    if (!mounted) return;
  }

Debug logs
D/TSBackgroundFetch( 6511): - configure: {
D/TSBackgroundFetch( 6511): "minimumFetchInterval": 15,
D/TSBackgroundFetch( 6511): "stopOnTerminate": false,
D/TSBackgroundFetch( 6511): "startOnBoot": false,
D/TSBackgroundFetch( 6511): "forceReload": false,
D/TSBackgroundFetch( 6511): "jobService": "com.transistorsoft.flutter.backgroundfetch.HeadlessJobService"
D/TSBackgroundFetch( 6511): }
D/TSBackgroundFetch( 6511): - start
I/flutter ( 6511): [BackgroundFetch] SUCCESS: 2
D/TSBackgroundFetch( 6511): - Background Fetch event received
I/flutter ( 6511): [BackgroundFetch] Event received
E/flutter ( 6511): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: setState() called after dispose(): _HomePageState#53dc8(lifecycle state: defunct, not mounted)
E/flutter ( 6511): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
E/flutter ( 6511): The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter ( 6511): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
E/flutter ( 6511): #0 State.setState. (package:flutter/src/widgets/framework.dart:1105:9)
E/flutter ( 6511): #1 State.setState (package:flutter/src/widgets/framework.dart:1140:6)
E/flutter ( 6511): #2 _HomePageState.initPlatformState. (package:demo_mobile/pages/homepage.dart:85:7)
E/flutter ( 6511):
E/flutter ( 6511): #3 BackgroundFetch.configure. (package:background_fetch/background_fetch.dart:169:17)
E/flutter ( 6511): #4 _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter ( 6511): #5 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter ( 6511): #6 _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
E/flutter ( 6511): #7 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:336:11)
E/flutter ( 6511): #8 _DelayedData.perform (dart:async/stream_impl.dart:591:14)
E/flutter ( 6511): #9 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:707:11)
E/flutter ( 6511): #10 _PendingEvents.schedule. (dart:async/stream_impl.dart:667:7)
E/flutter ( 6511): #11 _rootRun (dart:async/zone.dart:1120:38)
E/flutter ( 6511): #12 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter ( 6511): #13 _CustomZone.runGuarded (dart:async/zone.dart:923:7)
E/flutter ( 6511): #14 _CustomZone.bindCallbackGuarded. (dart:async/zone.dart:963:23)
E/flutter ( 6511): #15 _rootRun (dart:async/zone.dart:1124:13)
E/flutter ( 6511): #16 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter ( 6511): #17 _CustomZone.runGuarded (dart:async/zone.dart:923:7)
E/flutter ( 6511): #18 _CustomZone.bindCallbackGuarded. (dart:async/zone.dart:963:23)
E/flutter ( 6511): #19 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter ( 6511): #20 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
E/flutter ( 6511):

Additional context
Add any other context about the problem here.

Package doesn't work, When i am executing, the App is closing.

I always see this text: "Running Gradle task 'assembleDebug'..." and it is never end.

background_fetch

  • Plugin version: 0.2.0
  • Platform: Android
  • OS version: 9.0 (Pie) - API 28
  • Device manufacturer / model: Nexus 5x Emulator
  • Flutter info (flutter info, flutter doctor):

flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.2.1, on Microsoft Windows [Version 10.0.17134.706], locale tr-TR)
[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[√] Android Studio (version 3.3)
[√] VS Code (version 1.33.1)
[√] Connected device (1 available)

• No issues found!

AndroidManifest.xml :

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    package="com.example.back_work">

    <uses-permission android:name="android.permission.INTERNET"/>

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


Add a way to check if Background App Refresh is off in ios

Is your feature request related to a problem? Please describe.
BackgroundFetch.configure will hang/crash on ios if Background App Fetch is disabled for the app. There does not appear to be a way to check if this is the case before attempting to start the background process.

Describe the solution you'd like
Either a function that can be used to check if background fetch is unrunnable due to Background App Fetch being disabled, or a clean error to be returned from .configure in that scenario.

HeadlessTask.java:error: method findAppBundlePath in class FlutterMain cannot be applied to given types[BUG]

Environment
ubuntu 18.04
openjdk version "1.8.0_222"

  • Plugin version: latest
  • Platform: Android
  • OS version: API 28
  • Device manufacturer / model: emulator
  • Error info
/home/$USER/flutter/.pub-cache/hosted/pub.dartlang.org/background_fetch-0.3.0/android/src/main/java/com/transistorsoft/flutter/backgroundfetch/HeadlessTask.java:139: error: method findAppBundlePath in class FlutterMain cannot be applied to given types;
        args.bundlePath = FlutterMain.findAppBundlePath();              
                                     ^                                  
  required: Context                                                     
  found: no arguments                                                   
  reason: actual and formal argument lists differ in length             
1 error                                                                 
                                                                        
FAILURE: Build failed with an exception.                                
                                                                        
* What went wrong:                                                      
Execution failed for task ':background_fetch:compileDebugJavaWithJavac'.
> 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 log output. Run with --scan to get full insights.
                                                                        
* Get more help at https://help.gradle.org                              
                                                                        
BUILD FAILED in 0s                                                      
Running Gradle task 'assembleDebug'...                                  
Running Gradle task 'assembleDebug'... Done                         1.5s
Gradle task assembleDebug failed with exit code 1
  • Plugin config
    As shown in the Android setup.md

Additional context
I followed the complete setup and the app didn't even started ... I can show you code if needed ... but it's showing the error above and it does not even build the app itself . Please help me .

Question about restoring app from backup

Let's say a user reinstalls my app, and gets user data (e.g shared_preferences) restored thanks to Google backups. Will background_fetch start running the moment the app is reinstalled, or will it start only once the app gets launched for the first time?

can't apply android configuration

regarding the android configuration
in the file
android/app/build.gradle

apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

// flutter_background_geolocation (must be placed after the lines above)
+Project background_geolocation = project(':flutter_background_geolocation')
+apply from: "${background_geolocation.projectDir}/background_geolocation.gradle"

the first 2 lines don't exist, and after placing them, i've got an error

Could not get unknown property 'flutterRoot' for project ':app' of type org.gradle.api.Project.

Cannot run released app.

I have no problem for debug app + background_fetch. but when i try to release my app that using background_fetch, my app failed to launch without print any error. Is it a bug or we should configure something for release?

error while executing job

app crash and logcat

2019-02-27 13:12:37.249 11513-11513/? D/TSBackgroundFetch: - Background Fetch event received
2019-02-27 13:12:37.253 11513-11513/? D/TSBackgroundFetch: - finish
2019-02-27 13:12:37.253 11513-11513/? D/TSBackgroundFetch: - jobFinished
2019-02-27 13:12:37.259 11513-11513/? D/TSBackgroundFetch: HeadlessJobService onStartJob
2019-02-27 13:12:37.260 11513-11513/? D/TSBackgroundFetch: 💀 [HeadlessTask]
2019-02-27 13:12:37.345 11513-11513/? E/JobServiceEngine: Error while executing job: 998
2019-02-27 13:12:37.345 11513-11513/? D/AndroidRuntime: Shutting down VM
2019-02-27 13:12:37.347 11513-11513/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.tbm.test_background_fetch, PID: 11513
    java.lang.RuntimeException: java.lang.NullPointerException: Attempt to invoke interface method 'void io.flutter.plugin.common.PluginRegistry$PluginRegistrantCallback.registerWith(io.flutter.plugin.common.PluginRegistry)' on a null object reference
        at android.app.job.JobServiceEngine$JobHandler.handleMessage(JobServiceEngine.java:112)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
     Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void io.flutter.plugin.common.PluginRegistry$PluginRegistrantCallback.registerWith(io.flutter.plugin.common.PluginRegistry)' on a null object reference
        at com.transistorsoft.flutter.backgroundfetch.HeadlessTask.initFlutterView(HeadlessTask.java:133)
        at com.transistorsoft.flutter.backgroundfetch.HeadlessTask.<init>(HeadlessTask.java:47)
        at com.transistorsoft.flutter.backgroundfetch.HeadlessJobService.onStartJob(HeadlessJobService.java:38)
        at android.app.job.JobService$1.onStartJob(JobService.java:71)
        at android.app.job.JobServiceEngine$JobHandler.handleMessage(JobServiceEngine.java:108)
        at android.os.Handler.dispatchMessage(Handler.java:105) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6541) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
2019-02-27 13:12:37.351 1697-1712/? I/ActivityManager: Showing crash dialog for package com.tbm.test_background_fetch u0

[BUG] [Android] Unable to debug headless background fetch events

Plugin version: 0.2.0
Platform: Android

Steps to reproduce the behavior:

  1. Run the example app in emulator from VS Code.

  2. Execute the following in Windows 10 command prompt cmd :
    adb shell am broadcast -a com.transistorsoft.flutter.backgroundfetch.backgroundfetchexample.event.BACKGROUND_FETCH

  3. Output :
    Broadcasting: Intent { act=com.transistorsoft.flutter.backgroundfetch.backgroundfetchexample.event.BACKGROUND_FETCH flg=0x400000 }
    Broadcast completed: result=0

  4. However the event is neither logged by the example app in the emulator nor can we debug the code.

Note: Simulating the following other event works as expected -
"adb shell cmd jobscheduler run -f com.transistorsoft.flutter.backgroundfetch.backgroundfetchexample 999"

Does not run automatically in background or after termination. Myapp's main.dart has minimal code as I prefer everything managed, hence missing something while implementing this plug in.

Since I have called the check() , it runs only for the first time.

flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.5.4-hotfix.2, on Microsoft Windows [Version 10.0.15063], locale en-IN)

[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[√] Android Studio (version 3.4)
[√] VS Code (version 1.36.0)
[√] VS Code, 64-bit edition (version 1.26.1)
[√] Connected device (1 available)

• No issues found!

This is my main.dart

void main() {
  FlutterError.onError = (FlutterErrorDetails details) async {
    if (AppGlobals.isInDebugMode) {
      FlutterError.dumpErrorToConsole(details);
    } else {
      Zone.current.handleUncaughtError(details.exception, details.stack);
    }
  };

  runZoned<Future<Null>>(() async {
    runApp(MyApp());
    BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
    
  }, onError: (error, stackTrace) async {
    await AppGlobals.reportError(error, stackTrace);
  });
}
//my material app home is as below
home: SplashScreen(),

//my splash screen code is as below

void backgroundFetchHeadlessTask() async {
  print('[BackgroundFetch] Headless event received.');

  SharedPreferences pref = await SharedPreferences.getInstance();
  List<DocumentMaster> _lstDocumentMaster = new List<DocumentMaster>();
  List<DocumentMaster> lstDocumentMasterTemp;
  _lstDocumentMaster.clear();
  if (pref.getString("Username") != null && pref.getString("Username") != "") {
    int userMasterId = int.parse(pref.getString("UserMasterId"));
    lstDocumentMasterTemp =
        await DocumentMasterParser().selectAllDocumentMasterCheck(userMasterId);
    _lstDocumentMaster.addAll(lstDocumentMasterTemp);
  }

  BackgroundFetch.finish();
}

 @override
  void initState() {
    super.initState();

    BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
    initPlatformState();

    _streamSubscription = new Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult result) {
      AppGlobals.isInternetAvailable().then((value) {
        _isInternet = value;
        if (value) {
          loadSplashScreen();
        } else {
          setState(() {});
        }
      });
    });
  }

//check() calls api 
 check() async {
    List<DocumentMaster> lstDocumentMasterTemp;

    _lstDocumentMaster.clear();
    SharedPreferences pref = await SharedPreferences.getInstance();
    if (pref.getString("Username") != null &&
        pref.getString("Username") != "") {
      int userMasterId = int.parse(pref.getString("UserMasterId"));
      lstDocumentMasterTemp = await DocumentMasterParser()
          .selectAllDocumentMasterCheck(userMasterId);

      _lstDocumentMaster.addAll(lstDocumentMasterTemp);
      // AppGlobals.showMessage(
      //     _lstDocumentMaster.length.toString(), MessageType.information);
      setState(() {});
    }
  }
//below are your functions after removing unwanted code in my case
Future<void> initPlatformState() async {
    // Load persisted fetch events from SharedPreferences

    // Configure BackgroundFetch.
    BackgroundFetch.configure(
            BackgroundFetchConfig(
                minimumFetchInterval: 15,
                stopOnTerminate: false,
                enableHeadless: true,
                forceReload: false),
            _onBackgroundFetch)
        .then((int status) {
     

      print('[BackgroundFetch] SUCCESS: $status');
      check();

      setState(() {
        //_status = status;
      });
    }).catchError((e) {
      print('[BackgroundFetch] ERROR: $e');
      setState(() {
        //_status = e;
      });
    });

    // Optionally query the current BackgroundFetch status.
    //int status = await BackgroundFetch.status;
    setState(() {
      //_status = status;
    });

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
  }

  void _onBackgroundFetch() async {
    //SharedPreferences prefs = await SharedPreferences.getInstance();

    // This is the fetch-event callback.
    print('[BackgroundFetch] Event received');
    check();
    setState(() {
      //_events.insert(0, new DateTime.now().toString());
    });
    // Persist fetch events in SharedPreferences
    //prefs.setString(EVENTS_KEY, jsonEncode(_events));

    // IMPORTANT:  You must signal completion of your fetch task or the OS can punish your app
    // for taking too long in the background.
    BackgroundFetch.finish();
  }

When i terminate my app, it's not working.

When i clear (i mean terminate) my all apps, package doesn't work.

Adsız

This package only working, if my application continues to run in the background.
And then 15 minutes after, i see some prints.

But it had to work, according to this explanation:

The Android plugin provides a Headless implementation allowing you to continue handling events even after app-termination.

What part of which I misunderstood?

[BUG] Unfortunately app stopped

There is no error shows. But when launched app It shows app has been stopped unfortunately.
Please have a look on these images
Screenshot_1
Screenshot_2

BuildContext in headless task

I would to launch a notification (using flutter_local_notifications extension) with a translated message in my headless task. The translation extension needs a BuildContext instance in order to work.
How could I resolve this?

Headless Task keeps stopping Application

Hi,
I followed the tutorial and the Android setup, but something weird is happening.
When i run the script "simulate-fetch" with the App opened, the plugin works ok, but if I close my App and run the script again, I get a dialog that "App keeps Stopping" and the background task do not run.
In the example provided it runs flawlessly.
I changed the AndroidManifest, created the Application.java and changed my main.dart according to the example, and even tried to completely copy the main.dart from the example. But still no success.
I am running the App on the Android Studio Emulator, but also tested on a smartphone (same result).

On the logcat, with the app opened i get this when I ran the script (I assume that is correct):

02-12 18:45:37.114 22134 22134 D TSBackgroundFetch: - Background Fetch event received
02-12 18:45:37.128 22134 22153 I flutter : [BackgroundFetch] Event received
02-12 18:45:37.151 22134 22134 D TSBackgroundFetch: - finish
02-12 18:45:37.151 22134 22134 D TSBackgroundFetch: - jobFinished

When the app is closed the task just stops with no error or anything:

02-12 18:41:42.236 21985 21985 D TSBackgroundFetch: - Background Fetch event received
02-12 18:41:42.247 21985 21985 D TSBackgroundFetch: - finish
02-12 18:41:42.247 21985 21985 D TSBackgroundFetch: - jobFinished
02-12 18:41:42.266 21985 21985 D TSBackgroundFetch: HeadlessJobService onStartJob
02-12 18:41:42.266 21985 21985 D TSBackgroundFetch: 💀 [HeadlessTask]

On the example app i get this:

02-12 18:42:24.917 21105 21105 D TSBackgroundFetch: - Background Fetch event received
02-12 18:42:24.919 21105 21105 D TSBackgroundFetch: - finish
02-12 18:42:24.919 21105 21105 D TSBackgroundFetch: - jobFinished
02-12 18:42:24.955 21105 21105 D TSBackgroundFetch: HeadlessJobService onStartJob
02-12 18:42:24.955 21105 21105 D TSBackgroundFetch: 💀 [HeadlessTask]
02-12 18:42:25.049 21105 21139 I flutter : [BackgroundFetch] Headless event received.
02-12 18:42:25.073 21105 21105 D TSBackgroundFetch: - finish
02-12 18:42:25.073 21105 21105 D TSBackgroundFetch: HeadlessJobService jobFinished

On my app, the code just stops at 💀 [HeadlessTask] ..

When I start my app I get this. The jobService var is correct or should be different according to my app settings? Its related to my problem?

02-12 18:43:31.460 22134 22134 D TSBackgroundFetch: - configure: {
02-12 18:43:31.460 22134 22134 D TSBackgroundFetch:   "minimumFetchInterval": 15,
02-12 18:43:31.460 22134 22134 D TSBackgroundFetch:   "stopOnTerminate": false,
02-12 18:43:31.460 22134 22134 D TSBackgroundFetch:   "startOnBoot": true,
02-12 18:43:31.460 22134 22134 D TSBackgroundFetch:   "forceReload": false,
02-12 18:43:31.460 22134 22134 D TSBackgroundFetch:   "jobService": "com.transistorsoft.flutter.backgroundfetch.HeadlessJobService"
02-12 18:43:31.460 22134 22134 D TSBackgroundFetch: }
02-12 18:43:31.460 22134 22134 D TSBackgroundFetch: - start
02-12 18:43:32.003 22134 22153 I flutter : [BackgroundFetch] SUCCESS: 2

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.