Giter Site home page Giter Site logo

transistorsoft / cordova-background-geolocation-lt Goto Github PK

View Code? Open in Web Editor NEW
657.0 36.0 277.0 645.97 MB

The most sophisticated background location-tracking & geofencing module with battery-conscious motion-detection intelligence for iOS and Android.

Home Page: http://www.transistorsoft.com/shop/products/cordova-background-geolocation

License: Other

JavaScript 21.27% Objective-C 50.72% Java 14.25% Shell 0.57% TypeScript 2.89% HTML 0.03% C++ 10.27%
ionic cordova background-location background-geolocation background location-tracking

cordova-background-geolocation-lt's Introduction

Cordova Background Geolocation Β· npm npm


πŸ†• πŸ›‘ Capacitor version now available! See capacitor-background-geolocation πŸ›‘


The most sophisticated background location-tracking & geofencing module with battery-conscious motion-detection intelligence for iOS and Android.

The plugin's Philosophy of Operation is to use motion-detection APIs (using accelerometer, gyroscope and magnetometer) to detect when the device is moving and stationary.

  • When the device is detected to be moving, the plugin will automatically start recording a location according to the configured distanceFilter (meters).

  • When the device is detected be stationary, the plugin will automatically turn off location-services to conserve energy.

Also available for Capacitor, React Native, Flutter.


The Android plugin requires purchasing a license. However, it will work for DEBUG builds. It will not work with RELEASE builds without purchasing a license.

(2018) This plugin is supported full-time and field-tested daily since 2013.


Home Settings

Contents

πŸ”· Installing the plugin

⚠️ After installing the plugin, you must Configure the Plugin for both iOS & Android. :warning: Cocoapods >= 1.10.0 is required.

$ pod --version
// if < 1.10.0
$ sudo gem install cocoapods
  • From npm

$ cordova plugin add cordova-background-geolocation-lt
  • Ionic

$ ionic cordova plugin add cordova-background-geolocation-lt
  • Capacitor

npm install cordova-background-geolocation-lt
npx cap sync

ℹ️ See Capacitor Setup

  • Phonegap Build

  <plugin name="cordova-background-geolocation-lt" source="npm">

  </plugin>

From master (latest, greatest.)

$ cordova plugin add https://github.com/transistorsoft/cordova-background-geolocation-lt.git

πŸ”· Configuring the plugin

Android

  • Open config.xml: Add the following namespace attribute to the top-level <widget> element:
<widget
  id="com.foo.bar"
  version="1.0.0"
  xmlns="http://www.w3.org/ns/widgets"
+ xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:cdv="http://cordova.apache.org/ns/1.0">
  • Within the <platform name="android"> container, add the license key using a <config-file /> element:
  • ℹ️ If you haven't yet purchased a license, you can skip this step β€” the plugin is fully functional in DEBUG builds without a license so you can try before you buy. You will see a Toast message "License Validation Failure" when your app boots β€” ignore it.
<platform name="android">
      <!-- Cordova Background Geolocation License -->
      <config-file parent="/manifest/application" target="app/src/main/AndroidManifest.xml">
          <meta-data
            android:name="com.transistorsoft.locationmanager.license"
            android:value="YOUR_LICENSE_KEY_HERE" />
      </config-file>
</platform>

Polygon Geofencing Add-on

If you've purchased a license for the Polygon Geofencing add-on, add the following license key to your AndroidManifest (Polygon Geofencing is fully functional in DEBUG builds so you can try before you buy):

<platform name="android">
      <!-- Cordova Background Geolocation License -->
      <config-file parent="/manifest/application" target="app/src/main/AndroidManifest.xml">
          <meta-data
            android:name="com.transistorsoft.locationmanager.polygon.license"
            android:value="YOUR_POLYGON_LICENSE_KEY_HERE" />
      </config-file>
</platform>

Huawei Mobile Services (HMS) Support

If you've purchased an HMS Background Geolocation License for installing the plugin on Huawei devices without Google Play Services installed, add your HMS Background Geolocation license key:

<platform name="android">
      <!-- Cordova Background Geolocation License -->
      <config-file parent="/manifest/application" target="app/src/main/AndroidManifest.xml">
          <meta-data
            android:name="com.transistorsoft.locationmanager.license"
            android:value="YOUR_LICENSE_KEY_HERE" />
      </config-file>
      <!-- HMS Background Geolocation License -->
      <config-file parent="/manifest/application" target="app/src/main/AndroidManifest.xml">
          <meta-data
            android:name="com.transistorsoft.locationmanager.hms.license"
            android:value="YOUR_HMS_LICENSE_KEY_HERE" />
      </config-file>
</platform>

⚠️ Huawei HMS support requires cordova-background-geolocation >= 3.11.0.

AlarmManager "Exact Alarms" (optional)

The plugin uses AlarmManager "exact alarms" for precise scheduling of events (eg: Config.stopTimeout, Config.motionTriggerDelay, Config.schedule). Android 14 (SDK 34), has restricted usage of "AlarmManager exact alarms". To continue using precise timing of events with Android 14, you can manually add this permission to your AndroidManifest. Otherwise, the plugin will gracefully fall-back to "in-exact AlarmManager scheduling". For more information about Android's AlarmManager, see the Android API Docs.

