GithubHelp home page GithubHelp logo

yukams / background_locator_fixed Goto Github PK

View Code? Open in Web Editor NEW

This project forked from rekabhq/background_locator

48.0 48.0 85.0 1.63 MB

A Flutter plugin for updating location in background.

License: MIT License

Kotlin 49.26% Ruby 1.78% Swift 0.85% Objective-C 21.48% Dart 26.63%

background_locator_fixed's People

Contributors

alekseifm avatar argo1 avatar atsumo avatar caiobraga avatar dacianf avatar dj-denis avatar dmacan23 avatar fnicastri avatar gomazaba avatar gpibarra avatar hieudz avatar martofeld avatar mehdok avatar mohammedx6 avatar quewen08 avatar rahuldange09 avatar rajeshbdabhi avatar resfandiari avatar ric17101 avatar romanjos avatar saeedmasoumi avatar sanak avatar sandysultan avatar sjoudi avatar splangi avatar srmncnk avatar stxsudhi avatar tulioccalazans avatar williambarreiro avatar yukams avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

background_locator_fixed's Issues

[Android] BackgroundLocator.unRegisterLocationUpdate seems to not stop the locator isolate

I'm working on this issue right now, I feel like it's not working, if anyone is succeeding while using it, I'd like to know. Or if you think it works as expected and I misunderstood the intent.

Excpected behavior : BackgroundLocator.unRegisterLocationUpdate() should call the native stopIsolateService() in BackgroundLocatorPlugin() and I should be able to relaunch the isolate by doing BackgroundLocator.initialize() and BackgroundLocator.registerLocationUpdate()

EDIT : My problem is when the app is crashing because of a user changing the permissions for the app. I would like to relaunch the locator when the user comes back to the app but it seems to be buggy. I reproduced it with the example too. I'm going to work on that

Crash loop on iPhone at app start (EXC_BAD_ACCESS - KERN_INVALID_ADDRESS)

Hi, thank you for fixing the original repo and creating this fork.

I'm having issues with this plugin though:
The app works fine at first (when I run flutter run or just run the app through Xcode), but if I terminate the app and start it again, it crashes immediately, and it keeps doing that until I reinstall the app. I looked at the device logs and if I'm understanding it correctly, it's coming from one of the lines we add in the Setup:

Notes:

  • This only happens on a real iphone, doesn't reproduce in simulator
  • This reproduces with the example project of this repo as well
  • It does not crash in release build, only in debug build

I'm new to mobile app developing, and google'd everything I could, yet couldn't find anything helpful. I'd appreciate any help.

Thanks in advance!

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000000
Exception Codes: 0x0000000000000001, 0x0000000000000000
VM Region Info: 0 is not in any region.  Bytes before following region: 4364288000
      REGION TYPE                 START - END      [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
      UNUSED SPACE AT START
--->  
      __TEXT                   10421c000-1052cc000 [ 16.7M] r-x/r-x SM=COW  ...er.app/Runner
Exception Note:  EXC_CORPSE_NOTIFY
Termination Reason: SIGNAL 11 Segmentation fault: 11
Terminating Process: exc handler [767]

Triggered by Thread:  0

Crashed: com.apple.main-thread
0  ???                            0x1852576f4 (Missing)
...
4  ???                            0x104e16f80 (Missing)
5  Runner                         0x6780 +[GeneratedPluginRegistrant registerWithRegistry:] + 171 (GeneratedPluginRegistrant.m:171)
6  Runner                         0x6e94 AppDelegate.application(_:didFinishLaunchingWithOptions:) + 23 (AppDelegate.swift:23)
7  Runner                         0x71ac @objc AppDelegate.application(_:didFinishLaunchingWithOptions:) (<compiler-generated>)
8  ???                            0x182c27044 (Missing)
...
42 ???                            0x182b967f4 (Missing)
43 Runner                         0x7578 main + 15 (AppDelegate.swift:15)
44 ???                            0x104345a24 (Missing)

Here's my AppDelegate.swift:

import UIKit
import Flutter
import GoogleMaps
import background_locator_2
import Firebase
import FirebaseAuth

func registerPlugins(registry: FlutterPluginRegistry) -> () {
    if (!registry.hasPlugin("BackgroundLocatorPlugin")) {
        GeneratedPluginRegistrant.register(with: registry)
    }
}

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate { 
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
      FirebaseApp.configure()
      GMSServices.provideAPIKey("...")
    
      GeneratedPluginRegistrant.register(with: self)
      BackgroundLocatorPlugin.setPluginRegistrantCallback(registerPlugins)
      
      return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}


    override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let firebaseAuth = Auth.auth()
        firebaseAuth.setAPNSToken(deviceToken, type: AuthAPNSTokenType.unknown)
    }
   
}

[Android] Service not starting on BackgroundLocator.registerLocationUpdate

The Locator Service does not start running when BackgroundLocator.registerLocationUpdate is called. I confirmed this by checking the output of BackgroundLocator.isServiceRunning() after BackgroundLocator.registerLocationUpdate is called, which is false. I added @pragma('vm:entry-point') to all of my callback functions as well. My flutter version is 2.10.5.

I also tried running the example app and encountered the same issue. Any ideas of what might be happening here?

does the library work with android 5.1.1

does the library work with android 5.1.1?
The application works with Android 12 but does not work on 5.1.1. callback not being called
All dependencies are all configured

[Android] How to use flutter packages on the background locator service?

How can we use other packages on the background locator service?

I tried

static void callbackFromBackground(LocationDto locationDto) async {
    LocationPermissionStatus? status = await LocationPermissionHandler.getLocationPermission();
    ....
 }

Where getLocationPermission() implementation is:

static Future<LocationPermissionStatus> getLocationPermission() async {
   var serviceEnabled = await Geolocator.isLocationServiceEnabled();
   if (serviceEnabled) {
     var permission = await Geolocator.checkPermission();
     return LocationPermissionStatus(
       appLocationPermission: permission,
       isLocationServiceEnabled: true,
     );
   }
   var permission = await Geolocator.checkPermission();
   return LocationPermissionStatus(
     appLocationPermission: permission,
     isLocationServiceEnabled: true,
   );
 }

But it raise error, which seems like because we can't use packages on the isolate

 E/flutter (22736): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: MissingPluginException(No implementation found for method isLocationServiceEnabled on channel flutter.baseflow.com/geolocator)
E/flutter (22736): #0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:175:7)
E/flutter (22736): <asynchronous suspension>
E/flutter (22736): #1      LocationPermissionHandler.getLocationPermission (package:aye_app/service/permission/location_permission_handler.dart:98:26)
E/flutter (22736): <asynchronous suspension>
E/flutter (22736): #2      BackgroundLocationService.callbackFromBackground (package:aye_app/service/location/background_location_service.dart:56:46)
E/flutter (22736): <asynchronous suspension>

