Giter Club home page Giter Club logo

background-geolocation's People

Contributors

harelm avatar jamesdiacono avatar

Stargazers

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

Watchers

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

background-geolocation's Issues

Potential security best practice deviation for broadcasts (Snyk Code)

Hi!

As part of our internal security review, we perform security checks with Snyk. It found the following issue in your code, which I'm unable to completely verify:
image
I thought I might share, since due to the potential type of data (geolocation), this might be worth mitigating.

Add Custom path/route when tap on Notification to open specific screen.

Describe the solution you'd like
When the user taps on the notification, opens a specific screen. Add to addWatcher one more parameter in the same way that when receiving a push notification you can pass a parameter to open a specific screen.

When I tap on the notification it opens the application settings and not the application itself.

The plugin works wonderfully :)

true background geo location

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

yeah so when my coworker work with forground tasks in android it doesn't close the task and sticky pop up but i also
appreciate the fact that going to home opens the pop up and does the tracking but as soon as the task closes the pop up goes to nothing

Describe the solution you'd like
Atclear and concise description of what you want to happen.

the way this package is written is callback in js but when the task is closed completely figuring out a url in config would be ideal to what apps could do in current days and still send geo location untill user gets back to app to stop watcher

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

alter native solution for me was because of time restricted application i have to give the app to my coworker to setup android related task for now and hope community
Additional context
Add any other context or screenshots about the feature request here.

add an option to change the small icon on the notification when app goes into background?

Is your feature request related to a problem? Please describe.
Currently Default icon shows when the app goes into background which does not looks good

Describe the solution you'd like
A setting in the watcher option to change the notification small icon.

Describe alternatives you've considered

  1. this plugin provides the option to change icon maybe it can help in creating a feature for this package
    a. https://www.npmjs.com/package/capacitor-background-geolocation

Additional context
Add any other context or screenshots about the feature request here.

Combination with BLE Plugin: No disconnect when app gets closed

Description
Using this Plugin together with cordova-plugin-ble-central or capacitor-community/bluetooth-le in Android bluetooth connection doesn't get closed when app is closed.

Reproduce

  1. Create an ionic app for Android
  2. install background-geolocation
  3. install cordova-plugin-ble-central or capacitor-community/bluetooth-le
  4. connect a ble device with the app
  5. close the app
  6. device is still connected with phone and therefore doesn't get find when reopen the app
  7. to verify: disable Bluetooth in phone settings after app is closed and the device will notify a disconnect

Expected behavior
Bluetooth connection should get closed when app gets closed

Smartphone

  • Device: Motorola moto g 5G plus, Google Pixel 2
  • OS: Android 10
  • Version 29

Additional context
I am working on a ble-sensor combined with geolocation tracker project

I opened this also as an issue at capacitor-community/bluetooth-le:
capacitor-community/bluetooth-le#158

Android notification stays after calling removeWatcher

I start by calling addWatcher() and then after some time I decide to remove it by calling removeWatcher(). My understanding would be that the sticky notification would disappear when there is no active watcher. No watcher means no location tracking and that should be no notification, is that right?

I have a special option inside my app settings that allows users to switch background geolocation on/off. The idea was to remove the watcher when app is being backgrounded and then start it again when it's foregrounded.

The sample approach and logic I tried is something like this. I'm using Capacitor's App plugin to detect if the app was backgrounded or foregrounded.

App.addListener("appStateChange", state => {
  if (!this.canUseBackgroundGps) {
    if (state.isActive) {
      BackgroundGeolocation.addWatcher(/* ... */);
    } else {
      BackgroundGeolocation.removeWatcher(/* ... */);
    }
  }
});

I only tested and observed this behaviour on Android. I'll test if it behaves the same on iOS tomorrow.

Thanks for any heads up,
Patrik

How to keep HTTP requests running in background? - Android

First of all, awesome plugin. Now, I understand this is not exactly a plugin's issue, but probably a very common scenario for it.
I'm trying to watch and send the location via HTTP Post request to server as in the following code:

BackgroundGeolocation.addWatcher(
      {
        backgroundMessage:
          "Location is still tracked in background.",
        requestPermissions: true,
        stale: true,
        distanceFilter: 200,
      },
      async function (location) {
        if (location) {
          let formData = new FormData();
          formData.append("location", JSON.stringify(location));
          await ApiService.sendLocation(formData); // Does a simple HTTP post request using Axios.
        }
      }
    );

This is working fine in iOS indefinitely (as long as I grant the 'Always' location permission).

