rekabhq / background_locator Goto Github PK
View Code? Open in Web Editor NEWA Flutter plugin for updating location in background.
License: MIT License
A Flutter plugin for updating location in background.
License: MIT License
I downloaded the project and tested it against the provided example app. I installed it in a real iOS device and started it. Started getting a few sparse location, went to background and the project didn't show any notification but still got a few updates. As soon as you kill the app it stops.
Other info:
Had to get some work done according to the iOS migration guide to get it to work with XCode 11
Tested with
iPhone XR - 13.4.1
Can we hide sticky notification?
Its annoy users and inspire them to delete the app. :)
Hi, make icon and name it ic_background
and add it to each folder midmap-hdpi
, hmdpi, xhdpi, etc... and works fine on debug. See:
Icon on notification dialog (debug)
Testing in an emulator or installing the app-debug.apk
on a device it works... but when install the app-release.apk
or a published version from play store, notification icon not works. The icon is almost hidden on device bar, and in notification continues to show a single square. See:
Icon on status bar on my device (release)
See, the icon is resumed to a single pixel.... almost invisible.
Icon on notification dialog on my device (release)
Just renders a square...
Test with three different icons, and get the same issue. On each test, use the versions according to the sizes:
How to pass parameter to callback function, eg: username
Trying to unregister location update in the callback but having the error "Unhandled Exception: MissingPluginException(No implementation found for method LocatorPlugin.unRegisterLocationUpdate on channel app.rekab/locator_plugin)"
Any help would be appreciated, thanks!
Hello.
Testing in Android, plugin works fine, but have an issue: When close app, the notification baloon still shows on device; but stop capturing. There is some extra config to do when close app ?
Settings:
BackgroundLocator.registerLocationUpdate(
(LocationDto locationDto) async {
print('location in dart: ${locationDto.toString()}');
final SendPort send = IsolateNameServer.lookupPortByName(_isolateName);
send?.send(locationDto);
},
androidNotificationCallback: notificationCallback() {
print('Background Location notificationCallback');
},
settings: LocationSettings(
notificationTitle: "Notification title",
notificationMsg: "Notification text",
wakeLockTime: 20,
autoStop: false,
interval: 600, // 10 minutes interval
),
);
In your app example, il you tap on stop without hitting start, the app crash.
The same crash happen if you try to unregister twice.
I would expect the app not to crash or it should be possible to test if the service is already registered
Hello.
It's working fine on Android. But on iOS it not asks for permission and of course, not works.
See app permission... not have location permissions:
Do i miss something???
Below my files as oriented in documentation:
AppDelegate.swift
import UIKit
import Flutter
import Firebase
import background_locator
import GoogleMaps
func registerPlugins(registry: FlutterPluginRegistry) -> () {
GeneratedPluginRegistrant.register(with: registry)
}
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
FirebaseApp.configure()
GeneratedPluginRegistrant.register(with: self)
// Background Location BEGIN
BackgroundLocatorPlugin.setPluginRegistrantCallback(registerPlugins)
// Background Location END
// Google MAPS BEGIN
GMSServices.provideAPIKey("-----------------------")
// Google MAPS END
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
Info.plist
<!-- Background Location Settings BEGIN -->
<key>
NSLocationAlwaysAndWhenInUseUsageDescription
</key>
<string>
Location Needed
</string>
<key>
NSLocationAlwaysUsageDescription
</key>
<string>
Location Needed
</string>
<key>
NSLocationWhenInUseUsageDescription
</key>
<string>
Location Needed
</string>
<key>
UIBackgroundModes
</key>
<array>
<string>
location
</string>
</array>
<!-- Background Location Settings BEGIN -->
Sorry this took long and is not using the pull request workaround @mehdok , but the risk is that I never submit it. :-/
As discussed in issue #52 please find attached the object-c setup page as a single page.
I also started an FAQ page with some questions I asked. I think in general it might be a good addition to the wiki and help to answer some of the issues that get opened regularly. Feel free to do whatever with it :-)
Expected results:
Stop background (if autostop: true), or stay in background (if autostop: false)
Actual results:
Exception
I/flutter (21853): Initialization done
I/OpenGLRenderer(21853): Initialized EGL, version 1.4
D/OpenGLRenderer(21853): Swap behavior 2
D/FlutterView(21853): Attaching to a FlutterEngine: io.flutter.embedding.engine.FlutterEngine@297a492
D/FlutterView(21853): Already attached to this engine. Doing nothing.
I/Choreographer(21853): Skipped 30 frames! The application may be doing too much work on its main thread.
D/vndksupport(21853): Loading /vendor/lib/hw/[email protected] from current namespace instead of sphal namespace.
D/vndksupport(21853): Loading /vendor/lib/hw/gralloc.msm8937.so from current namespace instead of sphal namespace.
E/AccessibilityBridge(21853): VirtualView node must not be the root node.
I/flutter (21853): location in dart: LocationDto{latitude: -34.6524895, longitude: -58.5683421, accuracy: 15.871999740600586, altitude: 44.89999771118164, speed: 0.0, speedAccuracy: 0.0, heading: 0.0}
E/AccessibilityBridge(21853): VirtualView node must not be the root node.
E/AccessibilityBridge(21853): VirtualView node must not be the root node.
D/FlutterView(21853): Detaching from a FlutterEngine: io.flutter.embedding.engine.FlutterEngine@297a492
D/FlutterActivityAndFragmentDelegate(21853): Detaching FlutterEngine from the Activity that owns this Fragment.
D/FlutterEngine(21853): Destroying.
D/FlutterEnginePluginRegistry(21853): Destroying.
D/AndroidRuntime(21853): Shutting down VM
E/AndroidRuntime(21853): FATAL EXCEPTION: main
E/AndroidRuntime(21853): Process: rekab.app.background_locator_example, PID: 21853
E/AndroidRuntime(21853): java.lang.RuntimeException: Unable to destroy activity {rekab.app.background_locator_example/rekab.app.background_locator_example.MainActivity}: kotlin.UninitializedPropertyAccessException: lateinit property locatorClient has not been initialized
E/AndroidRuntime(21853): at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:4497)
E/AndroidRuntime(21853): at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:4515)
E/AndroidRuntime(21853): at android.app.ActivityThread.-wrap5(Unknown Source:0)
E/AndroidRuntime(21853): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1690)
E/AndroidRuntime(21853): at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime(21853): at android.os.Looper.loop(Looper.java:164)
E/AndroidRuntime(21853): at android.app.ActivityThread.main(ActivityThread.java:6626)
E/AndroidRuntime(21853): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(21853): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
E/AndroidRuntime(21853): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
E/AndroidRuntime(21853): Caused by: kotlin.UninitializedPropertyAccessException: lateinit property locatorClient has not been initialized
E/AndroidRuntime(21853): at rekab.app.background_locator.BackgroundLocatorPlugin.onDetachedFromEngine(BackgroundLocatorPlugin.kt:212)
E/AndroidRuntime(21853): at io.flutter.embedding.engine.FlutterEnginePluginRegistry.remove(FlutterEnginePluginRegistry.java:244)
E/AndroidRuntime(21853): at io.flutter.embedding.engine.FlutterEnginePluginRegistry.remove(FlutterEnginePluginRegistry.java:252)
E/AndroidRuntime(21853): at io.flutter.embedding.engine.FlutterEnginePluginRegistry.removeAll(FlutterEnginePluginRegistry.java:260)
E/AndroidRuntime(21853): at io.flutter.embedding.engine.FlutterEnginePluginRegistry.destroy(FlutterEnginePluginRegistry.java:116)
E/AndroidRuntime(21853): at io.flutter.embedding.engine.FlutterEngine.destroy(FlutterEngine.java:267)
E/AndroidRuntime(21853): at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onDetach(FlutterActivityAndFragmentDelegate.java:468)
E/AndroidRuntime(21853): at io.flutter.embedding.android.FlutterActivity.onDestroy(FlutterActivity.java:588)
E/AndroidRuntime(21853): at android.app.Activity.performDestroy(Activity.java:7241)
E/AndroidRuntime(21853): at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1271)
E/AndroidRuntime(21853): at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:4484)
E/AndroidRuntime(21853): ... 9 more
[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.17763.1039], locale es-419)
• Flutter version 1.12.13+hotfix.8 at C:\develop\flutter
• Framework revision 0b8abb4724 (4 weeks ago), 2020-02-11 11:44:36 -0800
• Engine revision e1e6ced81d
• Dart version 2.7.0
[√] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
• Android SDK at c:\develop\android\sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-29, build-tools 29.0.3
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)
• All Android licenses accepted.
[√] Android Studio (version 3.6)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin version 44.0.2
• Dart plugin version 192.7761
• Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)
[√] VS Code (version 1.43.0)
• VS Code at C:\Users\gibarra\AppData\Local\Programs\Microsoft VS Code
• Flutter extension version 3.8.1
[√] Connected device (2 available)
• Moto G 5 • ZY32226G73 • android-arm • Android 8.1.0 (API 27)
• Moto G 5 • 192.168.0.5:5555 • android-arm • Android 8.1.0 (API 27)
• No issues found!
I want to call api on location change. I want to attach JWT_TOKEN which is stored in shared preferences. I am facing.
E/flutter (10000): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
Expected results:
Notification of background work
Actual results:
Exception
[ +2 ms] � To hot reload changes while running, press "r". To hot restart (and rebuild state), press "R".
[ +1 ms] An Observatory debugger and profiler on Moto G 5 is available at: http://127.0.0.1:60354/iFpOkYs-vi4=/
[ ] For a more detailed help message, press "h". To detach, press "d"; to quit, press "q".
[+6050 ms] D/AndroidRuntime( 6720): Shutting down VM
[ +164 ms] E/AndroidRuntime( 6720): FATAL EXCEPTION: main
[ +1 ms] E/AndroidRuntime( 6720): Process: rekab.app.background_locator_example, PID: 6720
[ ] E/AndroidRuntime( 6720): java.lang.RuntimeException: Unable to create service rekab.app.background_locator.LocatorService: java.lang.NullPointerException: Attempt to invoke
virtual method 'android.os.Looper android.app.Activity.getMainLooper()' on a null object reference
[ ] E/AndroidRuntime( 6720): at android.app.ActivityThread.handleCreateService(ActivityThread.java:3440)
[ ] E/AndroidRuntime( 6720): at android.app.ActivityThread.-wrap4(Unknown Source:0)
[ ] E/AndroidRuntime( 6720): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1721)
[ ] E/AndroidRuntime( 6720): at android.os.Handler.dispatchMessage(Handler.java:106)
[ ] E/AndroidRuntime( 6720): at android.os.Looper.loop(Looper.java:164)
[ ] E/AndroidRuntime( 6720): at android.app.ActivityThread.main(ActivityThread.java:6626)
[ ] E/AndroidRuntime( 6720): at java.lang.reflect.Method.invoke(Native Method)
[ ] E/AndroidRuntime( 6720): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
[ ] E/AndroidRuntime( 6720): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
[ ] E/AndroidRuntime( 6720): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.app.Activity.getMainLooper()' on a null object
reference
[ ] E/AndroidRuntime( 6720): at com.google.android.gms.common.api.GoogleApi.<init>(Unknown Source:50)
[ ] E/AndroidRuntime( 6720): at com.google.android.gms.location.FusedLocationProviderClient.<init>(Unknown Source:8)
[ ] E/AndroidRuntime( 6720): at com.google.android.gms.location.LocationServices.getFusedLocationProviderClient(Unknown Source:2)
[ ] E/AndroidRuntime( 6720): at com.lyokone.location.FlutterLocation.setActivity(FlutterLocation.java:103)
[ ] E/AndroidRuntime( 6720): at com.lyokone.location.LocationPlugin.registerWith(LocationPlugin.java:36)
[ ] E/AndroidRuntime( 6720): at io.flutter.plugins.GeneratedPluginRegistrant.registerWith(GeneratedPluginRegistrant.java:17)
[ +3 ms] E/AndroidRuntime( 6720): at rekab.app.background_locator_example.Application.registerWith(Application.kt:15)
[ ] E/AndroidRuntime( 6720): at rekab.app.background_locator.LocatorService.startLocatorService(LocatorService.kt:80)
[ ] E/AndroidRuntime( 6720): at rekab.app.background_locator.LocatorService.onCreate(LocatorService.kt:61)
[ ] E/AndroidRuntime( 6720): at android.app.ActivityThread.handleCreateService(ActivityThread.java:3430)
[ ] E/AndroidRuntime( 6720): ... 8 more
[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.17763.1039], locale es-419)
• Flutter version 1.12.13+hotfix.8 at C:\develop\flutter
• Framework revision 0b8abb4724 (3 weeks ago), 2020-02-11 11:44:36 -0800
• Engine revision e1e6ced81d
• Dart version 2.7.0
[√] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
• Android SDK at c:\develop\android\sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-29, build-tools 29.0.3
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b03)
• All Android licenses accepted.
[√] Android Studio (version 3.5)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin version 42.1.1
• Dart plugin version 191.8593
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b03)
[√] VS Code (version 1.42.1)
• VS Code at C:\Users\gibarra\AppData\Local\Programs\Microsoft VS Code
• Flutter extension version 3.8.1
[√] Connected device (1 available)
• Moto G 5 • 192.168.0.5:5555 • android-arm • Android 8.1.0 (API 27)
• No issues found!
I am posting this here since the error is connected to the usage with your package. I know the error shows another though:
I wanted to integrate this plugin to an existing, but a bit dated, project. So I followed everything on the installation and setup but encountered too many errors.
I decided to test the example on this github and everything worked well as expected.
I couldn't find the problem so I decided to start a fresh project.
I did and I copied the main and file_manager files from the example project.
The app was now starting and asking for the permission to use the location of the device.
But when it tried to get the location and save to the log file I got:
(No implementation found for method getTemporaryDirectory on channel plugins.flutter.io/path_provider)
flutter clean
or flutter pub cache repair
as well as restarting Android Studio or something.I've prepared an example project here: https://github.com/Flavsditz/test_plugin
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, v1.12.13+hotfix.9, on Linux, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[✓] Android Studio (version 3.6)
[!] IntelliJ IDEA Ultimate Edition (version 2019.3)
✗ Flutter plugin not installed; this adds Flutter specific functionality.
✗ Dart plugin not installed; this adds Dart specific functionality.
[✓] VS Code (version 1.44.1)
[✓] Connected device (1 available)
I would love to make this plugin work since it seems to be exactly what I need. So any help would be much appreciated.
Thank you for developing this!
Hi I have some issue with the plugins not stopping the Isolate, I'm creating a new file with a new name every time in a specific directory before launching the plugins and the plugins retrieve this file by listing every files in this directory (I store the date and a string in the name to not creating a special db for this), the file is stored in static File _currentFile;
at the top of the class to not list the directory every callback. When its finished I stop the plugin using
BackgroundLocator.unRegisterLocationUpdate();
IsolateNameServer.removePortNameMapping(_isolateName);
I copy the file and delete it in the directory.
When I recreate another file and re-launch the plugin it will see that _currentFile
is not null and write to it even though its not the file I want.
I tried the example and its the same, by clicking stop I still see the plugin's thread running in VScode
Hello,
For a project I need to restart the background isolate from himself with new parameters.
I was trying to manually register the plugin in Application.kt
but I am having build error : Application.kt: (31, 37): Unresolved reference: registerWith
All others plugins are well registered and working in background.
package test.test.test
import rekab.app.background_locator.LocatorService
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import com.tekartik.sqflite.SqflitePlugin
import io.flutter.plugins.firebase.core.FirebaseCorePlugin
import io.flutter.plugins.firebase.database.FirebaseDatabasePlugin
import io.flutter.view.FlutterMain
import rekab.app.background_locator.BackgroundLocatorPlugin
class Application : FlutterApplication(), PluginRegistrantCallback {
override fun onCreate() {
super.onCreate()
LocatorService.setPluginRegistrant(this)
FlutterMain.startInitialization(this)
}
override fun registerWith(registry: PluginRegistry?) {
if (!registry!!.hasPlugin("com.tekartik.sqflite")) {
SqflitePlugin.registerWith(registry.registrarFor("com.tekartik.sqflite"))
}
if (!registry.hasPlugin("io.flutter.plugins.firebase.core")) {
FirebaseCorePlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebase.core"))
}
if (!registry.hasPlugin("io.flutter.plugins.firebase.database")) {
FirebaseDatabasePlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebase.database"))
}
if (!registry.hasPlugin("rekab.app.background_locator")) {
BackgroundLocatorPlugin.registerWith(registry.registrarFor("rekab.app.background_locator"))
}
}
}
When I didn't add the background plugin I am having run error : Unhandled Exception: MissingPluginException(No implementation found for method LocatorPlugin.unRegisterLocationUpdate on channel app.rekab/locator_plugin)
which happen here BackgroundLocator.unRegisterLocationUpdate();
Thanks
Hi, I am trying to setup the lib to be used in IOS and I am probably doing something wrong.
I followed the wiki page but inside my swift file it can't load the module:
....../ios/Runner/AppDelegate.swift:3:8: error: no such module 'background_locator'
import background_locator
When I started this, I didn't have a swift file, but Appdelegate.m and .h files and a main.
Any idea what I might be missing. Thanks a ton. Looking forward to test this library.
I have an app which is working fine on Android but it is calling the callback functions hundreds of times at each second.
How could I prevent such a behaviour?
Shoud I update the UI in order to dismiss the trigger event?
I'm using this code for setup:
BackgroundLocator.registerLocationUpdate(
LocationBackground.callback,
androidNotificationCallback: LocationBackground.notificationCallback,
settings: LocationSettings(
notificationTitle: "App",
notificationMsg: "Tracking location",
notificationIcon: 'ic_background',
wakeLockTime: 20,
autoStop: false,
interval: 60 * 15,
),
);
Hi, I'm trying to integrate this library with my flutter project but facing this issue:
(No implementation found for method LocatorPlugin.initializeService on channel app.rekab/locator_plugin)
I've setup the code for Android as expected
Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<application
tools:replace="android:label"
android:name=".Application"
android:icon="@mipmap/ic_launcher"
android:usesCleartextTraffic="true"
android:label="BeSafeSY">
<activity
android:name=".EmbeddingV1Activity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
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). -->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
</activity>
<receiver android:name="rekab.app.background_locator.LocatorBroadcastReceiver"
android:enabled="true"
android:exported="true"/>
<service android:name="rekab.app.background_locator.LocatorService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="true"/>
<service android:name="rekab.app.background_locator.IsolateHolderService"
android:permission="android.permission.FOREGROUND_SERVICE"
android:exported="true"
/>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
Application.kt:
class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
override fun onCreate() {
super.onCreate()
LocatorService.setPluginRegistrant(this)
}
override fun registerWith(registry: PluginRegistry?) {
SharedPreferencesPlugin.registerWith(registry!!.registrarFor("io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin"))
FirebaseMessagingPlugin.registerWith(registry!!.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
}
}
app.dart:
ReceivePort port = ReceivePort();
DateTime lastTimeLocation;
Location lastLocation;
static final _isolateName = 'LocatorIsolate';
@override
void initState() {
if (IsolateNameServer.lookupPortByName(_isolateName) != null) {
IsolateNameServer.removePortNameMapping(_isolateName);
}
IsolateNameServer.registerPortWithName(port.sendPort, _isolateName);
port.listen(
(dynamic data) async {
await updateUI(data);
},
);
initPlatformState();
super.initState();
}
Future<void> updateUI(LocationDto data) async {
setState(() {
lastTimeLocation = DateTime.now();
});
}
Future<void> initPlatformState() async {
print('Initializing...');
await BackgroundLocator.initialize();
print('Initialization done');
_startLocator();
}
static void callback(LocationDto locationDto) async {
print('location in dart: ${locationDto.toString()}');
print('test long ${locationDto.longitude}, ${locationDto.latitude}');
final SendPort send = IsolateNameServer.lookupPortByName(_isolateName);
send?.send(locationDto);
}
getCurrentLocation() {
BackgroundLocator.registerLocationUpdate((LocationDto location) {});
}
void _startLocator() {
BackgroundLocator.registerLocationUpdate(
callback,
);
}
Any ideas?
Hello.
I'm using background_locator to store locations in background without sendint it to port listened on UI... see here: Issue 30 - comment:610746281 and the result is amazing! But the problem is the excessively high battery consumption!!!
Users are complaining that background locator
is consuming about 90% of battery and that android itself is warning them to force the application to stop.
I configured background_locator
in a keep alive way, even when user closes the app and just to store locations in background in Shared Preferences... and to capture locations every 5 minutes, and each 30 minutes (about 5 or 6 captures), sent these results to my server. The idea is just to store user location for statistics.
BackgroundLocator.registerLocationUpdate(
LocationBackground.callback,
androidNotificationCallback: LocationBackground.notificationCallback,
settings: LocationSettings(
notificationTitle: "My App",
notificationMsg: "My App Title",
notificationIcon: 'ic_background',
wakeLockTime: 20,
autoStop: false,
interval: 60 * 5,
),
);
Well, my question is about battery: There is a way to optimize this consumption? I thought that this would only generate some consumption when it captures, but apparently it drains more battery because the GPS is active all the time.
If i change the captures from 5 to15 minutes interval, it will reduce this behavior ? Will reduce at least 2/3 of captures processing.
Hello,
is there a way to update the notification message?
Background: I want to track the distance someone has moved and it would be great, if I could show the current distance value in the notification.
Greetings
scotty86
Hello im having a problem when receiving the location changes even when app is in foreground, when i leave LocationAccuracy parameter empty for it to use the default, the callback works fine
settings: LocationSettings(
notificationTitle: "Start Location Tracking example",
notificationMsg: "Track location in background exapmle",
distanceFilter: 10.0,
wakeLockTime: 60,
autoStop: false,
interval: 5
),
When i use it with LocationAccuracy.HIGH callback only executes the first time when its initialized
settings: LocationSettings(
accuracy: LocationAccuracy.HIGH,
notificationTitle: "Start Location Tracking example",
notificationMsg: "Track location in background exapmle",
distanceFilter: 10.0,
wakeLockTime: 60,
autoStop: false,
interval: 5
),
Im testing on android emulator
Did you plan to release this plugin with a production ready status ?
It would be very useful
Just wondering is there a way to turn off notification?
In notification Android configure function callback. When on click notification open app and run callback (NavigationRoute example)
In the beta version, on start app request permissions.
In version 1.0.0 + 1 does not request permissions.
This is correct? In that case you have to change the "example" using any library (https://pub.dev/packages/permission_handler for example) to manage it.
To make it go,
Run app the first time
Click "start" button.
Show error "[ERROR: flutter / lib / ui / ui_dart_state.cc (157)] Unhandled Exception: PlatformException ('registerLocator' requires the ACCESS_FINE_LOCATION permission., Null, null)".
Leave app, and go to app's information, and give it permissions manually.
Open app again and it work ok.
Isolate port stops listening as soon as the app process is destroyed.
So logs are not written when the app is not running. while the background locator is working fine. Should we write logs in the callback or keep it in on port listen function
Good evening,
I'm testing my app on an Android Q devices, and when the app goes to background, send only few datas. You have any suggest??? Thanks for the attention
I implemented the plugin and used the example. All the settings for Android and for iOS were implemented as written in the docs. In Android it works great but in iOS the callback function is never triggered. Any idea?
Hi,
I need to get the vertical speed during the callback.
For this, I need to have different altitudes at 2 different times to calculate the speed.
Is it possible to get a new location update IN the callback method ? I tried using this plugin to get a location update : https://github.com/Lyokone/flutterlocation/
But I can't register it, I get this error while starting the service :
E/AndroidRuntime(32274): java.lang.RuntimeException: Unable to create service rekab.app.background_locator.LocatorService: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.app.Activity.getMainLooper()' on a null object reference E/AndroidRuntime(32274): at android.app.ActivityThread.handleCreateService(ActivityThread.java:4169) E/AndroidRuntime(32274): at android.app.ActivityThread.access$2400(ActivityThread.java:273) E/AndroidRuntime(32274): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2055) E/AndroidRuntime(32274): at android.os.Handler.dispatchMessage(Handler.java:112) E/AndroidRuntime(32274): at android.os.Looper.loop(Looper.java:216) E/AndroidRuntime(32274): at android.app.ActivityThread.main(ActivityThread.java:7625) E/AndroidRuntime(32274): at java.lang.reflect.Method.invoke(Native Method) E/AndroidRuntime(32274): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524) E/AndroidRuntime(32274): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987) E/AndroidRuntime(32274): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.app.Activity.getMainLooper()' on a null object reference E/AndroidRuntime(32274): at com.google.android.gms.common.api.GoogleApi.<init>(Unknown Source:50) E/AndroidRuntime(32274): at com.google.android.gms.location.FusedLocationProviderClient.<init>(Unknown Source:8) E/AndroidRuntime(32274): at com.google.android.gms.location.LocationServices.getFusedLocationProviderClient(Unknown Source:2) E/AndroidRuntime(32274): at com.lyokone.location.FlutterLocation.setActivity(FlutterLocation.java:106) E/AndroidRuntime(32274): at com.lyokone.location.LocationPlugin.registerWith(LocationPlugin.java:35) E/AndroidRuntime(32274): at com.ludesert.autologbook.Application.registerWith(Application.kt:23) E/AndroidRuntime(32274): at rekab.app.background_locator.LocatorService.startLocatorService(LocatorService.kt:90) E/AndroidRuntime(32274): at rekab.app.background_locator.LocatorService.onCreate(LocatorService.kt:63) E/AndroidRuntime(32274): at android.app.ActivityThread.handleCreateService(ActivityThread.java:4150) E/AndroidRuntime(32274): ... 8 more I/Process (32274): Sending signal. PID: 32274 SIG: 9 Lost connection to device.
Any idea ? Thanks
This crash is reported hundred times on firebase crashlytics. The app is working fine but some time is getting crashed.
Does anyone face the same issue? or any solution?
FYI I've followed all steps suggested by wiki.
One more issue -
The IsolateHolderService
foreground service getting destroy in Chinese custom ROM devices like OnePlus, Xiaomi, Vivo, Huawei, etc. when the app gets removed from recent.
Stack trace
Fatal Exception: java.lang.RuntimeException: Unable to start service rekab.app.background_locator.IsolateHolderService@e7be9cd with null: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter intent at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3821) at android.app.ActivityThread.access$1800(ActivityThread.java:207) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1779) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6863) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter intent at rekab.app.background_locator.IsolateHolderService.onStartCommand(:2) at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3802) at android.app.ActivityThread.access$1800(ActivityThread.java:207) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1779) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6863) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
I have a start and stop button in my app to register or unregister the background service. It works like a charm even when the app is killed (that's the intent of the plug-in), but for some reasons, after 10-15 min the notification disappears.
Is the service sticky? Because I guess it should start again everytime it gets killed, right?
I'm using a Huawei honor 10.
androidNotificationCallback gets called when clicking notifications that are shown by other flutter plugins. A payload/id (String) should be passed to androidNotificationCallback, so we are able to tell whether this was triggered as a result of clicking this plugin's foreground service notification or some other unrelated notification.
How to reproduce?
Is distance filter triggers the callback on change of location?
I am not getting any callback, when I changes the location in the map.
I have set the distance filter to 1.
Many crashes are being reported on Google Play Console after updating my app to use version 1.1.3+1 of this plugin (I had no issues until version 1.1.2+2), so it could be caused by the newly added feature #47, which I'm using.
java.lang.RuntimeException:
at android.app.ActivityThread.handleCreateService (ActivityThread.java:3761)
at android.app.ActivityThread.access$1400 (ActivityThread.java:236)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1800)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:214)
at android.app.ActivityThread.main (ActivityThread.java:7032)
at java.lang.reflect.Method.invoke (Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:965)
Caused by: java.lang.IllegalStateException:
at rekab.app.background_locator.LocatorService.a (LocatorService.java:39)
at rekab.app.background_locator.LocatorService.onCreate (LocatorService.java:3)
at android.app.ActivityThread.handleCreateService (ActivityThread.java:3749)
at android.app.ActivityThread.access$1400 (ActivityThread.java:236)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1800)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:214)
at android.app.ActivityThread.main (ActivityThread.java:7032)
at java.lang.reflect.Method.invoke (Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:965)
Any suggestion for how to display an alert or rebuild part of the UI from androidNotificationCallback?
I tried SchedulerBinding.instance.addPostFrameCallback()
and WidgetsBinding.instance.addPostFrameCallback()
with no success in getting that working.
There is a way to use an icon for notification to replace the default square icon?
I have a login, when user logout, I unregister locator, send to login, I when I login again inmediately, crash with that Duplicate plugin key: BackgroundLocatorPlugin, iOS. Any idea?
I Tried to implement cloud_firestore
plugin in the callback function
Application.kt
import rekab.app.background_locator.LocatorService
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import io.flutter.plugins.firebaseauth.FirebaseAuthPlugin
import io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin
class Application : FlutterApplication(), PluginRegistrantCallback {
override fun onCreate() {
super.onCreate()
LocatorService.setPluginRegistrant(this)
}
override fun registerWith(registry: PluginRegistry?) {
if (!registry!!.hasPlugin("io.flutter.plugins.firebaseauth")) {
FirebaseAuthPlugin.registerWith(registry!!.registrarFor("io.flutter.plugins.firebaseauth"))
}
if (!registry!!.hasPlugin("io.flutter.plugins.firebase.cloudfirestore")) {
CloudFirestorePlugin.registerWith(registry!!.registrarFor("io.flutter.plugins.firebase.cloudfirestore"))
}
}
}
callback function
static void callback(LocationDto location to) async {
fauth.FirebaseUser user = await fauth.FirebaseAuth.instance.currentUser();
if (user != null) {
await firestore.collection("users").document(user.uid).setData(
{
'coordinates': {
latitude: locationDto.latitude,
longitude: locationDto.longitude
},
'lastActive': new DateTime.now()
},
merge: true);
}
final SendPort send = IsolateNameServer.lookupPortByName(_isolateName);
send?.send(locationDto);
}
On terminating the app I get an error
W/FlutterJNI(11336): Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not send. Channel: plugins.flutter.io/cloud_firestore. Response ID: 0
Is there any way to fix this
Flutter doctor
[✓] Flutter (Channel stable, v1.12.13+hotfix.8, on Mac OS X 10.15.4 19E266, locale en-GB)
• Flutter version 1.12.13+hotfix.8 at /Users/viveknimkarde/flutter
• Framework revision 0b8abb4724 (7 weeks ago), 2020-02-11 11:44:36 -0800
• Engine revision e1e6ced81d
• Dart version 2.7.0
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.0-rc1)
• Android SDK at /Users/viveknimkarde/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-29, build-tools 29.0.0-rc1
• ANDROID_HOME = /Users/viveknimkarde/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)
• All Android licenses accepted.
[✓] Xcode - develop for iOS and macOS (Xcode 11.4)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 11.4, Build version 11E146
• CocoaPods version 1.9.1
[✓] Android Studio (version 3.5)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin version 38.2.3
• Dart plugin version 191.8423
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
Pubscpec versions
cloud_firestore: ^0.13.4+2
firebase_auth_ui: ^1.0.1
firebase_auth: ^0.15.5+3
background_locator: ^1.1.2+1`
Hi there,
I have just came across this plugin and it seems quite promising in its specific niche. I cannot however find any documentation - for instance I would like to know all LocationSettings
parameters meaning for start.
First of all very nice tool - working good.
In Android there are times where no location update is handled - sometimes 10minutes nothing...
Can this happen when the device is not moved?
Tested it with the example in this library
Happens on real devices (Android 8,9,10)
Hello,
I managed to make the package to work.
However, when I close the app on android (not just put in background), the location tracking is still active, draining the battery.
How to automatically stop the tracking in this case?
By default, the plugin is running for 1 hour.
It would be great if this time can be parametric and reset during the execution of the program.
Hi,
is it possible to start the service or stop when a particular bluetooth is connected/disconnected.
This could open the automatic registration of tracks.
Thanks for your beautiful plugin
I want to check if the service is running or not on app startup. Is there any exported function for checking that?
There is a way to define a large interval betwen captures in IOS?
For Android is fine with interval config parameter, but in ios not.
LocationSettings options for notificationIcon not working when we change the icon, it's not visible as it should, just white rectangle when the app in production build flutter build apk --split-per-abi
but it working when in development.
the icon image was in mipmap(s) diretory with name tracking_enable.png
settings: LocationSettings(
notificationIcon: 'tracking_enable',
....
)
Tested With
Google Pixel 2 XL Android 10
Flutter 1.12.13+hotfix.9
In documentation it says that androidNotificationCallback
is optional parameter but the plugin crashes if androidNotificationCallback=null
.
Also, please use correct semver versioning. You made a breaking change but increased minor version instead of major version. If minor version is changed the changes should be backward compatible.
Hello.
There is a way to config locator to starts when device is restarted ?
My app is to count hours user is in a specific place, so; when mobile is restarted, need to continue capture locations, even if user forgot to open the app to start the captures.
I have some questions that I think might interest others. I would be happy to gather the answers and make them a documentation page in the wiki. Not sure if the issue format is the best for this, but I will try:
On Android I am able to intercept the back button and unregister properly the location listener. What is usually done in IOS? Is there a difference between switching off the screen and pushing the home button?
In an app that allows background logging you have to explicitly make a difference between switching it off and just sending it to back and work on something else in the meanwhile.
In the current situation I initialize the logging but then am not sure if no point is coming because the GPS is off or because it doesn't have a fix. Is there a way to tell?
Is there a way to send notification updates. It is almost a pity to have the LocationSettings be static at first startup. It would be great to be able to send updates, let the user know the current accuracy and if the gps has a fix or when not.
Do I have to go through the whole
if (IsolateNameServer.lookupPortByName(_isolateName) != null) {
IsolateNameServer.removePortNameMapping(_isolateName);
}
await GPS.BackgroundLocator.unRegisterLocationUpdate();
and restart from scratch? It is not much work, just wanted to know if this is the proper way.
Thanks for any insight.
GPL is a very restrictive license, which makes the plugin unsuitable for most uses.
I suggest changing to MIT.
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.