MissingPluginException for IOS only

On Android devices, I am able to call methods but in IOS it throws this error every time and with different versions
background_locator_2: ^2.0.5 ---- ^2.0.6-dev.1 ---- ^2.0.6-dev.2

[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: MissingPluginException(No implementation found for method LocatorPlugin.isServiceRunning on channel app.yukams/locator_plugin)
#0      MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:313
<asynchronous suspension>
#1      BackgroundLocator.isServiceRunning
package:background_locator_2/background_locator.dart:61

Is there any solution to that

BUG: LocationCallbackHandler.initCallback() is not called sometimes (race condition)

Reproducable easily with example project.

Environment:

  • Flutter 3.7.8 (also with earlier versions released in the past few months)
  • Android emulator or device (any API level)

Steps to reproduce:

  1. Start example app using Android emulator
  2. Press start tracking button

Expected result:
LocationCallbackHandler.initCallback is called

Actual result:
LocationCallbackHandler.initCallback is mostly not called

Observations:
I made some investigation, and found a workaround, however, a proper fix would be welcome.

In android/src/main/kotlin/yukams/app/background_locator_2/IsolateHolderService.kt - line 100:

It seems, that there is a race condition here. Inter-isolate communication is occasionally not fully set up yet at this point(?) and message is not received in main isolate when services are started:

pluggables.forEach {context?.let { it1 -> it.onServiceStart(it1) } }

Currently, LocationCallbackHandler.initCallback is not called.

Note, if I use this ugly workaround below, then LocationCallbackHandler.initCallback is called properly all the time:

Handler(Looper.getMainLooper()).postDelayed( { pluggables.forEach { context?.let { it1 -> it.onServiceStart(it1) } } }, 1000 // value in milliseconds )

Symlink generated still references old package name for iOS

When building, I get
image

This is because the reference in the generated podspec file in .symlink is still named background_locator instead of background_locator_2. The file should be renamed to background_locator_2.podspec
image

The name of the file needs updating, and it's content should also be updated to reflect the correct name
image

I can confirm that the above changes allows iOS pod to install

IOS 16.1 Simulator searches for geolocation for 10 seconds

I'm doing tests with the plugin and the Android debug (real device) so far it's ok.

But the Iphone 14 Pro Max simulator with IOS 16.1 searches for geolocation for 10 seconds and then stops, the navigation icon disappears.

I'm using sample source code with minor changes, and Flutter 3.3.2, has anyone experienced this issue? I've read reports of potential issues with flutter+ 3.3.0
Simulator Screen Shot - iPhone 14 Pro Max - 2023-01-05 at 14 40 45

java.lang.IncompatibleClassChangeError: Found interface com.google.android.gms.location.FusedLocationProviderClient, but class was expected (declaration of 'com.google.android.gms.location.FusedLocationProviderClient' appears in /data/app/com.cis.zelderly-R4yzMHQbb02yUKGnof_ojg==/base.apk)

java.lang.IncompatibleClassChangeError: Found interface com.google.android.gms.location.FusedLocationProviderClient, but class was expected (declaration of 'com.google.android.gms.location.FusedLocationProviderClient' appears in /data/app/com.cis.zelderly-R4yzMHQbb02yUKGnof_ojg==/base.apk)

After update location implementation "com.google.android.gms:play-services-location:18.0.0" to implementation "com.google.android.gms:play-services-location:21.0.1" It is giving some new issue

e: /Users/cis/flutter/.pub-cache/git/background_locator_fixed-10b10556223cbd477372f9ca2db8d39bbb44f0d1/android/src/main/kotlin/yukams/app/background_locator_2/provider/GoogleLocationProviderClient.kt: (34, 5): 'onLocationResult' overrides nothing

[Question] How to correctly stop background locator & release its memory usage?

I my app, user can turn on/off background location through setting using a toggle.

When the toggle switch to off, I called
await BackgroundLocator.unRegisterLocationUpdate();

When the toggle switch to on, I called

static Future<void> startBackgroundTracking() async {
    Mutex().protect(() async {
      await init();

      SharedPreferences prefs = await SharedPreferences.getInstance();

      BackgroundLocator.registerLocationUpdate(
        callbackFromBackground,
        initDataCallback: {},
        initCallback: initBackgroundTracking,
        autoStop: false,
        iosSettings: const IOSSettings(accuracy: LocationAccuracy.NAVIGATION, distanceFilter: 1),
        androidSettings: AndroidSettings(
          accuracy: LocationAccuracy.NAVIGATION,
          distanceFilter: 0,
          androidNotificationSettings: AndroidNotificationSettings(...),
        ),
      );
    });
  }

Where init() is:

static Future<void> init() async {
  _port = ReceivePort();
  if (IsolateNameServer.lookupPortByName(_isolateName) != null) {
    IsolateNameServer.removePortNameMapping(_isolateName);
  }

  _port.listen((dynamic data) async {
    // TODO: Listen from background and do something with it
  });

  await BackgroundLocator.initialize();
}

Somehow, the memory keep increasing when ever I call startBackgroundTracking(), even though I have already unregister BackgroundLocator

image
Here is the snapshots of memory usage, small bumps are when I turn on the background tracking

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Invalid argument: is a regular instance: Instance of 'LocationDto'

Hi, so i have upgraded gradle and these are my settings.
android/build.gradle

buildscript {
    ext.kotlin_version = '1.7.10'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.0'
        classpath 'com.google.gms:google-services:4.3.8'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

Then on android/gradle/wrapper/gradle-wrapper.properties

#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-all.zip

Unfortunately i get this error now.

E/flutter (  787): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Invalid argument: is a regular instance: Instance of 'LocationDto'
E/flutter (  787): #0      _SendPort._sendInternal (dart:isolate-patch/isolate_patch.dart:249:43)
E/flutter (  787): #1      _SendPort.send (dart:isolate-patch/isolate_patch.dart:230:5)
E/flutter (  787): #2      LocationServiceRepository.callback (package:drivers_app/tabPages/location_service_reposirtory.dart:58:11)
E/flutter (  787): <asynchronous suspension>
E/flutter (  787): #3      LocationCallbackHandler.callback (package:drivers_app/tabPages/LocationCallbackHandler.dart:24:5)
E/flutter (  787): <asynchronous suspension>

The issue lies here

class LocationServiceRepository {
....
Future<void> callback(LocationDto locationDto) async {
    print('$_count location in dart: ${locationDto.toString()}');
    await setLogPosition(_count, locationDto);
    final SendPort? send = IsolateNameServer.lookupPortByName(isolateName);
    send?.send(locationDto); //here
    _count++;
  }

what is causing this and how can i fix it ?

cashing on android marshmallow

 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.xxxxx.xxxxx, PID: 31604 android.app.RemoteServiceException: Bad notification posted from package com.xxxxx.xxxxx: Couldn't create icon: StatusBarIcon(icon=Icon(typ=RESOURCE pkg=com.xxxx.xxxxx id=0x7f0d0000) visible user=0 ) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2019) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:158) at android.app.ActivityThread.main(ActivityThread.java:7225) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Android crash when start Locator

Things were fine in the old version, I never had this problem. Is there any update on this?
Or keep the old version for the time being until we get the latest updates ؟!

java.lang.IncompatibleClassChangeError: Found class com.google.android.gms.location.FusedLocationProviderClient, but interface was expected (declaration of 'com.google.android.gms.location.FusedLocationProviderClient' appears in /data/app/~~QL_sEP8t1Imcgq67YGeu4A==/com.example-We0cUMLjtzq133zZW0GvZA==/base.apk)
at yukams.app.background_locator_2.provider.GoogleLocationProviderClient.requestLocationUpdates(GoogleLocationProviderClient.kt:17)
at yukams.app.background_locator_2.IsolateHolderService.startHolderService(IsolateHolderService.kt:199)
at yukams.app.background_locator_2.IsolateHolderService.onStartCommand(IsolateHolderService.kt:166)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4424)
at android.app.ActivityThread.access$2000(ActivityThread.java:257)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2020)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8037)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)