However for Android, this is not the case. I granted all battery/data usage permissions for my app in particular.
After 5 minutes in background, the server will stop receiving locations.
As soon as I enter the app again (it is not being killed btw, I can tell because it does not reload the splash screen) it will start sending all the buffered requests to server.
So the location is being tracked correctly, but it seems like the HTTP requests get blocked and start to pile up.

Does this mean that I should actually do the HTTP request inside the native callback code?
public void onLocationResult(LocationResult locationResult)

I would appreciate any insight, but as I said, I understand this is not precisely this plugin's issue.

Clicking on app notification open App info Settings page ?

Describe the bug
Clicking on app notification open App info Settings page is that intended ?

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
It should open the app main activity hence the app and not its info settings page

Screenshots
https://user-images.githubusercontent.com/6751554/110302060-d4a6af80-801e-11eb-974f-aa3441774cbb.mp4

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6] one plus 7 pro
  • OS: [e.g. iOS8.1] android 10
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22] plugin version 0.3.11

Additional context
Add any other context about the problem here.

[Question] Is it possible to keep getting location updates when the app is closed?

After some testing on Android it seems like the location updates are sent only as long as the app is open, though it doesn't have to be visible. I'm wondering if it is possible for the watcher to persist if the user, say, accidentally closes the app? Is this something already possible with this plugin, or would it have to be implemented?

Thanks

Do I have to stop watching when entering Foreground?

Could you describe how the plugin works? I'm interested in only listening the location while being on background, does the Plugin already handles this? Does it only activate when App enters background mode, and stops when it enters foreground mode? Or do I have to detect this transitions myself and do addWatcher / removeWatcher accordingly?

No locations sent when app is closed

Describe the bug
I'm developing an app that requires to push locations to BE even if the app has been closed, not simply put in background. I did several tests but I was not able to do this, the app it stops to send location when I close it. Is this the normal behavior, is it a bug or am I doing something wrong?

To Reproduce
Steps to reproduce the behavior:

  1. close the app

Expected behavior
The BE continue to receive locations even if the app has been closed, not in background

Smartphone (please complete the following information):

  • Device: iPhone 12 Pro in iPhone Simultator
  • OS: iOS 14.4

Setting interval time

image

Hi,
we use this plugin in our ionic/react project. It's working great but , we need set location every 30 seconds. In plugin default 1 second. We need property like setInvertal method.

Thank you.

Add a example to use in typescript

Hi,
I have a request to you please add a example for the typescript that would be very helpful for us.
I am adding code which given code snippet but getting error.

Thanks!

registerPlugin not found

After reading the docs, the plugin looked very promising, but cannot get it to work as of yet, likely due to unclear instructions. registerPlugin cannot be found (using capacitor V3).

Steps to reproduce the behavior:

  1. Start new project using capacitor V3 (Angular + Ionic)
  2. Run npm install @capacitor-community/background-geolocation, npx cap update
  3. Attempt build

Editable timeout and new parameter

Problem

There is no option to set custom timeout and setFastestInterval parameter.

Solution

  • Could you add possibility to add custom timeout value for setMaxWaitTime and setMaxWaitTime?
  • Could you add setFastestInterval with possibility custom value?

Capacitor 3 Support

Is your feature request related to a problem? Please describe.

The Capacitor 3 RC is out! 🎉 This library should support the new version

Describe the solution you'd like

Follow the plugin upgrade guide here: https://capacitorjs.com/docs/v3/updating/plugins/3-0

Additional context

The migration is pretty easy, I've done it for a couple plugins. Happy to assist if you need assisting!

Prevent Android GPS spoofing

Is your feature request related to a problem? Please describe.
It is easy to use Fake GPS apps on Android to simulate a location. It would be great to have an option to prevent this. It shouldn't be a problem with iOS because it's supposedly a lot harder if not impossible to do so.

Describe the solution you'd like
If a location could be marked as isMock or something similar, that would be great.

Describe alternatives you've considered
Users in my apps save locations in a certain radius to score points so I can calculate distances between these points to see if it was possible. It solves the worst cases but doesn't help me find users who are more clever and for example check time of their locations.

Additional context
This SO answer offers an exact suggestion on how to deal with that - https://stackoverflow.com/questions/6880232/disable-check-for-mock-location-prevent-gps-spoofing.

Android Build failing with 'cannot find symbol call.setKeepAlive(true)'

I've built a simple Ionic App with Capacitor v3.

When trying to build this app with android studio, the build is failing with the following error:

@capacitor-community\background-geolocation\android\src\main\java\com\equimaps\capacitor_background_geolocation\BackgroundGeolocation.java:53: error: cannot find symbol
        call.setKeepAlive(true);
            ^
  symbol:   method setKeepAlive(boolean)
  location: variable call of type PluginCall