πŸ“‚ In your config.xml, add the following block within the <platform name="android"> block (exactly as-shown:

  <platform name="android">
      <config-file parent="/manifest" target="app/src/main/AndroidManifest.xml">
          <uses-permission android:minSdkVersion="34" android:name="android.permission.USE_EXACT_ALARM" />
      </config-file>
  </platform>

⚠️ It has been announced that Google Play Store has plans to impose greater scrutiny over usage of this permission (which is why the plugin does not automatically add it).

AndroidX (cordova-android >= 9.0.0)

It's highly recommended to configure your app for Android X when using Cordova 10 / cordova-android >= 9.0.0.

<platform name="android">
        <preference name="AndroidXEnabled" value="true" />
        .
        .
        .
</platform>

⚠️ If you see the following error, you need to configure your app for Android X.

java.lang.RuntimeException: Unable to get provider com.transistorsoft.locationmanager.util.LogFileProvider: java.lang.ClassNotFoundException

⚠️ On older version of Cordova, If you change your license key after building android, you might receive an error:

BUILD FAILED in 1s

-Element meta-data#com.transistorsoft.locationmanager.license at AndroidManifest.xml duplicated
-with element declared at AndroidManifest.xml duplicated with element declared at AndroidManifest.xml

Simply remove and re-add the android platform:

$ cordova platform remove android
$ cordova platform add android

Android Gradle Dependency Configuration.

Quite often, other 3rd-party plugins will require the same dependencies used by background-geolocation, including:

  • play-services:location
  • com.android.support libraries
  • okhttp (Android HTTP library)

If your app requests different versions of these dependencies, it can cause a build-failure (See wiki Solving Build Failures). Background Geolocation exposes the following Android CLI configuration --variable to help you align the required dependency versions with other plugins:

Cordova CLI --variable are used as follows:

❗ To apply changes to these --variable, you must remove/re-add the cordova platform(s)

$ cordova plugin add cordova-background-geolocation-lt --variable FOO=value_foo --variable BAR=value_bar

// After adding --variable, remove and re-add the platform
$ cordova platform remove android
$ cordova platform add android
@variable GOOGLE_API_VERSION ["20.+"]

Sets the desired version of play-services-location dependency. Many other plugins require play-services dependencies, (eg: cordova-plugin-googlemaps, phonegap-plugin-push): If the version of play-services and/or firebase is not aligned to the same version for ALL plugins, your build will fail.

$ cordova plugin add <git-url> --variable GOOGLE_API_VERSION=20.0.0
@variable OKHTTP_VERSION ["3.12.+"]

Sets the desired version of okhttp to import. The Android plugin uses okhttp for its HTTP service. Some other plugins can also import okhttp (eg: cordova-plugin-advanced-http). If both plugins don't align themselves to the same version, your Android build will fail.

$ cordova plugin add cordova-background-geolocation-lt --variable OKHTTP_VERSION=3.12.+

iOS

iOS requires a number of "Usage Strings" for location and motion-usage authorization. iOS will render these strings upon the dialog used to request permission from the user. Take care to write relevent descriptions of why your app requires these authorizations as they can affect whether Apple accepts your app or not.

Paste all the following elements into the <platform name="ios"> container:

<platform name="ios">
    <!-- background-geolocation -->
    <config-file parent="NSLocationAlwaysAndWhenInUseUsageDescription" target="*-Info.plist">
        <string>[CHANGEME] Background location tracking is required for our app so we can...</string>
    </config-file>
    <config-file parent="NSLocationAlwaysUsageDescription" target="*-Info.plist">
        <string>[CHANGEME pre-iOS11.  No longer used with iOS 12] Background location tracking is required for our app so we can...</string>
    </config-file>
    <config-file parent="NSLocationWhenInUseUsageDescription" target="*-Info.plist">
        <string>[CHANGEME] Background location tracking is required for our app so we can...</string>
    </config-file>
    <config-file parent="NSMotionUsageDescription" target="*-Info.plist">
        <string>[CHANGEME] Device motion updates help determine when the device is stationary so the app can save power by turning off location-updates</string>
    </config-file>
    <!-- /background-geolocation -->
</platform>

Privacy Manifest

Apple now requires apps provide a Privacy Manifest for "sensitive" APIs which could be abused for "fingerprinting" a user for malicious marketing activity.

⚠️ You MUST upgrade your cordova-ios platform to >= 7.1.0 for iOS Privacy Manifest Support:

  • πŸ“‚ config.xml
  • Add the following <privacy-manifest> four block within the NSPrivacyAccessedAPITypes container:
  <platform name="ios">
      <privacy-manifest>
          <key>NSPrivacyAccessedAPITypes</key>
          <array>
              <!-- [1] cordova-background-fetch: UserDefaults -->
              <dict>
                  <key>NSPrivacyAccessedAPIType</key>
                  <string>NSPrivacyAccessedAPICategoryUserDefaults</string>

                  <key>NSPrivacyAccessedAPITypeReasons</key>
                  <array>
                      <string>CA92.1</string>
                  </array>
              </dict>

              <!-- [2] cordova-background-geolocation: UserDefaults -->
              <dict>
                  <key>NSPrivacyAccessedAPIType</key>
                  <string>NSPrivacyAccessedAPICategoryUserDefaults</string>

                  <key>NSPrivacyAccessedAPITypeReasons</key>
                  <array>
                      <string>CA92.1</string>
                      <string>1C8F.1</string>
                  </array>
              </dict>
              <!-- [3] cordova-background-geolocation (CocoaLumberjack): FileTimestamp -->
              <dict>
                  <key>NSPrivacyAccessedAPIType</key>
                  <string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
                  <key>NSPrivacyAccessedAPITypeReasons</key>
                  <array>
                      <string>C617.1</string>
                      <string>0A2A.1</string>
                  </array>
              </dict>
              <!-- [4] cordova-background-geolocation (CocoaLumberjack): DiskSpace -->
              <dict>
                  <key>NSPrivacyAccessedAPIType</key>
                  <string>NSPrivacyAccessedAPICategoryDiskSpace</string>
                  <key>NSPrivacyAccessedAPITypeReasons</key>
                  <array>
                      <string>E174.1</string>
                  </array>
              </dict>
          </array>
      </privacy-manifest>
  </platform>

Configuring for useSignificantChangesOnly

For those using useSignificantChangesOnly: true, possibly because Apple denied your use of the background location capability, you can disable background location by providing the BACKGROUND_MODE_LOCATION --variable with an empty-string:

$ cordova plugin add cordova-background-geolocation-lt --variable BACKGROUND_MODE_LOCATION=""

$ cordova platform remove ios
$ cordova platform add ios

πŸ”· Using the Plugin

There are three simple steps to using BackgroundGeolocation:

  1. Listen to events.
  2. #ready the plugin.
  3. #start the plugin.

Ionic 2+ with Typescript

The plugin hosts its own Typescript API:

Sample Implementation

// You may import any optional interfaces
import BackgroundGeolocation, {
  State,
  Config,
  Location,
  LocationError,
  Geofence,
  HttpEvent,
  MotionActivityEvent,
  ProviderChangeEvent,
  MotionChangeEvent,
  GeofenceEvent,
  GeofencesChangeEvent,
  HeartbeatEvent,
  ConnectivityChangeEvent
} from "cordova-background-geolocation-lt";

class HomeView {
  .
  .
  .
  // Like any Cordova plugin, you must wait for Platform.ready() before referencing the plugin.
  configureBackgroundGeolocation() {
    // 1.  Listen to events.
    BackgroundGeolocation.onLocation(location => {
      console.log('[location] - ', location);
    });

    BackgroundGeolocation.onMotionChange(event => {
      console.log('[motionchange] - ', event.isMoving, event.location);
    });

    BackgroundGeolocation.onHttp(response => {
      console.log('[http] - ', response.success, response.status, response.responseText);
    });

    BackgroundGeolocation.onProviderChange(event => {
      console.log('[providerchange] - ', event.enabled, event.status, event.gps);
    });

    // 2.  Configure the plugin with #ready
    BackgroundGeolocation.ready({
      reset: true,
      debug: true,
      logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
      desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
      distanceFilter: 10,
      url: 'http://my.server.com/locations',
      autoSync: true,
      stopOnTerminate: false,
      startOnBoot: true
    }, (state) => {
      console.log('[ready] BackgroundGeolocation is ready to use');
      if (!state.enabled) {
        // 3.  Start tracking.
        BackgroundGeolocation.start();
      }
    });
  }
}

Cordova / Ionic 1

// Like any Cordova plugin, you must wait for deviceready before referencing the plugin.
function onDeviceReady() {
  // 1.  Listen to events
  var bgGeo = window.BackgroundGeolocation;

  bgGeo.onLocation(function(location) {
    console.log('[location] -', location);
  });

  bgGeo.onMotionChange(function(event) {
    console.log('[motionchange] -', event.isMoving, event.location);
  });

  bgGeo.onHttp(function(response) {
    console.log('[http] - ', response.success, response.status, response.responseText);
  });

  bgGeo.onProviderChange(function(event) {
    console.log('[providerchange] -', event.status, event.enabled, event.gps, event.network);
  });

  // 2. Execute #ready method:
  bgGeo.ready({
    reset: true,
    debug: true,
    logLevel: bgGeo.LOG_LEVEL_VERBOSE,
    desiredAccuracy: bgGeo.DESIRED_ACCURACY_HIGH,
    distanceFilter: 10,
    url: 'http://my.server.com/locations',
    autoSync: true,
    stopOnTerminate: false,
    startOnBoot: true
  }, function(state) {    // <-- Current state provided to #configure callback
    // 3.  Start tracking
    console.log('BackgroundGeolocation is configured and ready to use');
    if (!state.enabled) {
      bgGeo.start().then(function() {
        console.log('- BackgroundGeolocation tracking started');
      });
    }
  });

  // NOTE:  Do NOT execute any API methods which will access location-services
  // until the callback to #ready executes!
  //
  // For example, DO NOT do this here:
  //
  // bgGeo.getCurrentPosition();   // <-- NO!
  // bgGeo.start();                // <-- NO!
}

ℹ️ NOTE: The configuration {} provided to the #ready method is applied only when your app is first booted β€” for every launch thereafter, the plugin will automatically load the last known configuration from persistant storage. If you wish to force the #ready method to always apply the supplied config {}, you can specify reset: true

BackgroundGeolocation.ready({
  reset: true,  // <-- true to always apply the supplied config
  distanceFilter: 10
}, function(state) {
  console.log('- BackgroundGeolocation is ready: ', state);
});

⚠️ Do not execute any API method which will require accessing location-services until the callback to #ready executes (eg: #getCurrentPosition, #watchPosition, #start).

Promise API

The BackgroundGeolocation Javascript API supports Promises for nearly every method (the exceptions are #watchPosition and adding event-listeners (eg: #onLocation). For more information, see the API Documentation

// Traditional API still works:
BackgroundGeolocation.ready({desiredAccuracy: 0, distanceFilter: 50}).then(state => {
  console.log('- BackgroundGeolocation is ready: ', state);
}).catch(error => {
  console.log('- BackgroundGeolocation error: ', error);
});

A fully-featured SampleApp is available in its own public repo. After first cloning that repo, follow the installation instructions in the README there. This SampleApp includes a settings-screen allowing you to quickly experiment with all the different settings available for each platform.

If you're using XCode, boot the SampleApp in the iOS Simulator and enable Debug->Location->Freeway Drive.

πŸ”· Simple Testing Server

A simple Node-based web-application with SQLite database is available for field-testing and performance analysis. If you're familiar with Node, you can have this server up-and-running in about one minute.

Licence

cordova-background-geolocation
Copyright (c) 2018, Transistor Software (9224-2932 Quebec Inc)
All rights reserved.
[email protected]
http://transistorsoft.com
  1. Preamble: This Agreement governs the relationship between YOU OR THE ORGANIZATION ON WHOSE BEHALF YOU ARE ENTERING INTO THIS AGREEMENT (hereinafter: Licensee) and Transistor Software, a LICENSOR AFFILIATION whose principal place of business is Montreal, Quebec, Canada (Hereinafter: Licensor). This Agreement sets the terms, rights, restrictions and obligations on using [{software}] (hereinafter: The Software) created and owned by Licensor, as detailed herein

  2. License Grant: Licensor hereby grants Licensee a Personal, Non-assignable & non-transferable, Commercial, Royalty free, Including the rights to create but not distribute derivative works, Non-exclusive license, all with accordance with the terms set forth and other legal restrictions set forth in 3rd party software used while running Software.

    2.1 Limited: Licensee may use Software for the purpose of: - Running Software on Licensee's Website[s] and Server[s]; - Allowing 3rd Parties to run Software on Licensee's Website[s] and Server[s]; - Publishing Software’s output to Licensee and 3rd Parties; - Distribute verbatim copies of Software's output (including compiled binaries); - Modify Software to suit Licensee’s needs and specifications.

    2.2 Binary Restricted: Licensee may sublicense Software as a part of a larger work containing more than Software, distributed solely in Object or Binary form under a personal, non-sublicensable, limited license. Such redistribution shall be limited to unlimited codebases.

  3. 2.3 Non Assignable & Non-Transferable: Licensee may not assign or transfer his rights and duties under this license.

    2.4 Commercial, Royalty Free: Licensee may use Software for any purpose, including paid-services, without any royalties

    2.5 Including the Right to Create Derivative Works: Licensee may create derivative works based on Software, including amending Software’s source code, modifying it, integrating it into a larger work or removing portions of Software, as long as no distribution of the derivative works is made.

  4. Term & Termination: The Term of this license shall be until terminated. Licensor may terminate this Agreement, including Licensee's license in the case where Licensee :

    3.1 became insolvent or otherwise entered into any liquidation process; or

    3.2 exported The Software to any jurisdiction where licensor may not enforce his rights under this agreements in; or

    3.3 Licensee was in breach of any of this license's terms and conditions and such breach was not cured, immediately upon notification; or

    3.4 Licensee in breach of any of the terms of clause 2 to this license; or

    3.5 Licensee otherwise entered into any arrangement which caused Licensor to be unable to enforce his rights under this License.

  5. Payment: In consideration of the License granted under clause 2, Licensee shall pay Licensor a FEE, via Credit-Card, PayPal or any other mean which Licensor may deem adequate. Failure to perform payment shall construe as material breach of this Agreement.

  6. Upgrades, Updates and Fixes: Licensor may provide Licensee, from time to time, with Upgrades, Updates or Fixes, as detailed herein and according to his sole discretion. Licensee hereby warrants to keep The Software up-to-date and install all relevant updates and fixes, and may, at his sole discretion, purchase upgrades, according to the rates set by Licensor. Licensor shall provide any update or Fix free of charge; however, nothing in this Agreement shall require Licensor to provide Updates or Fixes.

    5.1 Upgrades: for the purpose of this license, an Upgrade shall be a material amendment in The Software, which contains new features and or major performance improvements and shall be marked as a new version number. For example, should Licensee purchase The Software under version 1.X.X, an upgrade shall commence under number 2.0.0.

    5.2 Updates: for the purpose of this license, an update shall be a minor amendment in The Software, which may contain new features or minor improvements and shall be marked as a new sub-version number. For example, should Licensee purchase The Software under version 1.1.X, an upgrade shall commence under number 1.2.0.

    5.3 Fix: for the purpose of this license, a fix shall be a minor amendment in The Software, intended to remove bugs or alter minor features which impair the The Software's functionality. A fix shall be marked as a new sub-sub-version number. For example, should Licensee purchase Software under version 1.1.1, an upgrade shall commence under number 1.1.2.

  7. Support: Software is provided under an AS-IS basis and without any support, updates or maintenance. Nothing in this Agreement shall require Licensor to provide Licensee with support or fixes to any bug, failure, mis-performance or other defect in The Software.

    6.1 Bug Notification: Licensee may provide Licensor of details regarding any bug, defect or failure in The Software promptly and with no delay from such event; Licensee shall comply with Licensor's request for information regarding bugs, defects or failures and furnish him with information, screenshots and try to reproduce such bugs, defects or failures.

    6.2 Feature Request: Licensee may request additional features in Software, provided, however, that (i) Licensee shall waive any claim or right in such feature should feature be developed by Licensor; (ii) Licensee shall be prohibited from developing the feature, or disclose such feature request, or feature, to any 3rd party directly competing with Licensor or any 3rd party which may be, following the development of such feature, in direct competition with Licensor; (iii) Licensee warrants that feature does not infringe any 3rd party patent, trademark, trade-secret or any other intellectual property right; and (iv) Licensee developed, envisioned or created the feature solely by himself.

  8. Liability: To the extent permitted under Law, The Software is provided under an AS-IS basis. Licensor shall never, and without any limit, be liable for any damage, cost, expense or any other payment incurred by Licensee as a result of Software’s actions, failure, bugs and/or any other interaction between The Software Β and Licensee’s end-equipment, computers, other software or any 3rd party, end-equipment, computer or services. Moreover, Licensor shall never be liable for any defect in source code written by Licensee when relying on The Software or using The Software’s source code.

  9. Warranty:

    8.1 Intellectual Property: Licensor hereby warrants that The Software does not violate or infringe any 3rd party claims in regards to intellectual property, patents and/or trademarks and that to the best of its knowledge no legal action has been taken against it for any infringement or violation of any 3rd party intellectual property rights.

    8.2 No-Warranty: The Software is provided without any warranty; Licensor hereby disclaims any warranty that The Software shall be error free, without defects or code which may cause damage to Licensee’s computers or to Licensee, and that Software shall be functional. Licensee shall be solely liable to any damage, defect or loss incurred as a result of operating software and undertake the risks contained in running The Software on License’s Server[s] and Website[s].

    8.3 Prior Inspection: Licensee hereby states that he inspected The Software thoroughly and found it satisfactory and adequate to his needs, that it does not interfere with his regular operation and that it does meet the standards and scope of his computer systems and architecture. Licensee found that The Software interacts with his development, website and server environment and that it does not infringe any of End User License Agreement of any software Licensee may use in performing his services. Licensee hereby waives any claims regarding The Software's incompatibility, performance, results and features, and warrants that he inspected the The Software.

  10. No Refunds: Licensee warrants that he inspected The Software according to clause 7(c) and that it is adequate to his needs. Accordingly, as The Software is intangible goods, Licensee shall not be, ever, entitled to any refund, rebate, compensation or restitution for any reason whatsoever, even if The Software contains material flaws.

  11. Indemnification: Licensee hereby warrants to hold Licensor harmless and indemnify Licensor for any lawsuit brought against it in regards to Licensee’s use of The Software in means that violate, breach or otherwise circumvent this license, Licensor's intellectual property rights or Licensor's title in The Software. Licensor shall promptly notify Licensee in case of such legal action and request Licensee's consent prior to any settlement in relation to such lawsuit or claim.

  12. Governing Law, Jurisdiction: Licensee hereby agrees not to initiate class-action lawsuits against Licensor in relation to this license and to compensate Licensor for any legal fees, cost or attorney fees should any claim brought by Licensee against Licensor be denied, in part or in full.

cordova-background-geolocation-lt's People

Contributors

brianmulhall avatar christocracy avatar coderroggie avatar gnarco avatar keithdmoore avatar sadortun avatar transistorsoft-pkg 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cordova-background-geolocation-lt's Issues

BackgroundGeoLocation error Class not found

Hi,
i am using android cordova 5.0, and i get this error message.

why?

code:

// Get a reference to the plugin.
var bgGeo = window.BackgroundGeolocation;

/**
 * This callback will be executed every time a geolocation is recorded in the background.
 */
var callbackFn = function(location, taskId) {
  console.log('start location');
  var coords = location.coords;
  var lat    = coords.latitude;
  var lng    = coords.longitude;

  // Simulate doing some extra work with a bogus setTimeout.  This could perhaps be an Ajax request to your server.
  // The point here is that you must execute bgGeo.finish after all asynchronous operations within the callback are complete.
  setTimeout(function() {
    console.log('finished');
    bgGeo.finish(taskId); // <-- execute #finish when your work in callbackFn is complete
  }, 1000);
};

var failureFn = function(error) {
  console.log('BackgroundGeoLocation error', error);
}

// BackgroundGeoLocation is highly configurable.
bgGeo.configure(callbackFn, failureFn, {
  // Geolocation config
  desiredAccuracy: 0,
  stationaryRadius: 50,
  distanceFilter: 50,
  disableElasticity: false, // <-- [iOS] Default is 'false'.  Set true to disable speed-based distanceFilter elasticity
  locationUpdateInterval: 5000,
  minimumActivityRecognitionConfidence: 80,   // 0-100%.  Minimum activity-confidence for a state-change
  fastestLocationUpdateInterval: 5000,
  activityRecognitionInterval: 10000,
  stopDetectionDelay: 1,  // Wait x minutes to engage stop-detection system
  stopTimeout: 2,  // Wait x miutes to turn off location system after stop-detection
  activityType: 'AutomotiveNavigation',

  // Application config
  debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
  forceReloadOnLocationChange: false,  // <-- [Android] If the user closes the app **while location-tracking is started** , reboot app when a new location is recorded (WARNING: possibly distruptive to user)
  forceReloadOnMotionChange: false,    // <-- [Android] If the user closes the app **while location-tracking is started** , reboot app when device changes stationary-state (stationary->moving or vice-versa) --WARNING: possibly distruptive to user)
  forceReloadOnGeofence: false,        // <-- [Android] If the user closes the app **while location-tracking is started** , reboot app when a geofence crossing occurs --WARNING: possibly distruptive to user)
  stopOnTerminate: false,              // <-- [Android] Allow the background-service to run headless when user closes the app.
  startOnBoot: true,                   // <-- [Android] Auto start background-service in headless mode when device is powered-up.

  // HTTP / SQLite config
  url: globalVars.apiUrl + '/liveLocation',
  method: 'POST',
  batchSync: true,       // <-- [Default: false] Set true to sync locations to server in a single HTTP request.
  autoSync: true,         // <-- [Default: true] Set true to sync each location to server as it arrives.
  maxDaysToPersist: 1,    // <-- Maximum days to persist a location in plugin's SQLite database when HTTP fails
  headers: {
    "X-FOO": "bar"
  },
  params: {
    "auth_token": "maybe_your_server_authenticates_via_token_YES?"
  }
});

// Turn ON the background-geolocation system.  The user will be tracked whenever they suspend the app.
bgGeo.start();

Failed to fetch plugin.....

Fetching plugin "https://github.com/transistorsoft/cordova-background-geolocation.git" via git clone
Error: Failed to fetch plugin https://github.com/transistorsoft/cordova-background-geolocation.git via git.
Either there is a connection problems, or plugin spec is incorrect:
Error: git: Command failed with exit code 128 Error output:
Cloning into '/tmp/git/1448183248166'...
remote: Repository not found.
fatal: repository 'https://github.com/transistorsoft/cordova-background-geolocation.git/' not found

getCurrentPosition is failing silently

On Android, I have an app using the following code

window.BackgroundGeolocation.configure(
    function (location, taskid) {
        console.debug('Configure cb', taskid);
        window.BackgroundGeolocation.finish(taskid);
    },
    function (err) {
        console.debug('Configure error', err);
    },
    {
        desiredAccuracy: 10, // 0, 10, 100, 1000 : 0 is accurate as hell, 1000 is lazy
        distanceFilter: 20, // 10,
        stopTimeout: 5,

        // iOS
        activityType: 'OtherNavigation',
        disableElasticity: true, // try to have an constant update or else update interval will depends on speed
        stationaryRadius: 20,

        // Android
        locationUpdateInterval: 1000,
        fastestLocationUpdateInterval: 1000,
        activityRecognitionInterval: 0, // 10000,
    }
);

setInterval(function () {
    console.debug('Interval start');
    try {
        window.BackgroundGeolocation.getCurrentPosition(
            function (location, taskid) {
                console.debug('Interval yay', taskid);
                window.BackgroundGeolocation.finish(taskid);
            },
            function (err) {
                console.debug('Interval error', err);
            },
            {
                //timeout: 30,
                maximumAge: 1000,
                //minimumAccuracy: 10
            }
        );
    } catch (e) {
        console.debug('Interval catch', e);
    }
}, 1000);

The following code does :

  1. Configure plugin.
  2. Begin an interval loop.
  3. Try to getCurrentPosition every second or so.

First time the app is newly installed (or after Clear Data was done in the App setting), everything is fine. The code print every second or so :

Interval start
Interval yay
Interval start
Interval yay
Interval start
Interval yay
Interval start
Interval yay

But after a few runs (opening App, and closing it), it never get to Interval yay and never trigger any error callback or catch an error :

Interval start
Interval start
Interval start
Interval start

Am I doing something wrong?

P.S. I want foreground maximum power Position. Never tried the start() approach as it seems to only work when app is in background

Delay permissions request

Currently, the plugin prompts for background location tracking permissions as soon as the app loads. Is there a way to delay this until a later point? It would make sense for it to prompt only when the configure method is called.

Leaving stationary state on IOS

It seems that the plugin can take a long time to leave the stationary state. It is possible to configure it without the power optimisation based on motion detection ?
I mean getting data at the rate configured for motion even when the phone is stationary ?

Can't build the project on Xcode

Hi,

I'm trying to run some tests with your plugin on iOS, but I can't build it. It prompt this error:

duplicate symbol _llvm.cmdline in:
    EarthlyExplorer/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(SOMotionDetector.o)
 EarthlyExplorer/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(LocationDAO.o)

duplicate symbol _llvm.embedded.module in:
EarthlyExplorer/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(SOMotionDetector.o)
EarthlyExplorer/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(LocationDAO.o)
duplicate symbol _llvm.cmdline in:
EarthlyExplorer/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(SOMotionDetector.o)
EarthlyExplorer/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(TSReachability.o)
duplicate symbol _llvm.embedded.module in:
EarthlyExplorer/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(SOMotionDetector.o)
EarthlyExplorer/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(TSReachability.o)
duplicate symbol _llvm.cmdline in:
EarthlyExplorer/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(SOMotionDetector.o)
EarthlyExplorer/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(TSLocationManager.o)
duplicate symbol _llvm.embedded.module in:
EarthlyExplorer/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(SOMotionDetector.o)
EarthlyExplorer/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(TSLocationManager.o)
ld: 6 duplicate symbols for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

This is a bug? Or I did something wrong?

Thanks

Cordova "deviceready" event is not firing

I'm doing a very simple window.addEventListener('deviceready', initFunction); The event never fires. I'm using an angular stack, but this event listener is outside of angular. I've brought it down to be as simple as an alert in event listener callback. No dice. Note that this is the only plugin I'm using.

A minor fix in docs

Your callbackFn will be executed each time the device has changed-state between MOVING or STATIONARY. The callbackFn will be provided with a Location object as the 1st param, with the usual params (latitude, longitude, accuracy, speed, bearing, altitude), in addition to a taskId used to signal that your callback is finished.

It says Location object as the 1st param, but as we see in the code below isMoving is the first param.

bgGeo.onMotionChange(function(isMoving, location, taskId) {
    if (isMoving) {
        console.log('Device has just started MOVING', location);
    } else {
        console.log('Device has just STOPPED', location);
    }
    bgGeo.finish(taskId);
})

Low accuracy on Android

Hi,
We have an isssue about the accurracy of the locations on Android devices (for iOS it seems OK).
There are big jumps on the locations (I mean hundreds of meters).
We have tried with many combinations of settings to achieve better result.
We also tested other apps (mainly Strava) on same device and get good results. If both Strava and our app is running in the background our locations are very close to Strava’s and the accurracy is acceptable. But, when our app is running alone the number of locations decreases and some locations are far away from actual path.
We also tried your sample app (on Google Play), results are similar.

Our app is mainly used by β€œwalking”.

What are the best settings for accuracy? Do you have any suggestion? This issue is very critical for us.

Thanks,

runtine crash on android

When I run the app on android:
cordova app run native

the build goes fine but I get a runtime error (the app crashes):
01-10 17:59:53.826: E/AndroidRuntime(18721): java.lang.VerifyError: com/transistorsoft/locationmanager/a
01-10 17:59:53.826: E/AndroidRuntime(18721): at com.transistorsoft.locationmanager.BackgroundGeolocationService.onStartCommand(Unknown Source)

Do you have an idea ?

problem when only using significant changes api

I'm having trouble using only the significant changes api in iOS. This is how it is configured.

window.BackgroundGeolocation.configure(callbackFn, failureFn, {
  useSignificantChangesOnly: true,
  desiredAccuracy: 1000,
  debug: true
});

When running the app I get the following error.

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Application must support the location background mode (in app's Info.plist, {UIBackgroundModes=(location);}'

If I have understood the documentation correctly, when only using the significant change api the app shouldn't have the location background mode enabled.

getCurrentPosition callbacks not called when finish() triggered in configure(successFn)

Hi There!

Thanks for the excellent plugin.

I have an issue where getCurrentPosition callbacks (both success and failure) are not being triggered when successFn from configure(successFn) calls finish(taskId).

So for example this will never trigger getCurrentPosition callbacks:

BackgroundGeolocationService.configure(function(location, taskId)
{
    console.log('Received location.');
    BackgroundGeolocationService.finish(taskId);
});

BackgroundGeolocationService.getCurrentPosition(function(location, taskId){
      console.log('current position received');
},function(){},{});

However if we comment out the finish(taskId) in successFn like so the getCurrentPosition callbacks are triggered as expected:

BackgroundGeolocationService.configure(function(location, taskId)
{
    console.log('Received location.');
    //BackgroundGeolocationService.finish(taskId);
});

BackgroundGeolocationService.getCurrentPosition(function(location, taskId){
      console.log('current position received');
},function(){},{});

Is this expected behavior?

Thank you.

Stationary detecting

Hey, Chris! This is more of an issue of myself than the plugin, but I can't figure out what I am doing wrong. So the idea is to track people movement, and when they stop for more than given interval (10 minutes in this case, but will be different for prod), notify them about objects they passed by and when they click on the notification show their route. This is the service I've come up with to do so (nevermind $logger, I just wanted to know what happens when moving). What actually happens is that diff (line 44) never gets more than 10. I thought this happens because once stationary it stops executing $callback, then I changed stopTimeout to 15 minutes, to be more than given value of 10 min difference, but it didn't help either. Could you please tell me what I am doing wrong here. Thanks.

Support for while using mode

I'm just wondering if there is a mode where you can enable the tracker to only function while the app is in use. For some apps always is a bit overkill. I read through the docs but couldn't see anything.

Interval Settings

I've purchased a solo license, but have just been testing so far with this repo (the free iOS version). I'm using an iPhone 6S running 9.2.1.

I'm trying to reduce the frequency with which the app POSTs to my server.

Here are my config settings:
{
desiredAccuracy: 0
stationaryRadius: 50,
distanceFilter: 50,
disableElasticity: false,
locationUpdateInterval: 60000,
minimumActivityRecognitionConfidence: 80,
fastestLocationUpdateInterval: 60000,
activityRecognitionInterval: 60000,
url: [myserver],
method: 'POST',
batchSync: true,
autoSync: true,
}

My expectation was that the app would only POST to my server once every 60 seconds (since all the intervals were set to 60000). Instead, the app posted about every 7-15 seconds. The output below shows the distance and time between points logged by the server - this was in a test drive across town for a few miles using an actual device (not the simulator).

Distance: 2.895mi Time: 151sec
Distance: 11.059mi Time: 557sec
Distance: 0.161mi Time: 7sec
Distance: 0.198mi Time: 10sec
Distance: 0.202mi Time: 10sec
Distance: 0.233mi Time: 11sec
Distance: 0.065mi Time: 10sec
Distance: 1.401mi Time: 62sec
Distance: 0.166mi Time: 7sec
Distance: 0.062mi Time: 14sec
Distance: 0.432mi Time: 10sec
Distance: 0.25mi Time: 12sec
Distance: 0.231mi Time: 11sec
Distance: 0.169mi Time: 8sec
Distance: 0.021mi Time: 14sec
Distance: 0.499mi Time: 11sec
Distance: 0.227mi Time: 11sec

Am I missing something?

Error when trying to run my iOS app using the plugin

Hi,

I have included the plugin in my iOS project and when I try to run the project I get the following error.Β I really appreciate your assistance in this matter. Please let me know what other information you might need. Thanks!

2015-09-02 16:19:39.757 APP[439:39386] - TSLocationManager create database
2015-09-02 16:19:39.758 APP[439:39386] THREAD WARNING: ['BackgroundGeolocation'] took '11.715820' ms. Plugin should use a background thread.
2015-09-02 16:19:39.759 APP[439:39386] [ts-locationmanager] - start
2015-09-02 16:19:39.759 APP[439:39386] [ts-locationmanager] - setPace 0, stationaryRegion? 0
2015-09-02 16:19:39.872 APP[439:39386] THREAD WARNING: ['BackgroundGeolocation'] took '113.088135' ms. Plugin should use a background thread.
2015-09-02 16:19:39.872 APP[439:39386] [ts-locationmanager] - didChangeAuthorizationStatus 3
2015-09-02 16:19:39.881 APP[439:39386] [ts-locationmanager] - didUpdateLocations (isMoving: 0, df: -1.000000, background: 0)
2015-09-02 16:19:39.896 APP[439:39386] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* +[NSJSONSerialization dataWithJSONObject:options:error:]: value parameter is nil'
*** First throw call stack:
(0x1859682d8 0x19718c0e4 0x185968218 0x1868dcee4 0x1000b37d4 0x1000afd60 0x1000af52c 0x18590e2c4 0x18584b450 0x18677aa80 0x100022a10 0x18a63d224 0x18a633bf0 0x18e1713c8 0x18592027c 0x18591f384 0x18591d9a8 0x1858492d4 0x18f05f6fc 0x18a40efac 0x100022340 0x19780aa08)
libc++abi.dylib: terminating with uncaught exception of type NSException

"Error - The plugin in your app does not support the compulsory arm64"

Could help in this matter, I added the plugin correctly but when you build the Phonegap site only android version is compiled and get the following error in the ios platform, "Error - The plugin in your app does not support the compulsory arm64 (64- bit support) architecture. "how do I solve? other questions in this version ios plugin enables the native option monitoring gps background defined as ever? as well as the new role of facebook friends nearby? which enables the GPS function always as seen in the image below?

aways1

/-------------------------------------/

aways

Question

Hello,

I'm very interested in this, but have 3 questions before buying:

  1. If this thing is closed completely (not just suspended) can it restart itself in the background on significant changes in positioning?
  2. Does it work with iOS 6,7, 8, and 9? What is compatibility like?
  3. What kind of updates do we get if we buy? If IOS 10 is different will we get a free fix, or will we have to pay more?

Thank you!

Works well on IOS simulator, but does not work for real IOS device for me

function onDeviceReady() {
      var bgGeo = window.BackgroundGeolocation;
      bgGeo.configure(function(location, taskId) {
        var data = {
          saved: false,
          currentData: {
            "time" : $scope.time,
            "position": {
              "lat": location.coords.latitude,
              "lng": location.coords.longitude
            }
          }
        };
        setTimeout(function() {
          $scope._formatLocationData(data);
          bgGeo.finish(taskId); // <-- execute #finish when your work in callbackFn is complete
        }, 1000);
      }, function(error) {
        console.log('BackgroundGeoLocation error');
      }, {
        desiredAccuracy: 10,
        stationaryRadius: 20,
        distanceFilter: 30,
        notificationTitle: 'Background tracking', // <-- android only, customize the title of the notification
        notificationText: 'ENABLED', // <-- android only, customize the text of the notification
        activityType: 'AutomotiveNavigation',
        debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
        stopOnTerminate: false
      });

      bgGeo.start();
    }

    var frequencyMin = 1;
    $scope.intervalSend = function () {
      var d = new Date(),
        h = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), (d.getMinutes() - (d.getMinutes() % frequencyMin)) + frequencyMin, 0, 0),
        e = h - d;
      $timeout($scope.intervalSend, e);
      if (d.getSeconds() === 0) {
        $scope.time = Math.floor(d.getTime() / 1000);
        $scope.syncMyLocation($scope.time, true);
      }
    };
    $scope.intervalSend();

My project works for IOS simulator, but does not work for real IOS device.
It works on device if I keep app in front, but it does not work for background.
Is there any suggestion I can get from you? thanks.

Location: Always
Motion & Fitness: Yes
Background App Refresh: Yes
Cellular Data: Yes

Background geolocation not getting updates

I set debut to true and changePace(true) on app pause.
It's ok when I put the app in bacgkround I receive the notification saying that agressive monitoring has been engaged. Then I get updates for my location only 10 minutes later or so.
When I get a location update I receive like 8 or more notifications from plugin saying MOVING and LOCATION UPDATE... but it takes like 10 minutes after I put the app in background to get the first location update.

I dont know what I'm doing wrong!

var successFn = function(location, taskid){
   //now i removed the post method to my server in order to test in debug mode
    bgGeo.finish(taskid);
}
bgGeo.configure(successFn, function(){
    //does nothing for now
}, {
    desiredAccuracy: 10,
    distanceFilter: 20,
    stationaryRadius: 20,
    debug: true,
    stopOnTerminate: true
});

background_print

Ionic No BackgroundGeolocation on window object

I have tried everything and am pulling my hair out here. I have my code to execute inside of the block below which is supposed to be equivalent to deviceready and even when I try to manually tie to deviceready it doesn't fire.

$ionicPlatform.ready(function() {

Even when trying to pull a geolocation first and then initializing the plugin I get cannot read property 'configure' of undefined. The strange thing to me is that there is no DI. Every other plugin I use I inject first, but I see nowhere documenting that I do this. Please help I am on a tight deadline..

Error when build application on OS X 10.11 El Capitan

$ ionic build ios
...
background/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(TSReachability.o)
    background/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(TSLocationManager.o)
duplicate symbol _llvm.embedded.module in:
    background/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(TSReachability.o)
    background/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(TSLocationManager.o)
duplicate symbol _llvm.cmdline in:
    background/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(TSReachability.o)
    background/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(LocationDAO.o)
duplicate symbol _llvm.embedded.module in:
    background/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(TSReachability.o)
    background/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(LocationDAO.o)
duplicate symbol _llvm.cmdline in:
    background/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(TSReachability.o)
    background/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(SOMotionDetector.o)
duplicate symbol _llvm.embedded.module in:
    background/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(TSReachability.o)
    background/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(SOMotionDetector.o)
ld: 12 duplicate symbols for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

** BUILD FAILED **


The following build commands failed:
    Ld build/emulator/background.app/background normal i386
(1 failure)
Error code 65 for command: xcodebuild with args: -xcconfig,/Users/rg/Devs/Apps/background/platforms/ios/cordova/build-debug.xcconfig,-project,background.xcodeproj,ARCHS=i386,-target,background,-configuration,Debug,-sdk,iphonesimulator,build,VALID_ARCHS=i386,CONFIGURATION_BUILD_DIR=/Users/rg/Devs/Apps/background/platforms/ios/build/emulator,SHARED_PRECOMPS_DIR=/Users/rg/Devs/Apps/background/platforms/ios/build/sharedpch
ERROR building one of the platforms: Error: /Users/rg/Devs/Apps/background/platforms/ios/cordova/build: Command failed with exit code 2
You may not have the required environment or OS to build this project
Error: /Users/rg/Devs/Apps/background/platforms/ios/cordova/build: Command failed with exit code 2
    at ChildProcess.whenDone (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/superspawn.js:139:23)
    at emitTwo (events.js:87:13)
    at ChildProcess.emit (events.js:172:7)
    at maybeClose (internal/child_process.js:817:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)

$ ionic info

Your system information:

Cordova CLI: 5.3.3
Gulp version:  CLI version 3.9.0
Gulp local:   Local version 3.9.0
Ionic Version: 1.1.0
Ionic CLI Version: 1.6.5
Ionic App Lib Version: 0.3.9
ios-deploy version: 1.7.0 
ios-sim version: 5.0.1 
OS: Mac OS X Yosemite (or El Capitan)
Node Version: v4.1.1
Xcode version: Xcode 6.4 Build version 6E35b

Invalid Date error while running on iPhone

Hey,

I am using background geolocation plugin (free) for iPhone. While using the simulator it works fine (location is emulated via Debug -> Location -> City Bicyle Ride).

But once deployed on a real iPhone the location callback is not called anymore.

I'm getting an 'Invalid Date' error on calling to BackgroundGeolocationService (taken from your example app) with method GetCurrentPosition():

> BackgroundGeolocationService.getCurrentPosition()
< undefined
[Log] ************************************************************************************* (console-via-logger.js, line 173)
[Error] BackgroundGeolocation caught a Javascript Exception in your application code
    (anonyme Funktion)
    _runBackgroundTask
    mySuccess
    callbackFromNative
    (anonyme Funktion)
    nativeEvalAndFetch
    nativeCallback
    (anonyme Funktion)
[Log]  while running in a background thread.  Auto-finishing background-task: – 14 (console-via-logger.js, line 173)
[Log]  to prevent application crash (console-via-logger.js, line 173)
[Log] ************************************************************************************* (console-via-logger.js, line 173)
[Log] STACK: (console-via-logger.js, line 173)
 – "toISOString@[native code]↡toJSON@[native code]↡stringify@[native code]↡fireLocationListeners@file:///var/mobile/Containers/Bundle/Application/C33D902D-6792-4A23-B40C-112D343BF51C/BG%20Geo.app/www/js/services/backgroundGeolocation.js:109:82↡file:///var/mobile/Containers/Bundle/Application/C33D902D-6792-4A23-B40C-112D343BF51C/BG%20Geo.app/www/plugins/com.transistorsoft.cordova.background-geolocation/www/BackgroundGeolocation.js:38:29↡_runBackgroundTask@file:///var/mobile/Containers/Bundle/Application/C33D902D-6792-4A23-B40C-112D343BF51C/BG%20Geo.app/www/plugins/com.transistorsoft.cordova.background-geolocation/www/BackgroundGeolocation.js:356:26↡mySuccess@file:///var/mobile/Containers/Bundle/Application/C33D902D-6792-4A23-B40C-112D343BF51C/BG%20Geo.app/www/plugins/com.transistorsoft.cordova.background-geolocation/www/BackgroundGeolocation.js:37:34↡callbackFromNative@file:///var/mobile/Containers/Bundle/Application/C33D902D-6792-4A23-B40C-112D343BF51C/BG%20Geo.app/www/cordova.js:293:63↡file:///var/mobile/Containers/Bundle/Application/C33D902D-6792-4A23-B40C-112D343BF51C/BG%20Geo.app/www/cordova.js:1109:35↡nativeEvalAndFetch@file:///var/mobile/Containers/Bundle/Application/C33D902D-6792-4A23-B40C-112D343BF51C/BG%20Geo.app/www/cordova.js:1117:13↡nativeCallback@file:///var/mobile/Containers/Bundle/Application/C33D902D-6792-4A23-B40C-112D343BF51C/BG%20Geo.app/www/cordova.js:1106:38↡global code@file:///var/mobile/Containers/Bundle/Application/C33D902D-6792-4A23-B40C-112D343BF51C/BG%20Geo.app/www/index.html#/:1:47"
[Error] RangeError: Invalid Date 
    (anonyme Funktion)
    _runBackgroundTask
    mySuccess
    callbackFromNative
    (anonyme Funktion)
    nativeEvalAndFetch
    nativeCallback
    (anonyme Funktion)
[Log] calculateWatt (console-via-logger.js, line 173)

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: value parameter is nil'

Hi!
Just started to implement this cool plugin into our product, but unfortunately it's not working.

When trying to start your small demo script as shown in the README, the following error occurs:

2016-02-02 11:38:18.429 GEOApp[3164:1323163] [ts-locationmanager] - start
2016-02-02 11:38:18.430 GEOApp[3164:1323163] [ts-locationmanager] - setPace 0, stationaryRegion? 0
2016-02-02 11:38:18.430 GEOApp[3164:1323163] [ts-locationmanager] - stop prevent-suspend timer
2016-02-02 11:38:18.431 GEOApp[3164:1323163] [ts-locationmanager] - stopShakeDetection
2016-02-02 11:38:18.431 GEOApp[3164:1323163] [ts-locationmanager] - start location updates
2016-02-02 11:38:18.436 GEOApp[3164:1323163] [ts-locationmanager] - MotionDetector starting
2016-02-02 11:38:18.538 GEOApp[3164:1323134] [ts-locationmanager] - start
2016-02-02 11:38:18.643 GEOApp[3164:1323098] [ts-locationmanager] - didChangeAuthorizationStatus 3
2016-02-02 11:38:18.644 GEOApp[3164:1323098] [ts-locationmanager] - setPace 0, stationaryRegion? 0
2016-02-02 11:38:18.644 GEOApp[3164:1323098] [ts-locationmanager] - stop prevent-suspend timer
2016-02-02 11:38:18.644 GEOApp[3164:1323098] [ts-locationmanager] - stopShakeDetection
2016-02-02 11:38:18.645 GEOApp[3164:1323098] [ts-locationmanager] - LocationManager didChangeAuthorizationStatus -- NO IMPL 3
2016-02-02 11:38:18.647 GEOApp[3164:1323098] [ts-locationmanager] --------------------------------------------------------
2016-02-02 11:38:18.647 GEOApp[3164:1323098] [ts-locationmanager] - didUpdateLocations (enabled: 1, isMoving: 0, df: -1.0, spd: -1.0)
2016-02-02 11:38:18.647 GEOApp[3164:1323098] [ts-locationmanager] updatingLocation: 1
2016-02-02 11:38:18.649 GEOApp[3164:1323098] [ts-locationmanager] isAcquiringStationaryLocation: 1
2016-02-02 11:38:18.673 GEOApp[3164:1323098] [ts-locationmanager] isAcquringSpeed: 0
2016-02-02 11:38:18.673 GEOApp[3164:1323098] [ts-locationmanager] stoppedAt: (null)
2016-02-02 11:38:18.673 GEOApp[3164:1323098] [ts-locationmanager] - LocationManager didChangeAuthorizationStatus -- NO IMPL 3
2016-02-02 11:38:18.675 GEOApp[3164:1323098] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* +[NSJSONSerialization dataWithJSONObject:options:error:]: value parameter is nil'
*** First throw call stack:
(0x181819900 0x180e87f80 0x181819848 0x182253760 0x1000d3bb0 0x1000d0398 0x1000cfb78 0x1817befc4 0x1817be7e4 0x1817be564 0x181823de4 0x1816ff0f4 0x1820eed2c 0x1000bf794 0x1867c3830 0x1867b1de0 0x182dcf790 0x182dcfb10 0x1817d0efc 0x1817d0990 0x1817ce690 0x1816fd680 0x182c0c088 0x186574d90 0x1000bf0e4 0x18129e8b8) libc++abi.dylib: terminating with uncaught exception of type NSException

I've the following Cordova Version

sinoboeckmann$ cordova -v
5.4.1

And of course the following plugins installed

sinoboeckmann$ cordova plugin list
com.synconset.imagepicker 1.0.6 "ImagePicker"
cordova-plugin-app-preferences 0.7.5 "AppPreferences"
cordova-plugin-calendar 4.4.5 "Calendar"
cordova-plugin-camera 1.2.0 "Camera"
cordova-plugin-console 1.0.2 "Console"
cordova-plugin-dialogs 1.2.0 "Notification"
cordova-plugin-file 3.0.0 "File"
cordova-plugin-splashscreen 3.0.0 "Splashscreen"
cordova-plugin-statusbar 2.0.0 "StatusBar"
cordova-plugin-vibration 2.1.0 "Vibration"
cordova-plugin-whitelist 1.2.0 "Whitelist"
de.appplant.cordova.plugin.background-mode 0.6.4 "BackgroundMode"
de.appplant.cordova.plugin.local-notification 0.8.1 "LocalNotification"
ionic-plugin-keyboard 1.0.8 "Keyboard"
org.apache.cordova.device 0.3.0 "Device"
phonegap-facebook-plugin 0.12.0 "Facebook Connect"

Both Simulator (iOS 9.2, Iphone 6) and Device (iPhone 5s 9.2.1) are crashing with the same issue.

If we will get fixed this error and everything is going to work, we're definitely in to buy a license!
Thanks! :)

TypeError: Cannot read property 'id' of undefined

I have code that logs a final location before I stop the background geolocation service. It is throwing an error when I run the following because I don't have the taskId variable. How do I get said variable so it doesn't error out, I don't think it effects the functionality but I don't want this thing to error if I can avoid it. Thanks! ^_^

Code I Run

this.bgGeo.getCurrentPosition(function(location) {
    this.driver.session.end = {
        lat: location.coords.latitude,
        lng: location.coords.longitude,
        timestamp: new Date().toString()
    };

    this.driver.$save();

    this.bgGeo.stop();
}.bind(this), this.missing);

Error

BackgroundGeolocation caught a Javascript Exception in your application code(anonymous function) @ console-via-logger.js:173module.exports._runBackgroundTask @ BackgroundGeolocation.js:367mySuccess @ BackgroundGeolocation.js:48cordova.callbackFromNative @ cordova.js:291processMessage @ cordova.js:1079processMessages @ cordova.js:1102pollOnce @ cordova.js:971pollOnceFromOnlineEvent @ cordova.js:958
console-via-logger.js:173  while running in a background thread.  Auto-finishing background-task: task-id-undefined
console-via-logger.js:173  to prevent application crash
console-via-logger.js:173 *************************************************************************************
console-via-logger.js:173 STACK:
 TypeError: Cannot read property 'id' of undefined
    at GeolocationService.located (file:///android_asset/www/js/build.js:81593:96)
    at Object.<anonymous> (file:///android_asset/www/plugins/com.transistorsoft.cordova.background-geolocation/www/BackgroundGeolocation.js:49:25)
    at Object.module.exports._runBackgroundTask (file:///android_asset/www/plugins/com.transistorsoft.cordova.background-geolocation/www/BackgroundGeolocation.js:364:22)
    at mySuccess (file:///android_asset/www/plugins/com.transistorsoft.cordova.background-geolocation/www/BackgroundGeolocation.js:48:16)
    at Object.cordova.callbackFromNative (file:///android_asset/www/cordova.js:291:58)
    at processMessage (file:///android_asset/www/cordova.js:1079:17)
    at processMessages (file:///android_asset/www/cordova.js:1102:9)
    at pollOnce (file:///android_asset/www/cordova.js:971:9)
    at pollOnceFromOnlineEvent (file:///android_asset/www/cordova.js:958:5)
console-via-logger.js:173 TypeError: Cannot read property 'id' of undefined(…)

taskId is NULL

Hello

I'm using your background geolocation and it works but I have one problem with parameter taskId in success callback from getting position.
I've got the following code (relevant to this topic):

    function OnBackgroundPositionSuccess(position, taskId) {
        LE.log('OnBackgroundPositionSuccess: ' + taskId);

        var request: any = {};
        request.SerialNumber = _SerialNumber;
        request.Time = position.timestamp;
        request.Latitude = position.latitude;
        request.Longitude = position.longitude;
        request.Speed = position.speed;

        sendToWebservice(request, taskId);
    }

    function OnBackgroundPositionError(error) {
        LE.log('OnBackgroundPositionError');
    }

    bgGeo.configure(OnBackgroundPositionSuccess, OnBackgroundPositionError, {
        desiredAccuracy: 1,
        distanceFilter: 1,
        activityRecognitionInterval: 0,
        autoSync: false //,
        //useSignificantChangesOnly: true,
        //debug: true,
    });

My problem is that taskId is always NULL in function OnBackgroundPositionSuccess(). Parameter position on the other hand has the correct values. As you can see I send my requests manual to the webservice but I don't think this should affect taskId. Is there anything wrong in my configuration?

Any help would be great.
Thank you very much.

Best Regards,
gogcam

GPS taking some time to "warm up"?

I've been noticing that some of the results I'm getting back show a bit of a "warm up" time.

See here for example: The car was travelling Westward, and you can see there's a "gap" near the start of about 15 minutes. I've seen it as long as 30 minutes before I start getting reliable data on some devices.

Since this is intermittent, I'm guessing it's a iOS issue, but have you (or anyone else) seen this before? Is there anything I can do to prevent it?

Plugin doesn't work on iOS 9

Hi,

I use Xcode 7.0 (7A218) to build Ionic project for iPhone with installed iOS 9 (official release). Deployment target is 6.0. Compilation and deployment happens without any issues, but when I run application from XCode on device it fails with locationManager failed: Error Domain=kCLErrorDomain Code=1 "(null)"

Any ideas, thoughts?

2015-09-17 22:17:28.707 MapMeIO[359:92477] Apache Cordova native platform version 3.8.0 is starting.
2015-09-17 22:17:28.709 MapMeIO[359:92477] Multi-tasking -> Device: YES, App: YES
2015-09-17 22:17:28.727 MapMeIO[359:92477] Unlimited access to network resources
2015-09-17 22:17:28.905 MapMeIO[359:92477] [CDVTimer][keyboard] 0.285983ms
2015-09-17 22:17:29.511 MapMeIO[359:92477] [CDVTimer][splashscreen] 605.219007ms
2015-09-17 22:17:29.511 MapMeIO[359:92477] [CDVTimer][TotalPluginStartup] 606.223047ms
2015-09-17 22:17:29.709 MapMeIO[359:92477] Resetting plugins due to page load.
2015-09-17 22:17:31.131 MapMeIO[359:92477] Finished load of: file:///var/mobile/Containers/Bundle/Application/7925DA38-0C6A-4CD1-8126-1DBCF76A8468/MapMeIO.app/www/index.html#/welcome
2015-09-17 22:17:31.649 MapMeIO[359:92477] - BackgroundGeolocation requires requestAlwaysAuthorization!
2015-09-17 22:17:31.652 MapMeIO[359:92477] [ts-locationmanager] CDVBackgroundGeoLocation configure {
activityRecognitionInterval = 10000;
activityType = AutomotiveNavigation;
autoSync = true;
batchSync = false;
debug = true;
desiredAccuracy = 0;
disableElasticity = false;
distanceFilter = 20;
fastestLocationUpdateInterval = 1000;
forceReloadOnGeofence = false;
forceReloadOnLocationChange = false;
forceReloadOnMotionChange = false;
locationUpdateInterval = 5000;
startOnBoot = false;
stationaryRadius = 20;
stopOnTerminate = true;
stopTimeout = 0;
triggerActivities = "in_vehicle, on_bicycle, running, walking, on_foot";
url = "";
}
2015-09-17 22:17:31.652 MapMeIO[359:92477] - TSLocationManager create database
2015-09-17 22:17:31.653 MapMeIO[359:92477] THREAD WARNING: ['BackgroundGeolocation'] took '11.375244' ms. Plugin should use a background thread.
2015-09-17 22:17:31.663 MapMeIO[359:92477] [ts-locationmanager] - didChangeAuthorizationStatus 2
2015-09-17 22:17:46.021 MapMeIO[359:92477] [ts-locationmanager] - setConfig {
activityRecognitionInterval = 10000;
activityType = AutomotiveNavigation;
autoSync = true;
batchSync = false;
debug = true;
desiredAccuracy = 0;
disableElasticity = false;
distanceFilter = 20;
fastestLocationUpdateInterval = 1000;
forceReloadOnGeofence = false;
forceReloadOnLocationChange = false;
forceReloadOnMotionChange = false;
locationUpdateInterval = 5000;
startOnBoot = false;
stationaryRadius = 20;
stopOnTerminate = true;
stopTimeout = 0;
triggerActivities = "in_vehicle, on_bicycle, running, walking, on_foot";
url = "";
}
2015-09-17 22:17:46.026 MapMeIO[359:92477] - setConfig:
2015-09-17 22:17:46.810 MapMeIO[359:92477] [ts-locationmanager] - setConfig {
activityRecognitionInterval = 10000;
activityType = AutomotiveNavigation;
autoSync = true;
batchSync = false;
debug = true;
desiredAccuracy = 0;
disableElasticity = false;
distanceFilter = 20;
fastestLocationUpdateInterval = 1000;
forceReloadOnGeofence = false;
forceReloadOnLocationChange = false;
forceReloadOnMotionChange = false;
locationUpdateInterval = 5000;
startOnBoot = false;
stationaryRadius = 20;
stopOnTerminate = true;
stopTimeout = 0;
triggerActivities = "in_vehicle, on_bicycle, running, walking, on_foot";
url = "";
}
2015-09-17 22:17:46.812 MapMeIO[359:92477] - setConfig:
2015-09-17 22:17:46.825 MapMeIO[359:92477] [ts-locationmanager] - stop
2015-09-17 22:17:46.833 MapMeIO[359:92477] [ts-locationmanager] - locationManager failed: Error Domain=kCLErrorDomain Code=1 "(null)"
2015-09-17 22:17:46.833 MapMeIO[359:92477] - onLocationManagerError: {
code = 1;
type = location;
}
2015-09-17 22:17:46.840 MapMeIO[359:92477] WARN: BackgroundGeolocation Error: 1
2015-09-17 22:17:47.859 MapMeIO[359:92515] CFNetwork SSLHandshake failed (-9806)
2015-09-17 22:17:47.861 MapMeIO[359:92541] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9806)
2015-09-17 22:17:48.563 MapMeIO[359:92515] CFNetwork SSLHandshake failed (-9806)
2015-09-17 22:17:48.566 MapMeIO[359:92541] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9806)
2015-09-17 22:17:49.812 MapMeIO[359:92515] CFNetwork SSLHandshake failed (-9806)
2015-09-17 22:17:49.814 MapMeIO[359:92541] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9806)
2015-09-17 22:17:50.940 MapMeIO[359:92515] CFNetwork SSLHandshake failed (-9806)
2015-09-17 22:17:50.943 MapMeIO[359:92541] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9806)
2015-09-17 22:17:52.782 MapMeIO[359:92515] CFNetwork SSLHandshake failed (-9806)
2015-09-17 22:17:52.786 MapMeIO[359:92541] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9806)
2015-09-17 22:17:54.588 MapMeIO[359:92477] [ts-locationmanager] - SUSPEND (enabled? 0)
2015-09-17 22:17:54.845 MapMeIO[359:92515] CFNetwork SSLHandshake failed (-9806)
2015-09-17 22:17:54.847 MapMeIO[359:92541] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9806)

Params Nor Locations Are Getting Passed with the url.

I have configure set to this....

    bgGeo.configure( function(location, taskId){ callbackFn(location, taskId);},
                     function(error){failureFn(error);}, 
                     {
                        locationUpdateInterval: localStorage.getItem('location_update_interval'),
                        fastestLocationUpdateInterval: localStorage.getItem('location_update_interval'),
                        desiredAccuracy: localStorage.getItem('desired_accuracy'),
                        stationaryRadius: localStorage.getItem('stationary_radius'),
                        distanceFilter: localStorage.getItem('distance_filter'),
                        disableElasticity : localStorage.getItem('disable_elasticity') == 'on',                    
                        autoSync: true,
                        batchSync: localStorage.getItem('batch_sync') == 'on',
                        debug: localStorage.getItem('debug_mode') == 'on',
                        url: localStorage.getItem('ims_url')+'/webSrvRequests/AVL/avlMobilePush.php?unitid='+localStorage.getItem('truck'),
                        params:{"my_param": "is coming through now?"},
                        headers:{"X-FOO": "bar"},
                        //params: [thiscoord],
                        /* params: {rcdid:new Date().getTime(), unitid:localStorage.getItem('truck'), network_state:defaultNetwork, platform:platform, version:device.version, uuid:device.uuid, device_name:device.name, collection_type:"linemanapp"},*/
                        method: 'GET',
                        maxDaysToPersist: 3
                    }

But in the apache access.log I see this..

64.183.192.222 - - [17/Sep/2015:14:21:55 -0500] "GET /webSrvRequests/AVL/avlMobilePush.php?unitid=NBT1 HTTP/1.1" 200 196

BUG XCODE WARN: BackgroundGeolocation Error: 0

Hi,
Excuse me my english is very bad.

I tested your application "Cordova Background Geolocation Sample Application" for xcode (version 7), and ios (version 9.0), in simulator, and active the location FreeWay Drive. I noticed that after a minute , I get the following error.

I have not changed the configuration.

My console log in launch the app,

"2015-09-19 12:47:22.048 myApp2[xxxxxxxx] Apache Cordova native platform version 3.9.1 is starting.
2015-09-19 12:47:22.048 myApp2[xxxxxxx] Multi-tasking -> Device: YES, App: YES
2015-09-19 12:47:22.050 myApp2[xxxxxxxx] Unlimited access to network resources
2015-09-19 12:47:22.113 myApp2[xxxxxxxx] [CDVTimer][keyboard] 0.064015ms
2015-09-19 12:47:22.212 myApp2[xxxxxxxx] [CDVTimer][splashscreen] 98.708034ms
2015-09-19 12:47:22.212 myApp2[xxxxxxxx] [CDVTimer][TotalPluginStartup] 99.184990ms
2015-09-19 12:47:22.254 myApp2[xxxxxxxx] Resetting plugins due to page load.
2015-09-19 12:47:23.116 myApp2[xxxxxxxx] Finished load of: file:///Users/xxxx/Library/Developer/CoreSimulator/Devices/xxxxxxxx/myApp2.app/www/index.html#/tab/login
2015-09-19 12:47:23.273 myApp2[xxxxxxxx] - BackgroundGeolocation requires requestAlwaysAuthorization!
2015-09-19 12:47:23.274 myApp2[xxxxxxxx] - TSLocationManager create database
2015-09-19 12:47:25.188 myApp2[xxxxxxxx] - INSERT success
2015-09-19 12:47:25.195 myApp2[xxxxxxxx] - LOCKED 245 records
2015-09-19 12:47:25.198 myApp2[xxxxxxxx] - UNLOCK success
2015-09-19 12:47:25.199 myApp2[xxxxxxxx] - UNLOCK success
2015-09-19 12:47:25.200 myApp2[xxxxxxxx] - UNLOCK success
2015-09-19 12:47:25.201 myApp2[xxxxxxxx] - UNLOCK success
2015-09-19 12:47:25.201 myApp2[xxxxxxxx] [js] onMotionChange: false {"coords":{"speed":2.43,"longitude":xxxxxxx,"latitude":xxxxxx,"accuracy":10,"heading":282.43,"altitude":0,"altitudeAccuracy":-1},"timestamp":"2015-09-19T08:47:23.2Z","is_moving":false,"battery":{"level":-1,"is_charging":0},"uuid":"xxxxxxx"}
2015-09-19 12:47:25.201 myApp2[xxxxxxxx] - BackgroundGeolocationService#finish, taskId: 4
2015-09-19 12:47:25.202 myApp2[xxxxxxxx] - UNLOCK success
2015-09-19 12:47:25.202 myApp2[xxxxxxxx] [js] BackgroundGeolocation location received: {"coords":{"speed":2.43,"longitude":xxxxxx,"latitude":xxxxxx,"accuracy":10,"heading":282.43,"altitude":0,"altitudeAccuracy":-1},"timestamp":"2015-09-19T08:47:23.200Z","is_moving":false,"battery":{"level":-1,"is_charging":0},"uuid":"xxxxxxxxx"}"

And the error after a minutes

"2015-09-19 13:03:30.229 myApp2[xxxxxxxx] - onLocationManagerError: {
code = 0;
type = location;
}
2015-09-19 13:03:30.230 myApp2[xxxxxxxx] WARN: BackgroundGeolocation Error: 0"

Thanks

Disable local push notifications in app?

Trying this out with iOS. In a case where a user says they want notifications, we would like to give them the option to disable them in app. Is that possible? Alternatively can we disable them outright?

Plugin doesn't work during turning application.

I tested this plugin on the street in the app but Background Geolocation doesn't work, I didn't get any GPS coordinates. What can be the problem? I launch this plugin in controller on Ionic Framework with such code:

var bgGeo = window.BackgroundGeolocation;
var options = {
        disableElasticity: false,
        locationUpdateInterval: 10000,
        fastestLocationUpdateInterval: 5000,
        activityRecognitionInterval: 10000,
        activityType: 'AutomotiveNavigation',
        debug: false
      };
      bgGeo.configure(function(location, taskId) {
          console.log('BackgroundGeolocationConfig');
          console.log(location.coords);
          $scope.getColorStatus(location.coords.accuracy);
          console.log($scope.transfer.location_gps_status);
          $scope.sendLocation(location);


        $timeout(function () {
          bgGeo.finish(taskId);
        }, 1000);
      }, function(error) {
        console.error('BackgroundGeolocationConfig',error);
      }, options);

  $ionicPlatform.on('pause', function(event) {
bgGeo.start();
});

 $ionicPlatform.on('resume', function(event) {
  bgGeo.stop();
});

window.BackgroundGeolocation is undefined

Plugin.xml

<?xml version="1.0" encoding="UTF-8"?>

<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
    xmlns:android="http://schemas.android.com/apk/res/android"
    id="com.transistorsoft.cordova.background-geolocation"
    version="1.2.0">
    <name>BackgroundGeolocation</name>
    <description>Sophisticated, battery-efficient background-geolocation plugin for Cordova</description>
    <license>MIT</license>
    <keywords>cordova, phonegap, background geolocation</keywords>

    <engines>
        <engine name="cordova" version=">=3.0.0" />
    </engines>

    <!-- 
        Pre-Cordova 5, non-npm plugin reference.  Uncomment this if you're not using Cordova 5.
    <dependency id="org.apache.cordova.dialogs" />
    -->

    <!-- Cordova 5 npm-style plugin referernce.  Comment this out if you're not using Cordova 5 -->
    <dependency id="cordova-plugin-dialogs" />

    <js-module src="www/BackgroundGeolocation.js" name="BackgroundGeolocation">
        <clobbers target="window.BackgroundGeolocation" />
    </js-module>

    <!-- android available in Premium Version: http://transistorsoft.github.io/cordova-background-geolocation -->

     <platform name="ios">
        <!-- required background modes:  App registers for location updates -->

        <config-file target="*-Info.plist" parent="NSLocationAlwaysUsageDescription">
            <string>TSLocationManager requires background location tracking</string>
        </config-file>

        <config-file target="*-Info.plist" parent="UIBackgroundModes">
            <array>
                <string>location</string>
            </array>
        </config-file>

        <config-file target="config.xml" parent="/*">
            <feature name="BackgroundGeolocation">
                <param name="ios-package" value="CDVBackgroundGeolocation"/>
            </feature>
        </config-file>
        <framework src="SystemConfiguration.framework" weak="true" />
        <framework src="AudioToolbox.framework" weak="true" />
        <framework src="AVFoundation.framework" weak="true" />
        <framework src="libsqlite3.dylib" weak="true" />
        <framework src="src/ios/TSLocationManager.framework" custom="true" />
        <source-file src="src/ios/CDVBackgroundGeolocation.m" />
        <header-file src="src/ios/CDVBackgroundGeolocation.h" />
     </platform>          

</plugin>

app.js

angular.module('starter', ['ionic','ionic.service.core', 'starter.controllers', 'starter.services','ngCordova','ngCordova.plugins.backgroundGeolocation'])

.run(function ($window,$ionicPlatform,  $rootScope, $cordovaGeolocation, $cordovaBackgroundGeolocation, $cordovaDevice, $http) {
   // alert('stop so I can inspect!');
  $ionicPlatform.ready(function() {
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }

   // $location.path('/app');
   /* $rootScope.$digest();

    $rootScope.deviceReady = false; */

  /*  document.addEventListener('deviceready', function () {
        if(window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
          window.cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        }

          */
         var bgGeo = window.BackgroundGeolocation;
         console.log(bgGeo);
    /**
    * This callback will be executed every time a geolocation is recorded in the background.
    */
    var callbackFn = function(location, taskId) {
        var coords = location.coords;
        var lat    = coords.latitude;
        var lng    = coords.longitude;

        // Simulate doing some extra work with a bogus setTimeout.  This could perhaps be an Ajax request to your server.
        // The point here is that you must execute bgGeo.finish after all asynchronous operations within the callback are complete.
        setTimeout(function() {
          bgGeo.finish(taskId); // <-- execute #finish when your work in callbackFn is complete
        }, 1000);
    };

    var failureFn = function(error) {
        console.log('BackgroundGeoLocation error');
    }

    // BackgroundGeoLocation is highly configurable.
    bgGeo.configure(callbackFn, failureFn, {
        // Geolocation config
        desiredAccuracy: 0,
        stationaryRadius: 50,
        distanceFilter: 50,
        disableElasticity: false, // <-- [iOS] Default is 'false'.  Set true to disable speed-based distanceFilter elasticity
        locationUpdateInterval: 5000,
        minimumActivityRecognitionConfidence: 80,   // 0-100%.  Minimum activity-confidence for a state-change 
        fastestLocationUpdateInterval: 5000,
        activityRecognitionInterval: 10000,
        stopDetectionDelay: 1,  // Wait x minutes to engage stop-detection system
        stopTimeout: 2,  // Wait x miutes to turn off location system after stop-detection
        activityType: 'AutomotiveNavigation',

        // Application config
        debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
        forceReloadOnLocationChange: false,  // <-- [Android] If the user closes the app **while location-tracking is started** , reboot app when a new location is recorded (WARNING: possibly distruptive to user) 
        forceReloadOnMotionChange: false,    // <-- [Android] If the user closes the app **while location-tracking is started** , reboot app when device changes stationary-state (stationary->moving or vice-versa) --WARNING: possibly distruptive to user) 
        forceReloadOnGeofence: false,        // <-- [Android] If the user closes the app **while location-tracking is started** , reboot app when a geofence crossing occurs --WARNING: possibly distruptive to user) 
        stopOnTerminate: false,              // <-- [Android] Allow the background-service to run headless when user closes the app.
        startOnBoot: true,                   // <-- [Android] Auto start background-service in headless mode when device is powered-up.

        // HTTP / SQLite config
        url: 'http://posttestserver.com/post.php?dir=cordova-background-geolocation',
        method: 'POST',
        batchSync: true,       // <-- [Default: false] Set true to sync locations to server in a single HTTP request.
        autoSync: true,         // <-- [Default: true] Set true to sync each location to server as it arrives.
        maxDaysToPersist: 1,    // <-- Maximum days to persist a location in plugin's SQLite database when HTTP fails
        headers: {
            "X-FOO": "bar"
        },
        params: {
            "auth_token": "maybe_your_server_authenticates_via_token_YES?"
        }
    });

    // Turn ON the background-geolocation system.  The user will be tracked whenever they suspend the app.
    bgGeo.start();
  });
})

Pasted above is my code , but every-time I run it in browser I get an error saying that window.BackgroundGeolocation is undefined. I think i am missing something but am unable to figure out. Any help would be really appreciated.

Performance ipad after update to iOS9.1

I implemented the background geoloc a few months ago.
Users never complained about performance issues on iOS 8.4.

Since 9.1, several users are complaining that other apps become laggy, non responsive when app with backgroundlocation is running. When app is not running, no lags.

I tested this for the last week.
Sometimes i do have lags, most of the time i don't. Can't find a reason of the irregular behaviour.

Anybody experiencing same problems lately?

Invalid callback id received by sendPluginResult

window.BackgroundGeolocation.setConfig(function() {
console.log('BackgroundGeolocation - set config success');
}, function(){
console.log('BackgroundGeolocation - failed to setConfig');
},{
desiredAccuracy: 0,
distanceFilter: 50
});

window.BackgroundGeolocation.getCurrentPosition(
onUpdate,
onError, {
preventSuspend: true,
stopOnTerminate: true
});

I'm getting this error: Invalid callback id received by sendPluginResult... any clues

iOS background geofence

Hi,

We want to use the onGeofence-event to relaunch the app and start gathering data.
According to the apple developer documentation
https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/index.html#//apple_ref/doc/uid/TP40007125-CH3-SW32

and specifically the quote:
"The region monitoring service delivers events normally while an app is running in the foreground or background. (You can use this service for both geographic and beacon regions.) For a terminated iOS app, this service relaunches the app to deliver events. Use of this service requires β€œAlways” authorization from the user."

we take it that the app should relaunch from these events. Although when the app runs in background (home button is pressed or screen is locked - applications has NOT been force-quit) we dont seem to get these events.

Example code:

bgGeo.onMotionChange(function(isMoving, location, taskId) {

    if (!isMoving) { // if not moving, create a geofence on this location
        bgGeo.addGeofence({
            identifier: "test",
            radius: 100,
            latitude: location.coords.latitude,
            longitude:location.coords.longitude,
            notifyOnEntry: false,
            notifyOnExit: true
        }, function() {
            console.log("Successfully added geofence");
            PostToServer('ADD_GEOFENCE');// Log on server that we added a geofence
        }, function(error) {
            console.warn("Failed to add geofence " + error);
        });
    } 
    bgGeo.finish(taskId);
})

bgGeo.onGeofence(function(params, taskId) {
    try {
        if ((params.identifier == 'test') && (params.action == 'EXIT')) {
            bgGeo.changePace(true); // set aggressive logging if we passed a geofence
            PostToServer('EXIT_GEOFENCE');// Log on server that we exited our geofence
        }
    } catch(e) {
        console.error('An error occurred in my application code ' + e);
    }
    bgGeo.finish(taskId);
});

We were thinking that we might be calling "bgGeo.finish(taskId)" at the wrong place but we've also tried doing that in the respective callbacks and also "if (isMoving)", like so:

bgGeo.onMotionChange(function(isMoving, location, taskId) {

    if (!isMoving) { // if not moving, create a geofence on this location
        bgGeo.addGeofence({
            identifier: "test",
            radius: 100,
            latitude: location.coords.latitude,
            longitude:location.coords.longitude,
            notifyOnEntry: false,
            notifyOnExit: true
        }, function() {
            console.log("Successfully added geofence");
            PostToServer('ADD_GEOFENCE');// Log on server that we added a geofence
            bgGeo.finish(taskId);
        }, function(error) {
            console.warn("Failed to add geofence " + error);
            bgGeo.finish(taskId);
        });
    } else {
        bgGeo.finish(taskId);
    }
})

When consulting our logs on server we can see that we create new geofences, but we never "EXIT" them.

Thanks in advance

Error on compilation with XCode7

I'm using Ionic 1.6.5 and Xcode 7.0.1

I'm trying to make an Archive of my App with background geolocation plugin and I have error:

Ld /Users/madubois/Library/Developer/Xcode/DerivedData/Lanauco-Mobile-ezkiqbpqposuhngohjxxkxxfowwq/Build/Intermediates/ArchiveIntermediates/Lanauco-Mobile/IntermediateBuildFilesPath/Lanauco-Mobile.build/Release-iphoneos/Lanauco-Mobile.build/Objects-normal/arm64/Lanauco-Mobile normal arm64

cd /Users/madubois/Projects/lanauco_workbench/lanauco.lanauco_mobile/platforms/ios

export IPHONEOS_DEPLOYMENT_TARGET=9.0

export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch arm64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk -L/Users/madubois/Library/Developer/Xcode/DerivedData/Lanauco-Mobile-ezkiqbpqposuhngohjxxkxxfowwq/Build/Intermediates/ArchiveIntermediates/Lanauco-Mobile/BuildProductsPath/Release-iphoneos -F/Users/madubois/Library/Developer/Xcode/DerivedData/Lanauco-Mobile-ezkiqbpqposuhngohjxxkxxfowwq/Build/Intermediates/ArchiveIntermediates/Lanauco-Mobile/BuildProductsPath/Release-iphoneos -FLanauco-Mobile/Plugins/com.transistorsoft.cordova.background-geolocation -filelist /Users/madubois/Library/Developer/Xcode/DerivedData/Lanauco-Mobile-ezkiqbpqposuhngohjxxkxxfowwq/Build/Intermediates/ArchiveIntermediates/Lanauco-Mobile/IntermediateBuildFilesPath/Lanauco-Mobile.build/Release-iphoneos/Lanauco-Mobile.build/Objects-normal/arm64/Lanauco-Mobile.LinkFileList -miphoneos-version-min=9.0 -dead_strip -fembed-bitcode -Xlinker -bitcode_verify -Xlinker -bitcode_hide_symbols -Xlinker -bitcode_symbol_map -Xlinker /Users/madubois/Library/Developer/Xcode/DerivedData/Lanauco-Mobile-ezkiqbpqposuhngohjxxkxxfowwq/Build/Intermediates/ArchiveIntermediates/Lanauco-Mobile/BuildProductsPath/Release-iphoneos -weak_framework CoreFoundation -weak_framework UIKit -weak_framework AVFoundation -weak_framework CoreMedia -weak-lSystem -ObjC -fobjc-arc -fobjc-link-runtime -framework AssetsLibrary /Users/madubois/Library/Developer/Xcode/DerivedData/Lanauco-Mobile-ezkiqbpqposuhngohjxxkxxfowwq/Build/Intermediates/ArchiveIntermediates/Lanauco-Mobile/BuildProductsPath/Release-iphoneos/libCordova.a -framework CoreGraphics -framework MobileCoreServices -weak_framework AudioToolbox -framework TSLocationManager -weak_framework AVFoundation -weak-lsqlite3 -weak_framework ImageIO -framework CoreLocation -Xlinker -dependency_info -Xlinker /Users/madubois/Library/Developer/Xcode/DerivedData/Lanauco-Mobile-ezkiqbpqposuhngohjxxkxxfowwq/Build/Intermediates/ArchiveIntermediates/Lanauco-Mobile/IntermediateBuildFilesPath/Lanauco-Mobile.build/Release-iphoneos/Lanauco-Mobile.build/Objects-normal/arm64/Lanauco-Mobile_dependency_info.dat -o /Users/madubois/Library/Developer/Xcode/DerivedData/Lanauco-Mobile-ezkiqbpqposuhngohjxxkxxfowwq/Build/Intermediates/ArchiveIntermediates/Lanauco-Mobile/IntermediateBuildFilesPath/Lanauco-Mobile.build/Release-iphoneos/Lanauco-Mobile.build/Objects-normal/arm64/Lanauco-Mobile

ld: bitcode bundle could not be generated because 'Lanauco-Mobile/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(TSReachability.o)' was built without full bitcode. All object files and libraries for bitcode must be generated from Xcode Archive or Install build for architecture arm64

clang: error: linker command failed with exit code 1 (use -v to see invocation)

Ld /Users/madubois/Library/Developer/Xcode/DerivedData/Lanauco-Mobile-ezkiqbpqposuhngohjxxkxxfowwq/Build/Intermediates/ArchiveIntermediates/Lanauco-Mobile/IntermediateBuildFilesPath/Lanauco-Mobile.build/Release-iphoneos/Lanauco-Mobile.build/Objects-normal/armv7/Lanauco-Mobile normal armv7

cd /Users/madubois/Projects/lanauco_workbench/lanauco.lanauco_mobile/platforms/ios

export IPHONEOS_DEPLOYMENT_TARGET=9.0

export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch armv7 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk -L/Users/madubois/Library/Developer/Xcode/DerivedData/Lanauco-Mobile-ezkiqbpqposuhngohjxxkxxfowwq/Build/Intermediates/ArchiveIntermediates/Lanauco-Mobile/BuildProductsPath/Release-iphoneos -F/Users/madubois/Library/Developer/Xcode/DerivedData/Lanauco-Mobile-ezkiqbpqposuhngohjxxkxxfowwq/Build/Intermediates/ArchiveIntermediates/Lanauco-Mobile/BuildProductsPath/Release-iphoneos -FLanauco-Mobile/Plugins/com.transistorsoft.cordova.background-geolocation -filelist /Users/madubois/Library/Developer/Xcode/DerivedData/Lanauco-Mobile-ezkiqbpqposuhngohjxxkxxfowwq/Build/Intermediates/ArchiveIntermediates/Lanauco-Mobile/IntermediateBuildFilesPath/Lanauco-Mobile.build/Release-iphoneos/Lanauco-Mobile.build/Objects-normal/armv7/Lanauco-Mobile.LinkFileList -miphoneos-version-min=9.0 -dead_strip -fembed-bitcode -Xlinker -bitcode_verify -Xlinker -bitcode_hide_symbols -Xlinker -bitcode_symbol_map -Xlinker /Users/madubois/Library/Developer/Xcode/DerivedData/Lanauco-Mobile-ezkiqbpqposuhngohjxxkxxfowwq/Build/Intermediates/ArchiveIntermediates/Lanauco-Mobile/BuildProductsPath/Release-iphoneos -weak_framework CoreFoundation -weak_framework UIKit -weak_framework AVFoundation -weak_framework CoreMedia -weak-lSystem -ObjC -fobjc-arc -fobjc-link-runtime -framework AssetsLibrary /Users/madubois/Library/Developer/Xcode/DerivedData/Lanauco-Mobile-ezkiqbpqposuhngohjxxkxxfowwq/Build/Intermediates/ArchiveIntermediates/Lanauco-Mobile/BuildProductsPath/Release-iphoneos/libCordova.a -framework CoreGraphics -framework MobileCoreServices -weak_framework AudioToolbox -framework TSLocationManager -weak_framework AVFoundation -weak-lsqlite3 -weak_framework ImageIO -framework CoreLocation -Xlinker -dependency_info -Xlinker /Users/madubois/Library/Developer/Xcode/DerivedData/Lanauco-Mobile-ezkiqbpqposuhngohjxxkxxfowwq/Build/Intermediates/ArchiveIntermediates/Lanauco-Mobile/IntermediateBuildFilesPath/Lanauco-Mobile.build/Release-iphoneos/Lanauco-Mobile.build/Objects-normal/armv7/Lanauco-Mobile_dependency_info.dat -o /Users/madubois/Library/Developer/Xcode/DerivedData/Lanauco-Mobile-ezkiqbpqposuhngohjxxkxxfowwq/Build/Intermediates/ArchiveIntermediates/Lanauco-Mobile/IntermediateBuildFilesPath/Lanauco-Mobile.build/Release-iphoneos/Lanauco-Mobile.build/Objects-normal/armv7/Lanauco-Mobile

ld: bitcode bundle could not be generated because 'Lanauco-Mobile/Plugins/com.transistorsoft.cordova.background-geolocation/TSLocationManager.framework/TSLocationManager(TSReachability.o)' was built without full bitcode. All object files and libraries for bitcode must be generated from Xcode Archive or Install build for architecture armv7

clang: error: linker command failed with exit code 1 (use -v to see invocation)

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.