transistorsoft / flutter_background_fetch Goto Github PK
View Code? Open in Web Editor NEWPeriodic callbacks in the background for both IOS and Android. Includes Android Headless mechanism
License: MIT License
Periodic callbacks in the background for both IOS and Android. Includes Android Headless mechanism
License: MIT License
Your Environment
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!
To Reproduce
Steps to reproduce the behavior:
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.
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();
}
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!
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!
Your Environment
flutter info
, flutter doctor
):To Reproduce
Steps to reproduce the behavior:
Debug logs
Additional context
Add any other context about the problem here.
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?
Your Environment
I tried to enable headless mode but the import inside my Application.kt fails. It cannot resolve com.transistorsoft.flutter.backgroundfetch.BackgroundFetchPlugin even though the plugin is installed correctly and is working in my dart code.
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!
The plugin is almost ready for release to those watching this repo.
Your Environment
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!
To Reproduce
Follow Headless Mechanism Steps
Steps to reproduce the behavior:
Application.kt
fileAndroidManifest.xml
- I think this is were issue lays, since there is already android:name
tag with value io.flutter.app.FlutterApplication
Finished with error: Gradle task assembleProductionDebug failed with exit code 1
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
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)
Your Environment
flutter info
, flutter doctor
): Doctor summary (to see all details, run flutter doctor -v):! Doctor found issues in 2 categories.
To Reproduce
Steps to reproduce the behavior:
Hi,
why is the minimum fetch time 15 min?
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.
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)
Your Environment
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
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
Your Environment
flutter info
, flutter doctor
): $ flutter doctor[√] 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!
To Reproduce
Steps to reproduce the behavior:
Debug logs
$ adb logcat
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.
Your Environment
flutter info
, flutter doctor
): No issuesDebug 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.
Your Environment
flutter info
, flutter doctor
):To Reproduce
Steps to reproduce the behavior:
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);
}
}
Your Environment
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!
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.
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 !
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)
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:
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.
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:
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;
}
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.
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:
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();
}
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.
I want to run background jobs on two different frequencies - once every 15 mins and once every day. Is it possible to configure two different background fetch services?
Your Environment
To Reproduce
Steps to reproduce the behavior:
image_picker: 0.4.12+1
as a dependencyadb shell cmd jobscheduler run -f com.transistorsoft.flutter.backgroundfetch.backgroundfetchexample 999
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? :)
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
I've just found out performFetchWithCompletionHandler will be deprecated from iOS 13.
I'm not coming from iOS world and not sure if it will affact the app behavior.
Just curious to know your thoughts on it.
Hi, you may want to change
import com.transistorsoft.flutter.backgroundgeolocation.BackgroundFetchPlugin;
with
import com.transistorsoft.flutter.backgroundfetch.BackgroundFetchPlugin;
in the android setup for headless mechanism wiki page.
I need to run a task in background and fetch every 5 minutes once time. So when I set minimum
fetch interval 5 minutes. Is this task working?
Your Environment
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)
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.
I configured your plugin on Android Nougat. It fired once at the 11th minute from app startup but after that it's not firing any fetch event. Any tips on what I might be missing?
I always see this text: "Running Gradle task 'assembleDebug'..." and it is never end.
background_fetch
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>
In the backgroundFetchHeadlessTask method, I need to access the showNotification() method, which I created inside the _MyAppState class of my Application. The showNotification method implements the flutter_local_notifications plugin functionality and hence cannot be made static.
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.
Environment
ubuntu 18.04
openjdk version "1.8.0_222"
/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
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 .
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?
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.
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?
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
Plugin version: 0.2.0
Platform: Android
Steps to reproduce the behavior:
Run the example app in emulator from VS Code.
Execute the following in Windows 10 command prompt cmd :
adb shell am broadcast -a com.transistorsoft.flutter.backgroundfetch.backgroundfetchexample.event.BACKGROUND_FETCH
Output :
Broadcasting: Intent { act=com.transistorsoft.flutter.backgroundfetch.backgroundfetchexample.event.BACKGROUND_FETCH flg=0x400000 }
Broadcast completed: result=0
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"
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 clear (i mean terminate) my all apps, package doesn't work.
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?
Why do we need two functions : configure and registerHeadlessTask?
I known registerHeadlessTask
only works on Android, how aboutconfigure
?
if configure
works on Android too, two callback functions will run.
I do by following the example code.
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?
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.