Avoiding duplicate watchers

Is it possible to specify an ID for a watcher so that if your code accidentally attempts a duplication of a background watcher it will overwrite an existing watcher or just not create a new one, since one already exists? Or have I missed features in the library that already exist? Thanks!

Notification icon still defaults to the white box even after providing the icon from mipmap

Describe the bug
A clear and concise description of what the bug is.
The feature update to have custom icon or per say default to app icon is not working as tested.
To Reproduce
Steps to reproduce the behavior:
going into background the notification which appears is still default white box.

Expected behavior
Should take app icon by default or provided asset which can be mentioned in the strings.xml file.

Screenshots
WhatsApp Image 2021-03-08 at 14 25 15
screenshot with still default icon

but when notification is pressed it shows the correct app icon then :
WhatsApp Image 2021-03-08 at 14 37 14

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6] One plus 7 pro
  • OS: [e.g. iOS8.1] Android 10
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22] plugin version 0.3.11

Additional context
Add any other context about the problem here.

iOS background location fails and the location stops updating in the foreground. Location icon in the status bar turns hollow.

We have been using v0.3 of this plugin on iOS for months now and it has been working in the background and foreground properly.

All of a sudden, we are experiencing when the app is backgrounded and brought back to the foreground, the location fails and doesn't update - both in the foreground and background. The arrow icon for location in the status bar turns from solid, to outlined/hollow.

The location works fine in the foreground, until it's backgrounded. After it fails when being backgrounded closing and opening the watcher seems to reset it to work again in the foreground.

Does anyone have any ideas on how to debug this?

Background stop when app is killed

Hello:

I'm testing the connector and when the app is open in the foreground and in the background it works fine, but if I remove the app from my running app manager, the background stops working and I don't keep getting coordinates.

What's going on? Isn't the service supposed to stay active?

I am using Capacitor v3 and my Android version is 9 on my smartphone.

Notification is not present upon going to background

  • No error is thrown
  • Watcher is properly added/removed (going to background/foreground respectively)
  • Watcher reports location from background 5-8 times in intervals from 3-5 s then stops
  • When in background notification is not present
  • Originally was cordova project but it has been migrated to capacitor (cordova is not present anymore)

Only thing i have found is in logcat from Android Studio:

  • Permission Denial: writing com.sec.android.provider.badge.BadgeProvider

I have tried adding :

  • <uses-permission android:name="com.sec.android.provider.badge.permission.READ"/>
  • <uses-permission android:name="com.sec.android.provider.badge.permission.WRITE"/>
    didn't notice any changes to plugin behaviour.

MainActivity.java:

import android.os.Bundle;

import com.getcapacitor.BridgeActivity;
import com.getcapacitor.Plugin;

import java.util.ArrayList;

import com.equimaps.capacitor_background_geolocation.BackgroundGeolocation;

public class MainActivity extends BridgeActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initializes the Bridge
    this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
      // Additional plugins you've installed go here
      // Ex: add(TotallyAwesomePlugin.class);
      add(BackgroundGeolocation.class);
    }});
  }
}

AndroidManifest.xml:

<application
        android:usesCleartextTraffic="true"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        
        <service
            android:name="com.equimaps.capacitor_background_geolocation.BackgroundGeolocationService"
            android:enabled="true"
            android:exported="true"
            android:foregroundServiceType="location" />

        <activity
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
            android:name="com.enonsolutions.taxi.driver.MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@style/AppTheme.NoActionBarLaunch"
            android:launchMode="singleTask">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="@string/custom_url_scheme" />
            </intent-filter>

        </activity>

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"></meta-data>
        </provider>
    </application>

Implementation:

let watcherId = BackgroundGeolocation.addWatcher(
        {
          backgroundMessage: "Cancel to prevent battery drain.",
          backgroundTitle: "Tracking You.",
          requestPermissions: true,
          stale: false,
          distanceFilter: 0,
        },
        function callback(location, error) {
          if (error) {
            console.log(error);
            if (error.code === "NOT_AUTHORIZED") {
              Modals.confirm({
                title: "Location Required",
                message:
                  "This app needs your location, " +
                  "but does not have permission.\n\n" +
                  "Open settings now?",
              }).then(function ({ value }) {
                if (value) {
                  BackgroundGeolocation.openSettings();
                }
              });
            }
            return console.error(error);
          }
          console.log("Background location:");
          console.log(location);
          return ;
        }
      );

Problem with typescript