not working for android

ı toke this error
MainActivity.kt: (1, 9): Package name must be a '.'-separated identifier list #42519

App crashes on startup

When I try to build and run, my app crashes with the following error:

E/AndroidRuntime(10738): java.lang.RuntimeException: Unable to create service yukams.app.background_locator_2.IsolateHolderService: java.lang.NullPointerException: Attempt to read from field 'java.lang.String io.flutter.view.FlutterCallbackInformation.callbackLibraryPath' on a null object reference in method 'java.lang.String io.flutter.embedding.engine.dart.DartExecutor$DartCallback.toString()'
E/AndroidRuntime(10738): 	at android.app.ActivityThread.handleCreateService(ActivityThread.java:4498)
E/AndroidRuntime(10738): 	at android.app.ActivityThread.-$$Nest$mhandleCreateService(Unknown Source:0)
E/AndroidRuntime(10738): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2161)
E/AndroidRuntime(10738): 	at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime(10738): 	at android.os.Looper.loopOnce(Looper.java:201)
E/AndroidRuntime(10738): 	at android.os.Looper.loop(Looper.java:288)
E/AndroidRuntime(10738): 	at android.app.ActivityThread.main(ActivityThread.java:7872)
E/AndroidRuntime(10738): 	at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(10738): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
E/AndroidRuntime(10738): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
E/AndroidRuntime(10738): Caused by: java.lang.NullPointerException: Attempt to read from field 'java.lang.String io.flutter.view.FlutterCallbackInformation.callbackLibraryPath' on a null object reference in method 'java.lang.String io.flutter.embedding.engine.dart.DartExecutor$DartCallback.toString()'
E/AndroidRuntime(10738): 	at io.flutter.embedding.engine.dart.DartExecutor$DartCallback.toString(DartExecutor.java:421)
E/AndroidRuntime(10738): 	at java.lang.String.valueOf(String.java:3657)
E/AndroidRuntime(10738): 	at java.lang.StringBuilder.append(StringBuilder.java:132)
E/AndroidRuntime(10738): 	at io.flutter.embedding.engine.dart.DartExecutor.executeDartCallback(DartExecutor.java:175)
E/AndroidRuntime(10738): 	at yukams.app.background_locator_2.IsolateHolderExtensionKt.startLocatorService(IsolateHolderExtension.kt:51)
E/AndroidRuntime(10738): 	at yukams.app.background_locator_2.IsolateHolderService.onCreate(IsolateHolderService.kt:83)
E/AndroidRuntime(10738): 	at android.app.ActivityThread.handleCreateService(ActivityThread.java:4485)
E/AndroidRuntime(10738): 	... 9 more
I/Process (10738): Sending signal. PID: 10738 SIG: 9

Failed to install

yukams.app.background_locator_2.BootBroadcastReceiver: Targeting S+ (version 31 and above) requires that an explicit value for android:exported be defined when intent filters are present]

Add an option to change notification priority

If a location background service was active in my phone I would have liked to know about it in PRIORITY_MAX and not PRIORITY_HIGH.

Anyway it is better to add an option to let the user decide what he wants.

return NotificationCompat.Builder(this, Keys.CHANNEL_ID) .setContentTitle(notificationTitle) .setContentText(notificationMsg) .setStyle( NotificationCompat.BigTextStyle() .bigText(notificationBigMsg) ) .setSmallIcon(icon) .setColor(notificationIconColor) .setPriority(NotificationCompat.PRIORITY_MAX) .setContentIntent(pendingIntent) .setOnlyAlertOnce(true) // so when data is updated don't make sound and alert in android 8.0+ .setOngoing(true) .build()

Android app crashing while on location service. in share build via google drive link and diawi link

java.lang.RuntimeException: Unable to start service yukams.app.background_locator_2.IsolateHolderService@c2a45c6 with Intent { act=UPDATE_NOTIFICATION cmp=com.techguy/yukams.app.background_locator_2.IsolateHolderService (has extras) }: java.lang.IllegalArgumentException: Invalid notification (no valid small icon): Notification(channel=app.yukams/locator_plugin pri=1 contentView=null vibrate=null sound=null defaults=0x0 flags=0xa color=0x00000000 vis=PRIVATE semFlags=0x0 semPriority=0 semMissedCount=0)

Caused by: java.lang.IllegalArgumentException: Invalid notification (no valid small icon): Notification(channel=app.yukams/locator_plugin pri=1 contentView=null vibrate=null sound=null defaults=0x0 flags=0xa color=0x00000000 vis=PRIVATE semFlags=0x0 semPriority=0 semMissedCount=0)

stop app on terminate dont really terminate the service

I'm using the last released version 2.0.5 on flutter 3.0.5 only on android.

until now I never stopped the service but now I need it to stop when the app is terminated.

so I added :
"""

    <service android:name="yukams.app.background_locator_2.LocatorService"
        android:permission="android.permission.BIND_JOB_SERVICE"
        android:stopWithTask="true"
        android:exported="true"/>

"""
but now every time I terminate the app and reopen I get doubled callbacks like this:
image

this is what i do when i reopen the app:
"""
if (!isUpdated || !isServiceRunning) {
await initBackgroundLocator();
await _registerLocator(staticRepository);
}
"""

Firebase_storage didn't work with background_locator together

UploadTask of Firebase_storage didn't work with background_locator together.
Upload file done but stuck at await uploadTask. how to fix this problem?

I try to config as this Use other plugins in callback