I can't import the plugin i get this error
Cannot find module '@capacitor-community/background-geolocation' or its corresponding type declarations.

No variants found on Android build

Describe the bug
I'm getting the exact same issue as #9 on version 1.0.2 for capacitor 3

Here is a snippet of the error log

No variants found for ':capacitor-community-background-geolocation'. Check build files to ensure at least one variant exists. at: com.android.tools.idea.gradle.project.sync.idea.svs.AndroidModule.deliverModels(AndroidModule.kt:191) com.android.tools.idea.gradle.project.sync.idea.svs.AndroidExtraModelProvider$Worker.populateBuildModels(AndroidExtraModelProvider.kt:121)

To Reproduce
Followed the installation instructions and run on Android

Expected behavior
To not run through a build error

Smartphone (please complete the following information):

  • Device: Android Studio
  • OS: Android 30
  • Version 1.0.2

Doesn't work on iOS 14 with Angular 11

Describe the bug
I upgraded my Ionic Angular project to Angular 11 and running on my iOS device stopped wotking.

To Reproduce
Steps to reproduce the behavior:

  1. Run ionic capacitor run ios -l --watch --external
  2. Click Build and run on device in XCode
  3. App crashes before being loaded

Ionic info

Ionic:

   Ionic CLI                     : 6.12.4 (/usr/local/lib/node_modules/@ionic/cli)
   Ionic Framework               : @ionic/angular 5.5.4
   @angular-devkit/build-angular : 0.1101.4
   @angular-devkit/schematics    : 11.1.4
   @angular/cli                  : 11.1.4
   @ionic/angular-toolkit        : 3.0.0

Capacitor:

   Capacitor CLI   : 2.4.0
   @capacitor/core : 2.4.0

Utility:

   cordova-res (update available: 0.15.3) : 0.15.2
   native-run (update available: 1.3.0)   : 1.2.2

System:

   NodeJS : v12.18.3 (/usr/local/Cellar/node@12/12.18.3/bin/node)
   npm    : 6.14.6
   OS     : macOS Catalina

Additional info
I tried cleaning all XCode caches, removing and recreating www and node_modules folders and nothing helped. It works on Android, the only issue is with iOS.

XCode says that the build succeeded but then it crashes on line 5 in a file AppDelegate.swift. The error message there is Thread 1: "Invalid parameter not satisfying: !stayUp || CLClientIsBackgroundable(internal->fClient) || _CFMZEnabled()".

The XCode error stack is following:

⚡️  To Native ->  BackgroundGeolocation addWatcher 74957257
2021-02-07 22:29:20.797206+0100 App[561:73313] *** Assertion failure in -[CLLocationManager setAllowsBackgroundLocationUpdates:], CLLocationManager.m:927
2021-02-07 22:29:20.797561+0100 App[561:73313] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: !stayUp || CLClientIsBackgroundable(internal->fClient) || _CFMZEnabled()'
*** First throw call stack:
(0x194d89114 0x1a8625cb4 0x194c98308 0x195f802c8 0x19a8941c4 0x101021e4c 0x1010221e0 0x10108bdb8 0x10108d5fc 0x10109ba6c 0x194d08c30 0x194d030e8 0x194d02200 0x1aae7f598 0x1975cbbcc 0x1975d11a0 0x100ddb6ec 0x1949e1588)
libc++abi.dylib: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: !stayUp || CLClientIsBackgroundable(internal->fClient) || _CFMZEnabled()'
terminating with uncaught exception of type NSException
(lldb) 

Let me know if you need any more info or see any obivous mistakes on my side.

Thanks,
Patrik

Cannot find module "@capacitor/core/dist/esm/core-plugin-definitions"

Describe the bug
I use Capacitor v3 and got this error

Error: node_modules/@capacitor-community/background-geolocation/definitions.d.ts:1:26 - error TS2307: Cannot find module '@capacitor/core/dist/esm/core-plugin-definitions' or its corresponding type declarations. import {CallbackID} from "@capacitor/core/dist/esm/core-plugin-definitions";

I notice CallbackID is deprecated now. And you must import it from '@capacitor/core/types'

Create typescript definitions

Hi @diachedelic,

Thanks for implementing the iOS part for background geolocation that was missing in the original package that you forked. I tested it on both platforms and it seems to be working great so far. The latest distanceFilter addition should help with a battery drainage. It seems a lot better and simpler than other alternatives.

It would be great if the project contained typescript definitions. I'm sure it would be helpful to many people. Could you take a look at that? The original package had that covered here: https://github.com/seididieci/capacitor-backround-geolocation/search?l=typescript