override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication
            .LaunchOptionsKey: Any]?
    ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)
        BackgroundLocatorPlugin.setPluginRegistrantCallback(registerPlugins)

        registerOtherPlugins()

        return super
            .application(application,
                         didFinishLaunchingWithOptions: launchOptions)
    }
 // setup for firebase_storage
    func registerOtherPlugins() {
      if !hasPlugin("io.flutter.plugins.firebase.storage") {
            FLTFirebaseStoragePlugin
                .register(with: registrar(forPlugin: "io.flutter.plugins.firebase.storage") as! FlutterPluginRegistrar)
        }
    }

This is my code

Future<String> urlDownload(file) async {
var uuid = Uuid().v1();
Reference ref = FirebaseStorage.instance.ref().child("post_$uuid.jpg");
UploadTask uploadTask = ref.putFile(file);

String downloadUrl = await (await uploadTask.onComplete).ref.getDownloadURL(); <-- stuck at this line.
return downloadUrl;
}

my dependencies

dependencies:
- firebase_storage: ^10.2.16
- background_locator_2: ^2.0.5
[✓] Flutter (Channel stable, 3.0.5, on macOS 12.5 21G72 darwin-arm (Rosetta),
    locale en-TH)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 13.4.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2020.3)
[✓] VS Code (version 1.71.0-insider)

Issue with compileSdkVersion 31

Hello Yukams,

thanks for managing this fork. I tried it today for the first time, but I'm getting an error when trying to start the Background Service.

The app is crashing and throwing an exception with following error message:

Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent. E/AndroidRuntime(23740): Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles. E/AndroidRuntime(23740): at android.app.PendingIntent.checkFlags(PendingIntent.java:382) E/AndroidRuntime(23740): at android.app.PendingIntent.getActivityAsUser(PendingIntent.java:465) E/AndroidRuntime(23740): at android.app.PendingIntent.getActivity(PendingIntent.java:451) E/AndroidRuntime(23740): at android.app.PendingIntent.getActivity(PendingIntent.java:415) E/AndroidRuntime(23740): at rekab.app.background_locator.IsolateHolderService.getNotification(IsolateHolderService.kt:116) E/AndroidRuntime(23740): at rekab.app.background_locator.IsolateHolderService.onCreate(IsolateHolderService.kt:81) E/AndroidRuntime(23740): at android.app.ActivityThread.handleCreateService(ActivityThread.java:4940) E/AndroidRuntime(23740): ... 9 more

Could you look into this please?

Thanks

[documentation/example issue] ios was getting can't find import in appdelegate.swift for pathprovider ios

when change to path provider foundation instead of ios module it is able to move forward
`
import path_provider_foundation
import UIKit

func registerPlugins(registry: FlutterPluginRegistry) {
GeneratedPluginRegistrant.register(with: registry)
}

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication
.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
BackgroundLocatorPlugin.setPluginRegistrantCallback(registerPlugins)

    registerOtherPlugins()

    return super
        .application(application,
                     didFinishLaunchingWithOptions: launchOptions)
}

func registerOtherPlugins() {
    if !hasPlugin("io.flutter.plugins.pathprovider") {
        PathProviderPlugin
            .register(with: registrar(forPlugin: "io.flutter.plugins.pathprovider")!)
    }
}

}
`
import path_provider_foundation

        PathProviderPlugin

are the changed lines

Is registering ports with IsolateNameServer necessary?

I'm wondering whether it's necessary to perform any of the operations on IsolateNameServer and ReceivePort as shown by the wiki (e.g. registering the port using IsolateNameServer.registerPortWithName and sending data to the port). AFAIK, if I want to do anything in response to the location updates being provided in the plugin I can just do it in the location callback and feed it into registerLocationUpdate. Is there a specific reason why the IsolateNameServer and ReceivePort is used in the example app?

stop report while app is killed

i try on three devices.
vivo, android 11 , flutter 3.3.0 , while app is killed, the notification was removed, and don't report log.
Honor, android 12, flutter 3.3.0, the same with vivo.
pixel, android 13, flutter 3.3.0. while app is killed, the the notification didn't removed , and can report log.

Restart service on device reboot is not working on android 12 with error on reboot

it works very well on background and even app is killed.
but when I reboot android phone then it cause error saying
backgound_locator_example is show below alert but after a while keep traking location.

How can I remove below alert when reboot

무제

my android manifext.xml is as below
(actually, i didn't make any change but run example github code from here )

`

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_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" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>


<!-- 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
    android:label="background_locator_example"
    android:name="${applicationName}"
    android:icon="@mipmap/ic_launcher"
    android:allowBackup="false"
    >
    <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"
        >
        <meta-data
            android:name="io.flutter.embedding.android.SplashScreenDrawable"
            android:resource="@drawable/launch_background" />
        <meta-data
            android:name="io.flutter.embedding.android.NormalTheme"
            android:resource="@style/NormalTheme"
            />
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver android:name="yukams.app.background_locator_2.BootBroadcastReceiver"
        android:enabled="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>
    <service
        android:name="yukams.app.background_locator_2.IsolateHolderService"
        android:permission="android.permission.FOREGROUND_SERVICE"
        android:exported="true"
        android:foregroundServiceType = "location"
        />

    <meta-data android:name="flutterEmbedding" android:value="2"/>

</application>

`

Unhandled Exception: type 'Null' is not a subtype of type 'LocationDto'

While using your plugin i get this error

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'Null' is not a subtype of type 'LocationDto'

This is the code i am using

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  ReceivePort port = ReceivePort();

  String logStr = '';
  bool? isRunning;
  LocationDto? lastLocation;

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

    if (IsolateNameServer.lookupPortByName(
            LocationServiceRepository.isolateName) !=
        null) {
      IsolateNameServer.removePortNameMapping(
          LocationServiceRepository.isolateName);
    }

    IsolateNameServer.registerPortWithName(
        port.sendPort, LocationServiceRepository.isolateName);

    port.listen(
      (dynamic data) async {
        await updateUI(data);
      },
    );
    initPlatformState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> updateUI(LocationDto data) async {
    final log = await FileManager.readLogFile();

    await _updateNotificationText(data);

    setState(() {
      lastLocation = data;
      logStr = log;
    });
  }

  Future<void> _updateNotificationText(LocationDto data) async {
    if (data == null) {
      return;
    }

    await BackgroundLocator.updateNotificationText(
        title: "new location received",
        msg: "${DateTime.now()}",
        bigMsg: "${data.latitude}, ${data.longitude}");
  }

  Future<void> initPlatformState() async {
    print('Initializing...');
    await BackgroundLocator.initialize();
    logStr = await FileManager.readLogFile();
    print('Initialization done');
    final _isRunning = await BackgroundLocator.isServiceRunning();
    setState(() {
      isRunning = _isRunning;
    });
    print('Running ${isRunning.toString()}');
  }

  @override
  Widget build(BuildContext context) {
    final start = SizedBox(
      width: double.maxFinite,
      child: ElevatedButton(
        child: Text('Start'),
        onPressed: () {
          _onStart();
        },
      ),
    );
    final stop = SizedBox(
      width: double.maxFinite,
      child: ElevatedButton(
        child: Text('Stop'),
        onPressed: () {
          onStop();
        },
      ),
    );
    final clear = SizedBox(
      width: double.maxFinite,
      child: ElevatedButton(
        child: Text('Clear Log'),
        onPressed: () {
          FileManager.clearLogFile();
          setState(() {
            logStr = '';
          });
        },
      ),
    );
    String msgStatus = "-";
    if (isRunning != null) {
      if (isRunning!) {
        msgStatus = 'Is running';
      } else {
        msgStatus = 'Is not running';
      }
    }
    final status = Text("Status: $msgStatus");

    final log = Text(
      logStr,
    );

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter background Locator'),
        ),
        body: Container(
          width: double.maxFinite,
          padding: const EdgeInsets.all(22),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[start, stop, clear, status, log],
            ),
          ),
        ),
      ),
    );
  }

  void onStop() async {
    await BackgroundLocator.unRegisterLocationUpdate();
    final _isRunning = await BackgroundLocator.isServiceRunning();
    setState(() {
      isRunning = _isRunning;
    });
  }

  void _onStart() async {
    //if (await isLocationAlwaysGranted()) {
    await _startLocator();
    final _isRunning = await BackgroundLocator.isServiceRunning();

    setState(() {
      isRunning = _isRunning;
      lastLocation = null;
    });
    // } else {
    // show error
  }
}