Cheers,
Patrik

`backgroundMessage` and `backgroundTitle` and custom icon has no effect on notification

Describe the bug
Passing backgroundMessage and backgroundTitle to addWatcher has no effect (does not change strings on the actual notification.) Also, the specified <string> (capacitor_background_geolocation_notification_icon) does not change the actual icon used. Also, touching the notification does NOT bring the app to foreground - instead it goes to app settings in the system UI.

To Reproduce
Steps to reproduce the behavior:

  1. Install version 1.0.3 (latest from npm)
  2. Call .addWatcher with custom backgroundMessage and backgroundTitle screens. Set strings.xml with custom icon
  3. Put app in background
  4. Check notification - see strings aren't set and icon is not set.
  5. Touch the notification - see it goes to App Settings in System UI, not the actual app

Expected behavior
Title and body of notification should match strings given in item 2 above. Icon should batch documented icon in strings.xml. Touching the notification should open the app (bring to foreground)

Screenshots
Available on request

Desktop (please complete the following information):
N/A

Smartphone (please complete the following information):

  • Device: Google Pixel 5
  • OS: latest
  • Browser: Chrome
  • Version: Latest

Additional context
On request

Capacitor 3 not registering pluging automatically

Describe the bug
I have upgraded from capacitor 2 to capacitor 3 . The issue I am facing on both plugins push notifications and background geolocation . Getting same error that is “Plugin not implemented for android”

According to the docs it should automatically register in MainActivity.java file but that is not happening I have to remove init method from that file

package siloc.xyz;

import android.os.Bundle;

import com.getcapacitor.BridgeActivity;
import com.getcapacitor.Plugin;

import java.util.ArrayList;
import com.hemangkumar.capacitorgooglemaps.CapacitorGoogleMaps;
import com.getcapacitor.community.bglocation.BackgroundGeolocation;
public class MainActivity extends BridgeActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
}

}

To Reproduce
I upgraded from capacitor 2 to capacitor 3

Expected behavior
It suppose to register these plugins

Screenshots
If applicable, add screenshots to help explain your problem.

Smartphone (please complete the following information):
vivo v2029

setting distance filter when a gps already run

Can be really useful a function to set the distance filter. I need to set it using the speed parameter:

More speed = mode distance filter
less speed = less distance filter

You can do it in 2 ways:

  1. permitting to pass to distance filter a function that must return a number
  2. an external function setDistanceFilter to set the parameter when user need to do it

Error: "BackgroundGeolocation" plugin is not implemented on android

Describe the bug
Starting the geolocation i recive in Logcat this error

E/Capacitor/Console: File: http://localhost/static/js/4.b5a04f7e.chunk.js - Line 2 - Msg: Uncaught (in promise) Error: "BackgroundGeolocation" plugin is not implemented on android

To Reproduce
Follow your step to install it and this howto to solve a compilation problem

Smartphone (please complete the following information):

  • OS: Android 30

Add support for web location tracking

Is your feature request related to a problem? Please describe.
There is no reason why this plugin is not supporting browser location tracking via service worker as well

Describe the solution you'd like
If a user is using capacitor app in a browser, user should be able to give permission to track location to the application. If permission is granted, service worker continues collecting locations in the background.

Describe alternatives you've considered
This is a standard so no need for alternatives

Additional context
iOS Safari supports this only while app is used. Soon it may add support for service worker background updates too.

Not receiving location on a specific device

Describe the bug
I have migrated from mauron85's cordova plugin to this one. I tested the app in virtual device with Android 11 and it worked well. But when I tested it on a physical device (previously working with the app), it says "Google Play Store is missing".

Other apps on this device work well with location.
Other devices with this app work well.
This error occurs even after OS reinstall.

I don't really think it is a bug, but I don't have any other idea what could cause it. I think it's something with the UnifiedNlp (microG), but I am not really experienced in this area. Do you have any suggestions?

To Reproduce

  1. Subscribe to location updates
  2. The location won't be ever given and logcat says W/GooglePlayServicesUtil: Google Play Store is missing.

Smartphone (please complete the following information):

  • Device: Sony E5823
  • OS: Android 11 (LineageOS with Play store and UnifiedNlp)

Unable to removeWatcher, missing ID.

This is the error I'm receiving in my Logcat: Line 1 - Msg: Unhandled Promise rejection: Missing id. ; Zone: <root> ; Task: null ;

I'm having trouble removing the watcher on Android (Pixel 4) - I am not using the const id = approach, because I start at one method & end at another method.

Variable declaration at the class level:

clockedOnId: any;

Then in my start method:

this.clockedOnId = BackgroundGeolocation.addWatcher({...

I have attempted several approaches:

Plugins.BackgroundGeolocation.removeWatcher(`${that.clockedOnId}`);
// Plugins.BackgroundGeolocation.removeWatcher(that.clockedOnId);
// BackgroundGeolocation.removeWatcher(that.clockedOnId);

None of which work on Android. On Apple all appears to be well, but it's harder to tell without the notification sitting in the notification tray. Closing the app seems to be the only desired result.

Any assistance will be appreciated.

Cannot read property 'addWatcher' of undefined

I'm developing an ionic app with React and capacitor (v2).

Installed this plugin as Readme said. Imported like:

 import {Plugins} from "@capacitor/core";
const {BackgroundGeolocation} = Plugins;

and used as:

this.watcher_id = BackgroundGeolocation.addWatcher(
            {
                backgroundTitle: "Tracking...",
                requestPermissions: false,
                stale: false,
            },
            (location, geolocationError) => {
                if (geolocationError) {
                    console.log("getting geolocation error", geolocationError);
                    this.setState({
                        lastCoords: null,
                        errorMessage: geolocationError.message,
                    });
                } else {
                    console.log("getting geolocation", location);
                    this.setState(prevState => {
                        return {
                            isLocationFound: true,
                            points: [...prevState.points, location],
                            lastCoords: location,
                            errorMessage: null,
                        };
                    });
                }
            }
        );

But I get this in execution:

capacitor-runtime.js:358 TypeError: Cannot read property 'addWatcher' of undefined
at n.value (main.b2f4cf63.chunk.js:1)
at n. (main.b2f4cf63.chunk.js:1)
at fo (4.cef1bb18.chunk.js:2)
at ps (4.cef1bb18.chunk.js:2)
at Du (4.cef1bb18.chunk.js:2)
at t.unstable_runWithPriority (4.cef1bb18.chunk.js:2)
at Ui (4.cef1bb18.chunk.js:2)
at Tu (4.cef1bb18.chunk.js:2)
at mu (4.cef1bb18.chunk.js:2)
at 4.cef1bb18.chunk.js:2

I think is related with issue #17 but it was closed without answer...

Multiple / Single background watchers behaviour

Hello,
Thanks for the plug-in. I am using it for my app and is working as expected. I have few questions:

  • Should I add only one watcher and remove that watcher using watcher_id when user logs out? As I do not want location updates when user logs out.
  • when adding multiple watcher, does all of the watcher gets invoked when location is changed?
  • what is the lifecycle of watcher does it last indefinitely? If not how those watchers are removed?

Thanks.
Kunal.

Save Battery - Check location every X seconds

Is your feature request related to a problem? Please describe.
The background geolocation drains too much battery.

Describe the solution you'd like
I would like to have an option to check the background geolocation every X seconds in order to save battery.

Is there any way I can achieve this? Is there any way I can make the plugin drain less battery power? Am I missing something?

Thank-you!

background location stops broadcasting after five minutes

Describe the bug
I am trying to share currrent location of user through pusher it works fine when app is open but when i minimize the app. after 5 minutes . it stops working . but the thing is I can see location get change when app is in background through devtool console. App remains alive when it is minimize . Foreground service is also running but still can't share location .. When app is minimize it seems like all the locations are added in queue. when i open app it start sending all queue locations .
I also tried https request instead of pusher that also stops after 5 minutes
here is the code.

   BackgroundGeolocation.addWatcher(
    {
        // If the "backgroundMessage" option is defined, the watcher will
        // provide location updates whether the app is in the background or the
        // foreground. If it is not defined, location updates are only
        // guaranteed in the foreground. This is true on both platforms.

        // On Android, a notification must be shown to continue receiving
        // location updates in the background. This option specifies the text of
        // that notification.
        backgroundMessage: "Requerido para el rastreo en tiempo real",

        // The title of the notification mentioned above. Defaults to "Using
        // your location".
        backgroundTitle: "Rastreo Siloc",

        // Whether permissions should be requested from the user automatically,
        // if they are not already granted. Defaults to "true".
        requestPermissions: true,

        // If "true", stale locations may be delivered while the device
        // obtains a GPS fix. You are responsible for checking the "time"
        // property. If "false", locations are guaranteed to be up to date.
        // Defaults to "false".
        stale: false,
        // The minimum number of metres between subsequent locations. Defaults
        // to 0.
        distanceFilter: 0
    },
    (location, error)=> {
        if (error) {
            if (error.code === "NOT_AUTHORIZED") {
                if (window.confirm(
                    "Esta app necesita acceso a tu ubicación" +
                    "para poder mostrar las funciones necesarias al llegar a la huerta y/o báscula\n\n" +
                    "¿Abrir ajustes ahora?"
                )) {
                    // It can be useful to direct the user to their device's
                    // settings when location permissions have been denied. The
                    // plugin provides the 'openSettings' method to do exactly
                    // this.
                    BackgroundGeolocation.openSettings();
                }
            }
            return console.error(error);
        }

   // console.log("Got new location", location);
        this.subscribe(location.longitude, location.latitude);
        let user = TokenService.getUserInfo();
        const work_order_id = TokenService.getWorkOrder();
        if (work_order_id != null) {
          let work_order = JSON.parse(
            this.$localStorage.get(`work_order_${work_order_id}`)
          );
          if (user != null && work_order?.status == 8) {
            // delivery reached
            var delivery_longitude = 0;
            var delivery_latitude = 0;
            if (work_order?.fruit_delivery_location == "Empaque") {
              delivery_latitude = Number(
                work_order?.packaging_company_details?.packaging_companies
                  ?.latitude
              );
              delivery_longitude = Number(
                work_order?.packaging_company_details?.packaging_companies
                  ?.longitude
              );
            } else {
              delivery_latitude = Number(work_order?.delivery_latitude);
              delivery_longitude = Number(work_order?.delivery_longitude);
            }

            var distance = this.checkDistance(
              delivery_latitude,
              delivery_longitude,
              location.latitude,
              location.longitude,
              "K"
            );

            if (distance <= 1) {
              if (work_order.status == 8) {
                this.markOrderComplete(work_order.id);
                this.downloadWorkOrders();
              }
            }
            //delivery reached
          }
        }

        return 0;
    }
).then(function after_the_watcher_has_been_added() {

    // When a watcher is no longer needed, it should be removed by calling
    // 'removeWatcher' with an object containing its ID.
    // BackgroundGeolocation.removeWatcher({
    //     id: watcher_id
    // });
});


To Reproduce
install package then minimize the app

Expected behavior
it should share the location when app is close. I checked that pusher is also remain connected . when app is minmize .

Desktop (please complete the following information):
windows 11

Smartphone (please complete the following information):
android 10,9

Additional context
I also tried to disable battery optimize and and webview.. but still no success

Background location doesn't update on Android 11

Describe the bug
Hello,
First of all, thanks for all your work on this plugin.

I have a small app, with a background geolocation working fine until I switch to Android 11.
After further tests, it's always working on Android 8,9,10 but Android 11 it's doesn't update location when app is in Background.

It's seem link to this isssue / the need of ACCESS_BACKGROUND_LOCATION for Android 11 and above.
https://stackoverflow.com/questions/62483266/location-updates-in-android-11

https://developer.android.com/training/location/permissions

Does someone have any clue on this or trick ?

Thanks

Unable to get location on non GMS devices

Describe the bug
It is unable to get locations on non-GMS devices.

To Reproduce
Steps to reproduce the behavior:

  1. Install the app on a emulator or device with no GMS
  2. Monitor the on location event

Expected behavior
Locations should be available on all devices with GPS.

Smartphone (please complete the following information):

  • Device: Zebra TC25
  • OS: Android 8.1
  • Browser: ionic

So I basically moved over from cordova mauron85's plugin. I migrated the entire project from cordova to capacitor with a new generate ionic app. I also implemented the capactior Geolocation plugin. The Geolocation plugin clearly logged that without GMS the plugin cannot work.

I was just wondering is it possible to use the plugin without GMS services? I noticed that transistorsoft's plugin also requires GMS. Has things changed that location plugin needs to utilise GMS API to fetch locations?

As this plugin is fairly light weight, would it be possible to add support for devices without GMS?

In addition, would you like to open a donation channel so people use this plugin can at least financially help maintaining this repo?

App crashes on Android 12 (SDK 31) devices

Describe the bug
The app crashes after calling the BackgroundGeolocation.addWatcher.

To Reproduce
Steps to reproduce the behavior:

  1. Simply use this plugin on a device that runs on Android 12 (SDK 31).
  2. The app will automatically crash after calling BackgroundGeolocation.addWatcher and gives the following error:
Error Message

2022-02-02 09:18:34.185 4220-4289/com.bundleid.example E/Capacitor: Serious error executing plugin java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at com.getcapacitor.PluginHandle.invoke(PluginHandle.java:121) at com.getcapacitor.Bridge.lambda$callPluginMethod$0$Bridge(Bridge.java:592) at com.getcapacitor.-$$Lambda$Bridge$25SFHybyAQk7zS27hTVXh2p8tmw.run(Unknown Source:8) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loopOnce(Looper.java:201) at android.os.Looper.loop(Looper.java:288) at android.os.HandlerThread.run(HandlerThread.java:67) Caused by: java.lang.IllegalArgumentException: com.bundleid.example: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent. 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. at android.app.PendingIntent.checkFlags(PendingIntent.java:375) at android.app.PendingIntent.getActivityAsUser(PendingIntent.java:458) at android.app.PendingIntent.getActivity(PendingIntent.java:444) at android.app.PendingIntent.getActivity(PendingIntent.java:408) at com.equimaps.capacitor_background_geolocation.BackgroundGeolocation.addWatcher(BackgroundGeolocation.java:121) ... 9 more

--------- beginning of crash

2022-02-02 09:18:34.200 4220-4289/com.bundleid.example E/AndroidRuntime: FATAL EXCEPTION: CapacitorPlugins
Process: com.bundleid.example, PID: 4220
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at com.getcapacitor.Bridge.lambda$callPluginMethod$0$Bridge(Bridge.java:601)
at com.getcapacitor.-$$Lambda$Bridge$25SFHybyAQk7zS27hTVXh2p8tmw.run(Unknown Source:8)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.os.HandlerThread.run(HandlerThread.java:67)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at com.getcapacitor.PluginHandle.invoke(PluginHandle.java:121)
at com.getcapacitor.Bridge.lambda$callPluginMethod$0$Bridge(Bridge.java:592)
at com.getcapacitor.-$$Lambda$Bridge$25SFHybyAQk7zS27hTVXh2p8tmw.run(Unknown Source:8) 
at android.os.Handler.handleCallback(Handler.java:938) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loopOnce(Looper.java:201) 
at android.os.Looper.loop(Looper.java:288) 
at android.os.HandlerThread.run(HandlerThread.java:67) 
Caused by: java.lang.IllegalArgumentException: com.bundleid.example: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
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.
at android.app.PendingIntent.checkFlags(PendingIntent.java:375)
at android.app.PendingIntent.getActivityAsUser(PendingIntent.java:458)
at android.app.PendingIntent.getActivity(PendingIntent.java:444)
at android.app.PendingIntent.getActivity(PendingIntent.java:408)
at com.equimaps.capacitor_background_geolocation.BackgroundGeolocation.addWatcher(BackgroundGeolocation.java:121)
... 9 more

Expected behavior
It should successfully get the current GPS location data

Desktop (please complete the following information):

  • OS: [MacBook Pro: macOS Monterey]
  • Version [12.2]

Smartphone (please complete the following information):

  • Device: [Samsung Galaxy A52s 5G]
  • OS: [Android 12 (SDK 31)]

Additional information
Using a simulator with Android 12 also crashes

Simulator specs

Name: Samsung-FMAP_API_31

CPU/ABI: Intel Atom (x86_64)

Path: /Users/ericaig/.android/avd/Samsung-FMAP_API_31.avd

Target: default [Default Android System Image] (API level 31)

Skin: 1080x2400

fastboot.chosenSnapshotFile:

runtime.network.speed: full

hw.accelerometer: yes

hw.device.name: Samsung-FMAP

hw.lcd.width: 1080

hw.initialOrientation: Portrait

image.androidVersion.api: 31

tag.id: default

hw.mainKeys: no

hw.camera.front: emulated

avd.ini.displayname: Samsung-FMAP API 31

hw.gpu.mode: auto

hw.ramSize: 1536

PlayStore.enabled: false

fastboot.forceColdBoot: no

hw.cpu.ncore: 4

hw.keyboard: yes

hw.sensors.proximity: yes

hw.dPad: no

hw.lcd.height: 2400

vm.heapSize: 256

skin.dynamic: yes

hw.device.manufacturer: User

hw.gps: yes

skin.path.backup: _no_skin

hw.audioInput: yes

image.sysdir.1: system-images/android-31/default/x86_64/

showDeviceFrame: no

hw.camera.back: virtualscene

AvdId: Samsung-FMAP_API_31

hw.lcd.density: 480

hw.arc: false

hw.device.hash2: MD5:---

fastboot.forceChosenSnapshotBoot: no

fastboot.forceFastBoot: yes

hw.trackBall: no

hw.battery: yes

hw.sdCard: yes

tag.display: Default Android System Image

runtime.network.latency: none

disk.dataPartition.size: 800M

hw.sensors.orientation: yes

avd.ini.encoding: UTF-8

hw.gpu.enabled: yes

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.