Future<bool> isLocationAlwaysGranted() async =>
    await Permission.locationAlways.isGranted;

/// Tries to ask for "location always" permissions from the user.
/// Returns `true` if successful, `false` othervise.
Future<bool> askForLocationAlwaysPermission() async {
  bool granted = await Permission.locationAlways.isGranted;

  if (!granted) {
    granted =
        await Permission.locationAlways.request() == PermissionStatus.granted;
  }

  return granted;
}

Future<void> _startLocator() async {
  Map<String, dynamic> data = {'countInit': 1};
  return await BackgroundLocator.registerLocationUpdate(
      LocationCallbackHandler.callback,
      initCallback: LocationCallbackHandler.initCallback,
      initDataCallback: data,
      disposeCallback: LocationCallbackHandler.disposeCallback,
      iosSettings: IOSSettings(
          accuracy: LocationAccuracy.NAVIGATION,
          distanceFilter: 0,
          stopWithTerminate: true),
      autoStop: false,
      androidSettings: AndroidSettings(
          accuracy: LocationAccuracy.NAVIGATION,
          interval: 5,
          distanceFilter: 0,
          client: LocationClient.google,
          androidNotificationSettings: AndroidNotificationSettings(
              notificationChannelName: 'Location tracking',
              notificationTitle: 'Start Location Tracking',
              notificationMsg: 'Track location in background',
              notificationBigMsg:
                  'Background location is on to keep the app up-tp-date with your location. This is required for main features to work properly when the app is not running.',
              notificationIconColor: Colors.grey,
              notificationTapCallback:
                  LocationCallbackHandler.notificationCallback)));
}

The error is in this line under initState when I start or stop the plugin.

  port.listen(
      (dynamic data) async {
        await updateUI(data);
      },
    );

The original code didn't have null safety so i tried to modify it. However it is pretty evident my knowledge is limited.
[1]: https://pub.dev/packages/background_locator_2

Build failed on Android. Flutter 3.0.5

e: C:\Users\User\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\background_locator_2-2.0.5\android\src\main\kotlin\yukams\app\background_locator_2\provider\LocationParserUtil.kt: (21, 20): Type mismatch: inferred type is String? but Any was expected

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':background_locator_2:compileDebugKotlin'.
> Compilation error. See log for more 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 22s
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

Flutter doctor:
[√] Flutter (Channel stable, 3.0.5, on Microsoft Windows [Version 10.0.19044.1889], locale en)
[√] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
[√] Chrome - develop for the web
[√] Visual Studio - develop for Windows (Visual Studio Community 2022 17.2.4)
[√] Android Studio (version 2021.2)
[√] VS Code (version 1.70.2)
[√] Connected device (4 available)
[√] HTTP Host Availability

release problem

Hello, I am trying to us the plugin with flutter 3.3.8 and I am experiencing crashes when running in release mode.

I saw this kind of documented in some issues of the original project, but not really here. So here my take on this.

This is what I added in the manifest:

        <receiver android:name="yukams.app.background_locator_2.BootBroadcastReceiver"
            android:enabled="true" android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

        <service android:name="yukams.app.background_locator_2.IsolateHolderService"
          android:permission="android.permission.FOREGROUND_SERVICE"
          android:exported="true"
          android:stopWithTask="true"
          android:foregroundServiceType = "location"/>
        
        <service android:name="yukams.app.background_locator_2.LocatorService"
          android:permission="android.permission.BIND_JOB_SERVICE"
          android:exported="true"
          android:stopWithTask="true"/>

I added the pragma to the callback function like:

@pragma('vm:entry-point')
  static void callback(LocationDto locationDto) async {
   
  }

I am not getting much of a readable error from this, but maybe you can work with it.

Here in the code I call BackgroundLocator.initialize and then BackgroundLocator.registerLocationUpdate, the log then shows some errors (the ones with the X in front of the line, even if no real error message is given):

Type	Time	PID	Tag	Message
X 11:03:51.950	18232	BackgroundLocatorPlugin	startIsolateService
X 11:03:51.990	18232	IsolateHolderService	startLocatorService: Start Flutter Engine
X 11:03:51.107	18232	IsolateHolderExtension	service initialized
X 11:03:51.110	18232	IsolateHolderService	onStartCommand => intent.action : START
X 11:03:51.110	18232	IsolateHolderService	startHolderService
11:03:51.112	1511	LocationManagerService	gps provider added registration from 10460/eu.hydrologis.smash/76256C68 -> Request[@+1s0ms HIGH_ACCURACY, WorkSource{10460 eu.hydrologis.smash}]
11:03:51.112	1511	LocationManagerService	try to release motion power when coming new active request
X 11:03:51.113	3421	RequestManager_FLP	[LocationManager] Location request 76256C68(Listener) gps interval=1000ms (min=1000ms) from eu.hydrologis.smash (10460_FINE_fg_true_foreground)
11:03:51.114	1511	CompatibilityChangeReporter	Compat change id reported: 73144566; UID 10460; state: ENABLED
11:03:51.114	1511	GnssLocationProvider	setRequest ProviderRequest[@+1s0ms, HIGH_ACCURACY, WorkSource{10460 eu.hydrologis.smash}]
11:03:51.114	1511	GnssLocationProvider	mStarted =  false, isEnabled = true
11:03:51.114	1511	GnssLocationProvider	stopBatching
11:03:51.114	1511	GnssLocationProvider	startNavigating
11:03:51.114	1511	GnssLocationProvider_ex	Data status WIFI connected
11:03:51.114	1511	LocationManagerService	network provider added registration from 10460/eu.hydrologis.smash/76256C68 -> Request[@+1s0ms LOW_POWER, WorkSource{10460 eu.hydrologis.smash}]
X 11:03:51.117	3421	RequestManager_FLP	[LocationManager] Location request 76256C68(Listener) network interval=1000ms (min=1000ms) from eu.hydrologis.smash (10460_FINE_fg_true_foreground)
11:03:51.117	1511	GnssLocationProvider	setting position_mode to standalone
11:03:51.117	1378	[email protected]	gps_set_position_mode: lowPowerMode(F)
11:03:51.118	1373	gpsd	WakeLock(Acquire,GPSD)

11:03:51.118	1373	gpsd	WakeLock(Release,GPSD)

11:03:51.121	1378	[email protected]	start: IGnss impl: start request
11:03:51.121	1373	gpsd	WakeLock(Acquire,GPSD)

11:03:51.122	3421	SettingManager_FLP	Location icon is enabled by eu.hydrologis.smash(10460)
11:03:51.122	3421	GnssEngineManager_FLP	updateEngineEnabled, true / isFromAp=true
11:03:51.122	3421	GnssEngineManager_FLP	updateEngineEnabled, register stationary

Then, at some point I also get the following:

Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 18287 (1.ui), pid 18232 (ydrologis.smash)

and and it crashes with:

Revision: '7'
ABI: 'arm64'
Processor: '5'
Timestamp: 2022-11-17 11:03:51.196259533+0100
Process uptime: 264s
Cmdline: eu.hydrologis.smash
pid: 18232, tid: 18287, name: 1.ui  >>> eu.hydrologis.smash <<<
uid: 10460
signal 6 (SIGABRT), code -1 (SI_QUEUE), fault addr --------
Abort message: '../../third_party/dart/runtime/vm/message_snapshot.cc: 576: error: expected: !lib.IsNull()'
    x0  0000000000000000  x1  000000000000476f  x2  0000000000000006  x3  0000007d0adf0410
    x4  0000800000808080  x5  0000800000808080  x6  0000800000808080  x7  8080800000800000
    x8  00000000000000f0  x9  0c618253e961ed3b  x10 0000000000000000  x11 ffffff80fffffbdf
    x12 0000000000000001  x13 000000000000005c  x14 0000000000000000  x15 0000000000000058
    x16 0000007e18f59d30  x17 0000007e18f32cd0  x18 0000007d05148000  x19 0000000000004738
    x20 000000000000476f  x21 00000000ffffffff  x22 0000007d0adf0968  x23 b400007ce917f412
    x24 b400007d60f0cf00  x25 0000000000000001  x26 0000000000000000  x27 0000007d07983000
    x28 0000007d07986000  x29 0000007d0adf0490
    lr  0000007e18ee2e90  sp  0000007d0adf03f0  pc  0000007e18ee2ebc  pst 0000000000001000
backtrace:
      #00 pc 000000000008bebc  /apex/com.android.runtime/lib64/bionic/libc.so (abort+168) (BuildId: 62a3df020a8897fe2ee2211519054ca7)
      #01 pc 0000000000696484  /data/app/~~Vaq6ie_lSi2zkwnZuw9uWg==/eu.hydrologis.smash-4iRIUBr6LiPmMKuIxFC3MA==/lib/arm64/libflutter.so (BuildId: 2cf88341252c95e1c57ab402a766496ee4430dec)
      #02 pc 00000000006ea7bc  /data/app/~~Vaq6ie_lSi2zkwnZuw9uWg==/eu.hydrologis.smash-4iRIUBr6LiPmMKuIxFC3MA==/lib/arm64/libflutter.so (BuildId: 2cf88341252c95e1c57ab402a766496ee4430dec)
      #03 pc 00000000006eefc0  /data/app/~~Vaq6ie_lSi2zkwnZuw9uWg==/eu.hydrologis.smash-4iRIUBr6LiPmMKuIxFC3MA==/lib/arm64/libflutter.so (BuildId: 2cf88341252c95e1c57ab402a766496ee4430dec)
      #04 pc 00000000006d7a84  /data/app/~~Vaq6ie_lSi2zkwnZuw9uWg==/eu.hydrologis.smash-4iRIUBr6LiPmMKuIxFC3MA==/lib/arm64/libflutter.so (BuildId: 2cf88341252c95e1c57ab402a766496ee4430dec)
      #05 pc 00000000006dde88  /data/app/~~Vaq6ie_lSi2zkwnZuw9uWg==/eu.hydrologis.smash-4iRIUBr6LiPmMKuIxFC3MA==/lib/arm64/libflutter.so (BuildId: 2cf88341252c95e1c57ab402a766496ee4430dec)
      #06 pc 00000000005b3e4c  /data/app/~~Vaq6ie_lSi2zkwnZuw9uWg==/eu.hydrologis.smash-4iRIUBr6LiPmMKuIxFC3MA==/lib/arm64/libflutter.so (BuildId: 2cf88341252c95e1c57ab402a766496ee4430dec)
      #07 pc 000000000068d918  /data/app/~~Vaq6ie_lSi2zkwnZuw9uWg==/eu.hydrologis.smash-4iRIUBr6LiPmMKuIxFC3MA==/lib/arm64/libflutter.so (BuildId: 2cf88341252c95e1c57ab402a766496ee4430dec)
      #08 pc 00000000003460cc  /data/app/~~Vaq6ie_lSi2zkwnZuw9uWg==/eu.hydrologis.smash-4iRIUBr6LiPmMKuIxFC3MA==/lib/arm64/libflutter.so (BuildId: 2cf88341252c95e1c57ab402a766496ee4430dec)
      #09 pc 0000000000349658  /data/app/~~Vaq6ie_lSi2zkwnZuw9uWg==/eu.hydrologis.smash-4iRIUBr6LiPmMKuIxFC3MA==/lib/arm64/libflutter.so (BuildId: 2cf88341252c95e1c57ab402a766496ee4430dec)
      #10 pc 000000000001716c  /system/lib64/libutils.so (android::Looper::pollInner(int)+916) (BuildId: eee35419973f1d9330ba7fca3b3f5bf7)
      #11 pc 0000000000016d6c  /system/lib64/libutils.so (android::Looper::pollOnce(int, int*, int*, void**)+116) (BuildId: eee35419973f1d9330ba7fca3b3f5bf7)
      #12 pc 0000000000017510  /system/lib64/libandroid.so (ALooper_pollOnce+104) (BuildId: 1199f5b6a507bffc9402e8d87cc7759b)
      #13 pc 0000000000349764  /data/app/~~Vaq6ie_lSi2zkwnZuw9uWg==/eu.hydrologis.smash-4iRIUBr6LiPmMKuIxFC3MA==/lib/arm64/libflutter.so (BuildId: 2cf88341252c95e1c57ab402a766496ee4430dec)
      #14 pc 0000000000347d8c  /data/app/~~Vaq6ie_lSi2zkwnZuw9uWg==/eu.hydrologis.smash-4iRIUBr6LiPmMKuIxFC3MA==/lib/arm64/libflutter.so (BuildId: 2cf88341252c95e1c57ab402a766496ee4430dec)
      #15 pc 00000000000f1194  /apex/com.android.runtime/lib64/bionic/libc.so (__pthread_start(void*)+264) (BuildId: 62a3df020a8897fe2ee2211519054ca7)
      #16 pc 000000000008d7f0  /apex/com.android.runtime/lib64/bionic/libc.so (__start_thread+68) (BuildId: 62a3df020a8897fe2ee2211519054ca7)

Any help would be great here, this is an odd showstopper.
Thank you

pod update failed

I'm trying example with my ios device.

flutter build ios

then cause error
Error running pod install


Running pod install...                                             493ms
CocoaPods' output:
↳
      Preparing

    Analyzing dependencies

    Inspecting targets to integrate
      Using `ARCHS` setting to build architectures of target `Pods-Runner`: (``)

    Fetching external sources
    -> Fetching podspec for `Flutter` from `Flutter`
    -> Fetching podspec for `background_locator_2` from
    `.symlinks/plugins/background_locator_2/ios`
    [!] No podspec found for `background_locator_2` in
    `.symlinks/plugins/background_locator_2/ios`

I tried open with Runner.xcworkspace
but cause error with below.
I think I should pod install but keep failed
스크린샷 2022-08-07 오전 10 26 00

pedrojung@pedroui-MacBookPro ios % arch -arm64 pod update
Update all pods
Updating local specs repositories
Analyzing dependencies
[!] No podspec found for background_locator_2 in .symlinks/plugins/background_locator_2/ios
pedrojung@pedroui-MacBookPro ios % arch -arm64 pod update
Update all pods
Updating local specs repositories
Analyzing dependencies
[!] No podspec found for background_locator_2 in .symlinks/plugins/background_locator_2/ios
pedrojung@pedroui-MacBookPro ios % pod install
Analyzing dependencies
[!] No podspec found for background_locator_2 in .symlinks/plugins/background_locator_2/ios
pedrojung@pedroui-MacBookPro ios %

[ios] Call back is not working in release mode

The application is working as expected in debug mode no issues are found.

But when the ios app is running on release mode, The callback is not calling from the native side.
Even the example app is not working in release mode.

Android Release mode

Package is work in debug mode without any issues, but its not working on release mode

Stop reporting while in Standby

First of all, excellent work of you in continuing with this project

Knowing that Android from version 10 has begun to change the way of working with location and communications, and in version 11 and 12 it is already a fact, I wanted to know if there is a way or if someone could solve, that when the cell phone is in standby mode, it is still reporting, since while it is like this, android lowers the communications and turns off the location, so that after a few hours it enables them for a few minutes and turns everything off again and stays like this until the cell phone is turned on for example and remains in the foreground, this is documented in android and it is its way of working, but I would like to know if there is a way to avoid this to always have a location in real time.

Android crash: Context.startForegroundService() did not then call Service.startForeground()

My code crashs here, but not all devices.

if (await BackgroundLocator.isServiceRunning()) { IsolateNameServer.removePortNameMapping('LocatorIsolate'); BackgroundLocator.unRegisterLocationUpdate(); }

`# Crashlytics - Stack trace

Platform: android

Version: 1.7.6 (77)

Issue: 739411ac5d00e1e8f6030399048f08d9

Session: 63779F660291000128383E0AC46E1DCC_DNE_0_v2

Date: Fri Nov 18 2022 16:07:36 GMT+0100 (Mitteleuropäische Normalzeit)

Fatal Exception: android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{f73a0c4 u0 XXX/yukams.app.background_locator_2.IsolateHolderService}
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1894)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7156)
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:975)

Firebase-Messaging-Topics-Io:
at java.lang.Object.wait(Object.java)
at java.lang.Thread.parkFor$(Thread.java:2137)
at sun.misc.Unsafe.park(Unsafe.java:358)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:190)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2059)
at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1120)
at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:849)
at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1092)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1152)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at com.google.android.gms.common.util.concurrent.zza.run(zza.java:6)
at java.lang.Thread.run(Thread.java:764)

Crashlytics Exception Handler1:
at dalvik.system.VMStack.getThreadStackTrace(VMStack.java)
at java.lang.Thread.getStackTrace(Thread.java:1538)
at java.lang.Thread.getAllStackTraces(Thread.java:1588)
at com.google.firebase.crashlytics.internal.common.CrashlyticsReportDataCapture.populateThreadsList(CrashlyticsReportDataCapture.java:16)
at com.google.firebase.crashlytics.internal.common.CrashlyticsReportDataCapture.populateExecutionData(CrashlyticsReportDataCapture.java:4)
at com.google.firebase.crashlytics.internal.common.CrashlyticsReportDataCapture.populateEventApplicationData(CrashlyticsReportDataCapture.java:45)
at com.google.firebase.crashlytics.internal.common.CrashlyticsReportDataCapture.captureEventData(CrashlyticsReportDataCapture.java:44)
at com.google.firebase.crashlytics.internal.common.SessionReportingCoordinator.persistEvent(SessionReportingCoordinator.java:19)
at com.google.firebase.crashlytics.internal.common.SessionReportingCoordinator.persistFatalEvent(SessionReportingCoordinator.java:32)
at com.google.firebase.crashlytics.internal.common.CrashlyticsController$2.call(CrashlyticsController.java:49)
at com.google.firebase.crashlytics.internal.common.CrashlyticsController$2.call(CrashlyticsController.java)
at com.google.firebase.crashlytics.internal.common.CrashlyticsBackgroundWorker$3.then(CrashlyticsBackgroundWorker.java:2)
at com.google.android.gms.tasks.zze.run(zze.java:8)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at com.google.firebase.crashlytics.internal.common.ExecutorUtils$1$1.onRun(ExecutorUtils.java:2)
at com.google.firebase.crashlytics.internal.common.BackgroundPriorityRunnable.run(BackgroundPriorityRunnable.java:5)
at java.lang.Thread.run(Thread.java:764)

pool-4-thread-1:
at java.lang.Object.wait(Object.java)
at java.lang.Thread.parkFor$(Thread.java:2137)
at sun.misc.Unsafe.park(Unsafe.java:358)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:190)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2059)
at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1092)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1152)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)

ReferenceQueueDaemon:
at java.lang.Object.wait(Object.java)
at java.lang.Daemons$ReferenceQueueDaemon.runInternal(Daemons.java:178)
at java.lang.Daemons$Daemon.run(Daemons.java:103)
at java.lang.Thread.run(Thread.java:764)

GoogleApiHandler:
at android.os.MessageQueue.nativePollOnce(MessageQueue.java)
at android.os.MessageQueue.next(MessageQueue.java:326)
at android.os.Looper.loop(Looper.java:181)
at android.os.HandlerThread.run(HandlerThread.java:65)

MessengerIpcClient:
at java.lang.Object.wait(Object.java)
at java.lang.Thread.parkFor$(Thread.java:2137)
at sun.misc.Unsafe.park(Unsafe.java:358)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:190)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2059)
at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1120)
at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:849)
at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1092)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1152)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at com.google.android.gms.common.util.concurrent.zza.run(zza.java:6)
at java.lang.Thread.run(Thread.java:764)

Sqflite:
at android.os.MessageQueue.nativePollOnce(MessageQueue.java)
at android.os.MessageQueue.next(MessageQueue.java:326)
at android.os.Looper.loop(Looper.java:181)
at android.os.HandlerThread.run(HandlerThread.java:65)

GmsDynamite:
at java.lang.Object.wait(Object.java)
at com.google.android.gms.dynamite.zza.run(zza.java:6)

Firebase-Messaging-Init:
at java.lang.Object.wait(Object.java)
at java.lang.Thread.parkFor$(Thread.java:2137)
at sun.misc.Unsafe.park(Unsafe.java:358)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:190)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2059)
at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1120)
at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:849)
at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1092)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1152)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at com.google.android.gms.common.util.concurrent.zza.run(zza.java:6)
at java.lang.Thread.run(Thread.java:764)

queued-work-looper:
at android.os.MessageQueue.nativePollOnce(MessageQueue.java)
at android.os.MessageQueue.next(MessageQueue.java:326)
at android.os.Looper.loop(Looper.java:181)
at android.os.HandlerThread.run(HandlerThread.java:65)

pool-16-thread-2:
at java.lang.Object.wait(Object.java)
at java.lang.Thread.parkFor$(Thread.java:2137)
at sun.misc.Unsafe.park(Unsafe.java:358)
at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:230)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2101)
at java.util.concurrent.LinkedBlockingQueue.poll(LinkedBlockingQueue.java:467)
at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1091)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1152)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)

flutter-worker-2:
at android.os.Handler.post(Handler.java:395)
at com.tekartik.sqflite.SqflitePlugin.onQueryCall(SqflitePlugin.java:14)
at com.tekartik.sqflite.SqflitePlugin.onMethodCall(SqflitePlugin.java:224)
at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:17)
at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:18)
at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0(DartMessenger.java:20)
at io.flutter.embedding.engine.dart.DartMessenger.$r8$lambda$TsixYUB5E6FpKhMtCSQVHKE89gQ(DartMessenger.java)
at io.flutter.embedding.engine.dart.DartMessenger$$InternalSyntheticLambda$0$5dd8b6f7959f08bc8717eff7469e77e06ef5aed51cc0cee17f1e13794798223f$0.run(DartMessenger.java:12)
at io.flutter.embedding.engine.dart.DartMessenger$SerialTaskQueue.flush(DartMessenger.java:20)
at io.flutter.embedding.engine.dart.DartMessenger$SerialTaskQueue.lambda$dispatch$0(DartMessenger.java)
at io.flutter.embedding.engine.dart.DartMessenger$SerialTaskQueue.$r8$lambda$F0iXMzLdPiwUET1ugdCo3vpOFvI(DartMessenger.java)
at io.flutter.embedding.engine.dart.DartMessenger$SerialTaskQueue$$InternalSyntheticLambda$1$87f003a9f337bebdd0ba7a08cc7e573e8bd1ce25d26d2f3d3923593655f1df5b$0.run(DartMessenger.java:2)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)

awaitEvenIfOnMainThread task continuation executor1:
at java.lang.Object.wait(Object.java)
at java.lang.Thread.parkFor$(Thread.java:2137)
at sun.misc.Unsafe.park(Unsafe.java:358)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:190)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2059)
at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1092)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1152)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at com.google.firebase.crashlytics.internal.common.ExecutorUtils$1$1.onRun(ExecutorUtils.java:2)
at com.google.firebase.crashlytics.internal.common.BackgroundPriorityRunnable.run(BackgroundPriorityRunnable.java:5)
at java.lang.Thread.run(Thread.java:764)

com.google.firebase.crashlytics.startup1:
at java.lang.Object.wait(Object.java)
at java.lang.Thread.parkFor$(Thread.java:2137)
at sun.misc.Unsafe.park(Unsafe.java:358)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:190)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2059)
at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1092)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1152)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at com.google.firebase.crashlytics.internal.common.ExecutorUtils$1$1.onRun(ExecutorUtils.java:2)
at com.google.firebase.crashlytics.internal.common.BackgroundPriorityRunnable.run(BackgroundPriorityRunnable.java:5)
at java.lang.Thread.run(Thread.java:764)

FinalizerWatchdogDaemon:
at java.lang.Object.wait(Object.java)
at java.lang.Daemons$FinalizerWatchdogDaemon.sleepUntilNeeded(Daemons.java:297)
at java.lang.Daemons$FinalizerWatchdogDaemon.runInternal(Daemons.java:277)
at java.lang.Daemons$Daemon.run(Daemons.java:103)
at java.lang.Thread.run(Thread.java:764)

FinalizerDaemon:
at java.lang.Object.wait(Object.java)
at java.lang.Object.wait(Object.java:422)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:188)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:209)
at java.lang.Daemons$FinalizerDaemon.runInternal(Daemons.java:232)
at java.lang.Daemons$Daemon.run(Daemons.java:103)
at java.lang.Thread.run(Thread.java:764)`

Erro null safety

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
E/flutter ( 8512): #0 SettingsUtil._getCommonArgumentsMap (package:background_locator_2/utils/settings_util.dart:39:54)
E/flutter ( 8512): #1 SettingsUtil.getArgumentsMap (package:background_locator_2/utils/settings_util.dart:17:18)
E/flutter ( 8512): #2 BackgroundLocator.registerLocationUpdate (package:background_locator_2/background_locator.dart:39:31)

Not working on ios release mode when app is killed

Hi i am trying this library on latest flutter 3.7.3 version and background_locator_2: ^2.0.6
Android working perfect but on ios not working in release mode when app is killed or terminated. I need to get the location data when user without the need to open the app. Does this library not work when the application is killed or am I wrong?

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

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

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.