Giter Club home page Giter Club logo

react-native-background-geolocation's Introduction

@mauron85/react-native-background-geolocation

CircleCI issuehunt-shield-v1

We're moving

Npm package is now @mauron85/react-native-background-geolocation!

Submitting issues

All new issues should follow instructions in ISSUE_TEMPLATE.md. A properly filled issue report will significantly reduce number of follow up questions and decrease issue resolving time. Most issues cannot be resolved without debug logs. Please try to isolate debug lines related to your issue. Instructions for how to prepare debug logs can be found in section Debugging. If you're reporting an app crash, debug logs might not contain all the necessary information about the cause of the crash. In that case, also provide relevant parts of output of adb logcat command.

Issue Hunt

Fund your issues or feature request to drag attraction of developers. Checkout our issue hunt page.

Android background service issues

There are repeatedly reported issues with some android devices not working in the background. Check if your device model is on dontkillmyapp list before you report new issue. For more information check out dontkillmyapp.com.

Another confusing fact about Android services is concept of foreground services. Foreground service in context of Android OS is different thing than background geolocation service of this plugin (they're related thought). Plugin's background geolocation service actually becomes foreground service when app is in the background. Confusing, right? :D

If service wants to continue to run in the background, it must "promote" itself to foreground service. Foreground services must have visible notification, which is the reason, why you can't disable drawer notification.

The notification can only be disabled, when app is running in the foreground, by setting config option startForeground: false (this is the default option), but will always be visible in the background (if service was started).

Recommend you to read https://developer.android.com/about/versions/oreo/background

Description

React Native fork of cordova-plugin-background-geolocation with battery-saving "circular region monitoring" and "stop detection".

This plugin can be used for geolocation when the app is running in the foreground or background.

You can choose from following location providers:

  • DISTANCE_FILTER_PROVIDER
  • ACTIVITY_PROVIDER
  • RAW_PROVIDER

See Which provider should I use? for more information about providers.

Dependencies

Versions of libraries and sdk versions used to compile this plugin can be overriden in android/build.gradle with ext declaration.

When ext is not provided then following defaults will be used:

ext {
  compileSdkVersion = 28
  buildToolsVersion = "28.0.3"
  targetSdkVersion = 28
  minSdkVersion = 16
  supportLibVersion = "28.0.0"
  googlePlayServicesVersion = "11+"
}

Compatibility

Due to the rapid changes being made in the React Native ecosystem, this module will support only the latest version of React Native. Older versions will only be supported if they're compatible with this module.

Module React Native
0.1.0 - 0.2.0 0.33
>=0.3.0 >=0.47
>=0.6.0 >=0.60

If you are using an older version of React Native with this module some features may be buggy.

If you are using react-native-maps or another lib that requires Google Play Services such as Exponent.js, then in addition to the instalation steps described here, you must set Google Play Services library version to match the version used by those libraries. (in this case 9.8.0)

Add following to android/build.gradle

ext {
  googlePlayServicesVersion = "9.8.0"
}

Example Apps

The repository react-native-background-geolocation-example hosts an example app for both iOS and Android platform.

Quick example

import React, { Component } from 'react';
import { Alert } from 'react-native';
import BackgroundGeolocation from '@mauron85/react-native-background-geolocation';

class BgTracking extends Component {
  componentDidMount() {
    BackgroundGeolocation.configure({
      desiredAccuracy: BackgroundGeolocation.HIGH_ACCURACY,
      stationaryRadius: 50,
      distanceFilter: 50,
      notificationTitle: 'Background tracking',
      notificationText: 'enabled',
      debug: true,
      startOnBoot: false,
      stopOnTerminate: true,
      locationProvider: BackgroundGeolocation.ACTIVITY_PROVIDER,
      interval: 10000,
      fastestInterval: 5000,
      activitiesInterval: 10000,
      stopOnStillActivity: false,
      url: 'http://192.168.81.15:3000/location',
      httpHeaders: {
        'X-FOO': 'bar'
      },
      // customize post properties
      postTemplate: {
        lat: '@latitude',
        lon: '@longitude',
        foo: 'bar' // you can also add your own properties
      }
    });

    BackgroundGeolocation.on('location', (location) => {
      // handle your locations here
      // to perform long running operation on iOS
      // you need to create background task
      BackgroundGeolocation.startTask(taskKey => {
        // execute long running task
        // eg. ajax post location
        // IMPORTANT: task has to be ended by endTask
        BackgroundGeolocation.endTask(taskKey);
      });
    });

    BackgroundGeolocation.on('stationary', (stationaryLocation) => {
      // handle stationary locations here
      Actions.sendLocation(stationaryLocation);
    });

    BackgroundGeolocation.on('error', (error) => {
      console.log('[ERROR] BackgroundGeolocation error:', error);
    });

    BackgroundGeolocation.on('start', () => {
      console.log('[INFO] BackgroundGeolocation service has been started');
    });

    BackgroundGeolocation.on('stop', () => {
      console.log('[INFO] BackgroundGeolocation service has been stopped');
    });

    BackgroundGeolocation.on('authorization', (status) => {
      console.log('[INFO] BackgroundGeolocation authorization status: ' + status);
      if (status !== BackgroundGeolocation.AUTHORIZED) {
        // we need to set delay or otherwise alert may not be shown
        setTimeout(() =>
          Alert.alert('App requires location tracking permission', 'Would you like to open app settings?', [
            { text: 'Yes', onPress: () => BackgroundGeolocation.showAppSettings() },
            { text: 'No', onPress: () => console.log('No Pressed'), style: 'cancel' }
          ]), 1000);
      }
    });

    BackgroundGeolocation.on('background', () => {
      console.log('[INFO] App is in background');
    });

    BackgroundGeolocation.on('foreground', () => {
      console.log('[INFO] App is in foreground');
    });

    BackgroundGeolocation.on('abort_requested', () => {
      console.log('[INFO] Server responded with 285 Updates Not Required');

      // Here we can decide whether we want stop the updates or not.
      // If you've configured the server to return 285, then it means the server does not require further update.
      // So the normal thing to do here would be to `BackgroundGeolocation.stop()`.
      // But you might be counting on it to receive location updates in the UI, so you could just reconfigure and set `url` to null.
    });

    BackgroundGeolocation.on('http_authorization', () => {
      console.log('[INFO] App needs to authorize the http requests');
    });

    BackgroundGeolocation.checkStatus(status => {
      console.log('[INFO] BackgroundGeolocation service is running', status.isRunning);
      console.log('[INFO] BackgroundGeolocation services enabled', status.locationServicesEnabled);
      console.log('[INFO] BackgroundGeolocation auth status: ' + status.authorization);

      // you don't need to check status before start (this is just the example)
      if (!status.isRunning) {
        BackgroundGeolocation.start(); //triggers start on start event
      }
    });

    // you can also just start without checking for status
    // BackgroundGeolocation.start();
  }

  componentWillUnmount() {
    // unregister all event listeners
    BackgroundGeolocation.removeAllListeners();
  }
}

export default BgTracking;

Instalation

Installation

Add the package to your project

yarn add @mauron85/react-native-background-geolocation

Automatic setup

Since version 0.60 React Native does linking of modules automatically. However it does it only for single module. As plugin depends on additional 'common' module, it is required to link it with:

node ./node_modules/@mauron85/react-native-background-geolocation/scripts/postlink.js

Manual setup

Android setup

In android/settings.gradle

...
include ':@mauron85_react-native-background-geolocation-common'
project(':@mauron85_react-native-background-geolocation-common').projectDir = new File(rootProject.projectDir, '../node_modules/@mauron85/react-native-background-geolocation/android/common')
include ':@mauron85_react-native-background-geolocation'
project(':@mauron85_react-native-background-geolocation').projectDir = new File(rootProject.projectDir, '../node_modules/@mauron85/react-native-background-geolocation/android/lib')
...

In android/app/build.gradle

dependencies {
    ...
    compile project(':@mauron85_react-native-background-geolocation')
    ...
}

Register the module (in MainApplication.java)

import com.marianhello.bgloc.react.BackgroundGeolocationPackage;  // <--- Import Package

public class MainApplication extends Application implements ReactApplication {
  ...
  /**
   * A list of packages used by the app. If the app uses additional views
   * or modules besides the default ones, add more packages here.
   */
  @Override
  protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new BackgroundGeolocationPackage() // <---- Add the Package
      );
  }
  ...
}

iOS setup

  1. In XCode, in the project navigator, right click Libraries โžœ Add Files to [your project's name]
  2. Add ./node_modules/@mauron85/react-native-background-geolocation/ios/RCTBackgroundGeolocation.xcodeproj
  3. In the XCode project navigator, select your project, select the Build Phases tab and in the Link Binary With Libraries section add libRCTBackgroundGeolocation.a
  4. Add UIBackgroundModes location to Info.plist
  5. Add NSMotionUsageDescription App requires motion tracking to Info.plist (required by ACTIVITY_PROVIDER)

For iOS before version 11:

  1. Add NSLocationAlwaysUsageDescription App requires background tracking to Info.plist

For iOS 11:

  1. Add NSLocationWhenInUseUsageDescription App requires background tracking to Info.plist
  2. Add NSLocationAlwaysAndWhenInUseUsageDescription App requires background tracking to Info.plist

API

configure(options, success, fail)

Parameter Type Platform Description
options JSON Object all Configure options

Configure options:

Parameter Type Platform Description Provider* Default
locationProvider Number all Set location provider @see PROVIDERS N/A DISTANCE_FILTER_PROVIDER
desiredAccuracy Number all Desired accuracy in meters. Possible values [HIGH_ACCURACY, MEDIUM_ACCURACY, LOW_ACCURACY, PASSIVE_ACCURACY]. Accuracy has direct effect on power drain. Lower accuracy = lower power drain. all MEDIUM_ACCURACY
stationaryRadius Number all Stationary radius in meters. When stopped, the minimum distance the device must move beyond the stationary location for aggressive background-tracking to engage. DIS 50
debug Boolean all When enabled, the plugin will emit sounds for life-cycle events of background-geolocation! See debugging sounds table. all false
distanceFilter Number all The minimum distance (measured in meters) a device must move horizontally before an update event is generated. @see Apple docs. DIS,RAW 500
stopOnTerminate Boolean all Enable this in order to force a stop() when the application terminated (e.g. on iOS, double-tap home button, swipe away the app). all true
startOnBoot Boolean Android Start background service on device boot. all false
interval Number Android The minimum time interval between location updates in milliseconds. @see Android docs for more information. all 60000
fastestInterval Number Android Fastest rate in milliseconds at which your app can handle location updates. @see Android docs. ACT 120000
activitiesInterval Number Android Rate in milliseconds at which activity recognition occurs. Larger values will result in fewer activity detections while improving battery life. ACT 10000
stopOnStillActivity Boolean Android @deprecated stop location updates, when the STILL activity is detected ACT true
notificationsEnabled Boolean Android Enable/disable local notifications when tracking and syncing locations all true
startForeground Boolean Android Allow location sync service to run in foreground state. Foreground state also requires a notification to be presented to the user. all false
notificationTitle String optional Android Custom notification title in the drawer. (goes with startForeground) all "Background tracking"
notificationText String optional Android Custom notification text in the drawer. (goes with startForeground) all "ENABLED"
notificationIconColor String optional Android The accent color to use for notification. Eg. #4CAF50. (goes with startForeground) all
notificationIconLarge String optional Android The filename of a custom notification icon. @see Android quirks. (goes with startForeground) all
notificationIconSmall String optional Android The filename of a custom notification icon. @see Android quirks. (goes with startForeground) all
activityType String iOS [AutomotiveNavigation, OtherNavigation, Fitness, Other] Presumably, this affects iOS GPS algorithm. @see Apple docs for more information all "OtherNavigation"
pauseLocationUpdates Boolean iOS Pauses location updates when app is paused. *@see Apple docs all false
saveBatteryOnBackground Boolean iOS Switch to less accurate significant changes and region monitory when in background all false
url String all Server url where to send HTTP POST with recorded locations @see HTTP locations posting all
syncUrl String all Server url where to send fail to post locations @see HTTP locations posting all
syncThreshold Number all Specifies how many previously failed locations will be sent to server at once all 100
httpHeaders Object all Optional HTTP headers sent along in HTTP request all
maxLocations Number all Limit maximum number of locations stored into db all 10000
postTemplate Object|Array all Customization post template @see Custom post template all

* DIS = DISTANCE_FILTER_PROVIDER ACT = ACTIVITY_PROVIDER RAW = RAW_PROVIDER

Partial reconfiguration is possible by later providing a subset of the configuration options:

BackgroundGeolocation.configure({
  debug: true
});

In this case new configuration options will be merged with stored configuration options and changes will be applied immediately.

Important: Because configuration options are applied partially, it's not possible to reset option to default value just by omitting it's key name and calling configure method. To reset configuration option to the default value, it's key must be set to null!

// Example: reset postTemplate to default
BackgroundGeolocation.configure({
  postTemplate: null
});

getConfig(success, fail)

Platform: iOS, Android

Get current configuration. Method will return all configuration options and their values in success callback. Because configure method can be called with subset of the configuration options only, getConfig method can be used to check the actual applied configuration.

BackgroundGeolocation.getConfig(function(config) {
  console.log(config);
});

start()

Platform: iOS, Android

Start background geolocation.

stop()

Platform: iOS, Android

Stop background geolocation.

getCurrentLocation(success, fail, options)

Platform: iOS, Android

One time location check to get current location of the device.

Option parameter Type Description
timeout Number Maximum time in milliseconds device will wait for location
maximumAge Number Maximum age in milliseconds of a possible cached location that is acceptable to return
enableHighAccuracy Boolean if true and if the device is able to provide a more accurate position, it will do so
Success callback parameter Type Description
location Object location object (@see Location event)
Error callback parameter Type Description
code Number Reason of an error occurring when using the geolocating device
message String Message describing the details of the error

Error codes:

Value Associated constant Description
1 PERMISSION_DENIED Request failed due missing permissions
2 LOCATION_UNAVAILABLE Internal source of location returned an internal error
3 TIMEOUT Timeout defined by `option.timeout was exceeded

checkStatus(success, fail)

Check status of the service

Success callback parameter Type Description
isRunning Boolean true/false (true if service is running)
locationServicesEnabled Boolean true/false (true if location services are enabled)
authorization Number authorization status

Authorization statuses:

  • NOT_AUTHORIZED
  • AUTHORIZED - authorization to run in background and foreground
  • AUTHORIZED_FOREGROUND iOS only authorization to run in foreground only

Note: In the Android concept of authorization, these represent application permissions.

showAppSettings()

Platform: Android >= 6, iOS >= 8.0

Show app settings to allow change of app location permissions.

showLocationSettings()

Platform: Android

Show system settings to allow configuration of current location sources.

getLocations(success, fail)

Platform: iOS, Android

Method will return all stored locations. This method is useful for initial rendering of user location on a map just after application launch.

Success callback parameter Type Description
locations Array collection of stored locations
BackgroundGeolocation.getLocations(
  function (locations) {
    console.log(locations);
  }
);

getValidLocations(success, fail)

Platform: iOS, Android

Method will return locations which have not yet been posted to server.

Success callback parameter Type Description
locations Array collection of stored locations

deleteLocation(locationId, success, fail)

Platform: iOS, Android

Delete location with locationId.

deleteAllLocations(success, fail)

Note: You don't need to delete all locations. The plugin manages the number of stored locations automatically and the total count never exceeds the number as defined by option.maxLocations.

Platform: iOS, Android

Delete all stored locations.

Note: Locations are not actually deleted from database to avoid gaps in locationId numbering. Instead locations are marked as deleted. Locations marked as deleted will not appear in output of BackgroundGeolocation.getValidLocations.

switchMode(modeId, success, fail)

Platform: iOS

Normally the plugin will handle switching between BACKGROUND and FOREGROUND mode itself. Calling switchMode you can override plugin behavior and force it to switch into other mode.

In FOREGROUND mode the plugin uses iOS local manager to receive locations and behavior is affected by option.desiredAccuracy and option.distanceFilter.

In BACKGROUND mode plugin uses significant changes and region monitoring to receive locations and uses option.stationaryRadius only.

// switch to FOREGROUND mode
BackgroundGeolocation.switchMode(BackgroundGeolocation.FOREGROUND_MODE);

// switch to BACKGROUND mode
BackgroundGeolocation.switchMode(BackgroundGeolocation.BACKGROUND_MODE);

forceSync()

Platform: Android, iOS

Force sync of pending locations. Option syncThreshold will be ignored and all pending locations will be immediately posted to syncUrl in single batch.

getLogEntries(limit, fromId, minLevel, success, fail)

Platform: Android, iOS

Return all logged events. Useful for plugin debugging.

Parameter Type Description
limit Number limits number of returned entries
fromId Number return entries after fromId. Useful if you plan to implement infinite log scrolling*
minLevel String return log entries above level. Available levels: ["TRACE", "DEBUG", "INFO", "WARN", "ERROR]
success Function callback function which will be called with log entries

*Example of infinite log scrolling

Format of log entry:

Parameter Type Description
id Number id of log entry as stored in db
timestamp Number timestamp in milliseconds since beginning of UNIX epoch
level String log level
message String log message
stackTrace String recorded stacktrace (Android only, on iOS part of message)

removeAllListeners(event)

Unregister all event listeners for given event. If parameter event is not provided then all event listeners will be removed.

Events

Name Callback param Platform Provider* Description
location Location all all on location update
stationary Location all DIS,ACT on device entered stationary mode
activity Activity Android ACT on activity detection
error { code, message } all all on plugin error
authorization status all all on user toggle location service
start all all geolocation has been started
stop all all geolocation has been stopped
foreground Android all app entered foreground state (visible)
background Android all app entered background state
abort_requested all all server responded with "285 Updates Not Required"
http_authorization all all server responded with "401 Unauthorized"

Location event

Location parameter Type Description
id Number ID of location as stored in DB (or null)
provider String gps, network, passive or fused
locationProvider Number location provider
time Number UTC time of this fix, in milliseconds since January 1, 1970.
latitude Number Latitude, in degrees.
longitude Number Longitude, in degrees.
accuracy Number Estimated accuracy of this location, in meters.
speed Number Speed if it is available, in meters/second over ground.
altitude Number Altitude if available, in meters above the WGS 84 reference ellipsoid.
bearing Number Bearing, in degrees.
isFromMockProvider Boolean (android only) True if location was recorded by mock provider
mockLocationsEnabled Boolean (android only) True if device has mock locations enabled

Locations parameters isFromMockProvider and mockLocationsEnabled are not posted to url or syncUrl by default. Both can be requested via option postTemplate.

Note: Do not use location id as unique key in your database as ids will be reused when option.maxLocations is reached.

Note: Android currently returns time as type of String (instead of Number) @see issue #9685

Activity event

Activity parameter Type Description
confidence Number Percentage indicating the likelihood user is performing this activity.
type String "IN_VEHICLE", "ON_BICYCLE", "ON_FOOT", "RUNNING", "STILL",
"TILTING", "UNKNOWN", "WALKING"

Event listeners can registered with:

const eventSubscription = BackgroundGeolocation.on('event', callbackFn);

And unregistered:

eventSubscription.remove();

Note: Components should unregister all event listeners in componentWillUnmount method, individually, or with removeAllListeners

HTTP locations posting

All locations updates are recorded in the local db at all times. When the App is in foreground or background, in addition to storing location in local db, the location callback function is triggered. The number of locations stored in db is limited by option.maxLocations and never exceeds this number. Instead, old locations are replaced by new ones.

When option.url is defined, each location is also immediately posted to url defined by option.url. If the post is successful, the location is marked as deleted in local db.

When option.syncUrl is defined, all locations that fail to post will be coalesced and sent in some time later in a single batch. Batch sync takes place only when the number of failed-to-post locations reaches option.syncTreshold. Locations are sent only in single batch when the number of locations reaches option.syncTreshold. (No individual locations will be sent)

The request body of posted locations is always an array, even when only one location is sent.

Warning: option.maxLocations has to be larger than option.syncThreshold. It's recommended to be 2x larger. In any other case the location syncing might not work properly.

Custom post template

With option.postTemplate it is possible to specify which location properties should be posted to option.url or option.syncUrl. This can be useful to reduce the number of bytes sent "over the "wire".

All wanted location properties have to be prefixed with @. For all available properties check Location event.

Two forms are supported:

jsonObject

BackgroundGeolocation.configure({
  postTemplate: {
    lat: '@latitude',
    lon: '@longitude',
    foo: 'bar' // you can also add your own properties
  }
});

jsonArray

BackgroundGeolocation.configure({
  postTemplate: ['@latitude', '@longitude', 'foo', 'bar']
});

Note: Keep in mind that all locations (even a single one) will be sent as an array of object(s), when postTemplate is jsonObject and array of array(s) for jsonArray!

Android Headless Task (Experimental)

A special task that gets executed when the app is terminated, but the plugin was configured to continue running in the background (option stopOnTerminate: false). In this scenario the Activity was killed by the system and all registered event listeners will not be triggered until the app is relaunched.

Note: Prefer configuration options url and syncUrl over headless task. Use it sparingly!

Task event

Parameter Type Description
event.name String Name of the event [ "location", "stationary", "activity" ]
event.params Object Event parameters. @see Events

Keep in mind that the callback function lives in an isolated scope. Variables from a higher scope cannot be referenced!

Following example requires CORS enabled backend server.

Warning: callback function must by async!

BackgroundGeolocation.headlessTask(async (event) => {
    if (event.name === 'location' ||
      event.name === 'stationary') {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://192.168.81.14:3000/headless');
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.send(JSON.stringify(event.params));
    }
});

Important:

After application is launched again (main activity becomes visible), it is important to call start method to rebind all event listeners.

BackgroundGeolocation.checkStatus(({ isRunning }) => {
  if (isRunning) {
    BackgroundGeolocation.start(); // service was running -> rebind all listeners
  }
});

Transforming/filtering locations in native code

In some cases you might want to modify a location before posting, reject a location, or any other logic around incoming locations - in native code. There's an option of doing so with a headless task, but you may want to preserve battery, or do more complex actions that are not available in React.

In those cases you could register a location transform.

Android example:

When the Application is initialized (which also happens before services gets started in the background), write some code like this:

BackgroundGeolocationFacade.setLocationTransform(new LocationTransform() {
    @Nullable
    @Override
    public BackgroundLocation transformLocationBeforeCommit(@NonNull Context context, @NonNull BackgroundLocation location) {
    // `context` is available too if there's a need to use a value from preferences etc.

    // Modify the location
    location.setLatitude(location.getLatitude() + 0.018);

    // Return modified location
    return location;

    // You could return null to reject the location,
    // or if you did something else with the location and the library should not post or save it.
    }
});

iOS example:

In didFinishLaunchingWithOptions delegate method, write some code like this:

BackgroundGeolocationFacade.locationTransform = ^(MAURLocation * location) {
  // Modify the location
  location.latitude = @(location.latitude.doubleValue + 0.018);
  
  // Return modified location
  return location;
  
  // You could return null to reject the location,
  // or if you did something else with the location and the library should not post or save it.
};

Advanced plugin configuration

Change Account Service Name (Android)

Add string resource "account_name" into "android/app/src/main/res/values/strings.xml"

<string name="account_name">Sync Locations</string>

Example of backend server

Background-geolocation-server is a backend server written in nodejs with CORS - Cross-Origin Resource Sharing support. There are instructions how to run it and simulate locations on Android, iOS Simulator and Genymotion.

Debugging

Submit crash log

TODO

Debugging sounds

Event ios android
Exit stationary region Calendar event notification sound dialtone beep-beep-beep
Geolocation recorded SMS sent sound tt short beep
Aggressive geolocation engaged SIRI listening sound
Passive geolocation engaged SIRI stop listening sound
Acquiring stationary location sound "tick,tick,tick" sound
Stationary location acquired sound "bloom" sound long tt beep

NOTE: For iOS in addition, you must manually enable the Audio and Airplay background mode in Background Capabilities to hear these debugging sounds.

Geofencing

Try using react-native-boundary. Let's keep this plugin lightweight as much as possible.

Changelog

See CHANGES.md

See ๅ˜ๆ›ด๏ผˆ้žๅฎ˜ๆ–นไธญๆ–‡็‰ˆ๏ผ‰

react-native-background-geolocation's People

Contributors

asafron avatar danielgindi avatar diegogurpegui avatar djereg avatar farruxx avatar hugosbg avatar jwaldrip avatar kennytian avatar koenpunt avatar luisguilhermemsalmeida avatar mantaroh avatar mauron85 avatar morrislaptop avatar msmyrk avatar patrykcysarz avatar roconda avatar tpisto avatar wesleycoder 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

react-native-background-geolocation's Issues

Question: track geolocation only 1 time

I know this library is purposed for background geolocation that listen geo movement. But my usage is: I want to capture current location, if I got current location, then stop to listen. It can be a button that refresh current geo every time I click button. I want to replicate RN built-in geolocation getCurrentPosition, which is make me very frustrate because of bug. I just want to make sure that this library can accommodate my usage, so I ask here. Thanks.

Could not resolve all dependencies for configuration ':app:_debugApk'

Hi,
I have done react-native setup and have successfully running other android react-native apps.

But In my react-native project, I just insalled npm install react-native-mauron85-background-geolocation --save
then added as below

In android/settings.gradle

include ':react-native-mauron85-background-geolocation', ':app'
project(':react-native-mauron85-background-geolocation').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-mauron85-background-geolocation/android')

In android/app/build.gradle

dependencies {
...
compile project(':react-native-mauron85-background-geolocation')
...
}

Registered Module in MainApplication.java
import com.marianhello.react.BackgroundGeolocationPackage; // <--- Import Package
@OverRide
protected List getPackages() {
return Arrays.asList(
new MainReactPackage(),
new BackgroundGeolocationPackage() // <---- Add the Package
);
}

then I ran react-native run-android, it fails with below error

Building and installing the app on the device (cd android && ./gradlew installDebug)...

FAILURE: Build failed with an exception.

What went wrong:
A problem occurred configuring project ':app'.
Could not resolve all dependencies for configuration ':app:_debugApk'.
Configuration with name 'default' not found.
Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED

Total time: 5.074 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html

Can you please help understand whats wrong

Crash on IOS, always show "better location found"

Environment

  • Plugin version: 0.2.0-alpha.7
  • Platform: iOS
  • OS version: 8.1
  • Device manufacturer and model: iphone5
  • React Native version:0.42.3
  • Plugin configuration options:
BackgroundGeolocation.configure({
          // Geolocation Config
          desiredAccuracy: 10,
          stationaryRadius: 25,
          distanceFilter: 30,
          // Activity Recognition
          stopTimeout: 1,
          // Application config
          debug: false, // <-- enable this hear sounds for background-geolocation
          //life-cycle.
          logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
          locationProvider: Platform.OS == 'android'? BackgroundGeolocation.provider.ANDROID_DISTANCE_FILTER_PROVIDER : null,
          stopOnTerminate: false,   // <-- Allow the background-service to continue tracking when user closes the app.
          startOnBoot: true,        // <-- Auto start tracking when device is powered-up.
          // HTTP / SQLite config
          url: "http://nodemiddleware.songxiaocai.org/location",
          batchSync: false,       // <-- [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.
          autoSyncThreshold: 1,
          maxDaysToPersist: 1,    // <-- Maximum days to persist a location in plugin's SQLite database when HTTP fails
          preventSuspend: true,
      });

Context

image

Disable Notifications Completely

I wish to remove all the notifications from the app. Is it possible without letting OS to kill it. I want everything the same except notifications.

url inside the BackgroundGeolocation.configure.

I haven't been able to get the automatic post sent on location updates. Do you have any more info on how the fetch is built or how to debug it?

I have been calling a fetch in BackgroundGeolocation.on's callback. This seems to be working great:

  • Are there any downsides to doing it this way instead of using your automatic post?
  • Are there limitations in what I can put in that callback?

Thanks for the info. And for an awesome plug-in.
Dan

Plugin version: v0.1.1
Platform: iOS
OS version: 9
Device manufacturer and model: Iphone 5 SE
React Native version: 0.42
Plugin configuration options:
BackgroundGeolocation.configure({
desiredAccuracy: 1,
stationaryRadius: 1,
distanceFilter: 1,
debug: true,
stopOnTerminate: false,
interval: 1000,
httpHeaders: {
'X-FOO': 'bar'
}
}, function () {});
Link to your project: I'm not allowed..

Geolocation logging just when app closed

Hello @mauron85 !
I need to logging geoposition on server side by sending location payload when app is cilled.
So is it possible to make such logic:
on app will close - BackgroundLocation.start()
on app will start - BackgroundLocation.stop()
?

thanks in advance!

App Failed to build with ios setup instructions

I have followed the setup instructions in the readme for IOS and am getting failures when trying to run

  • Plugin version: 0.2.0-alpha.5
  • Platform: iOS
  • OS version: 10.0
  • Device manufacturer and model: iPhone 6 (10.0)
  • React Native version: 0.33.0 (react version 15.3.1)
  • Plugin configuration options:
  • Link to your project: https://github.com/sdb1228/RNbackgroundLocationTest

Context

I Followed the instructions word for word on the readme of how to set up the project. I have also tried react-native link and can't seem to get it running for IOS

Expected Behavior

it should run and not fail on compile

Actual Behavior

it doesn't run

Steps to Reproduce

follow steps on readme

Context

I can't use your npm module

Debug logs

The following build commands failed:
Libtool /Users/stevenburnett/Desktop/foo/ios/build/Build/Products/Debug-iphonesimulator/libRCTBackgroundGeolocation.a normal x86_64
(1 failure)
Installing build/Build/Products/Debug-iphonesimulator/foo.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist

Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/foo.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist

I have checked this and it does exist it just doesn't like me for some reason.

Some more relevant information.. Actual error from Xcode:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: can't open file: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator10.0.sdk/usr/lib/libsqlite3.tbd (No such file or directory)

[iOS] Crash when start the app

Environment

  • Plugin version: 0.2.0-alpha.7
  • Platform: iOS
  • OS version: 10.2
  • Device manufacturer and model: iPhone 5 (simulator)
  • React Native version: 0.42

Context

When I start the app the line 112 of LocationManager.m throw a error

The line:

locationManager.allowsBackgroundLocationUpdates = YES;

The error:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: !stayUp || CLClientIsBackgroundable(internal->fClient)'

*** First throw call stack:
(
0 CoreFoundation 0x06139bf2 __exceptionPreprocess + 194
1 libobjc.A.dylib 0x04c38e66 objc_exception_throw + 52
2 CoreFoundation 0x0613dd12 +[NSException raise:format:arguments:] + 130
3 Foundation 0x04838af4 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 94
4 CoreLocation 0x01880ad8 CLClientGetCapabilities + 12072
7 libobjc.A.dylib 0x04c4e36b +[NSObject new] + 69prepareModulesWithDispatchGroup:]_block_invoke + 139
13 libdispatch.dylib 0x06f7d396 _dispatch_call_block_and_release + 15
14 libdispatch.dylib 0x06fa8cc3 _dispatch_client_callout + 14
15 libdispatch.dylib 0x06f87c55 _dispatch_main_queue_callback_4CF + 662
16 CoreFoundation 0x060fa05e CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE + 14
17 CoreFoundation 0x060bc8df __CFRunLoopRun + 2319
18 CoreFoundation 0x060bbd5b CFRunLoopRunSpecific + 395
19 CoreFoundation 0x060bbbbb CFRunLoopRunInMode + 123
20 GraphicsServices 0x0927ab4c GSEventRunModal + 177
21 GraphicsServices 0x0927a9c7 GSEventRun + 80
22 UIKit 0x02ebbff3 UIApplicationMain + 148
24 libdyld.dylib 0x06fe3799 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

java.lang.NoClassDefFoundError: com.marianhello.bgloc.ActivityRecognitionLocationProvider

Trying to include your project in my react-native app and run the example in the readme, I get an app crash with the below stacktrace...

D/AndroidRuntime(16589): Shutting down VM
E/AndroidRuntime(16589): FATAL EXCEPTION: main
E/AndroidRuntime(16589): Process: com.astarreactnative, PID: 16589
E/AndroidRuntime(16589): java.lang.NoClassDefFoundError: com.marianhello.bgloc.ActivityRecognitionLocationProvider
E/AndroidRuntime(16589): 	at com.marianhello.bgloc.LocationProviderFactory.getInstance(LocationProviderFactory.java:37)
E/AndroidRuntime(16589): 	at com.marianhello.bgloc.LocationService.onStartCommand(LocationService.java:237)
E/AndroidRuntime(16589): 	at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2924)
E/AndroidRuntime(16589): 	at android.app.ActivityThread.access$2100(ActivityThread.java:155)
E/AndroidRuntime(16589): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1415)
E/AndroidRuntime(16589): 	at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(16589): 	at android.os.Looper.loop(Looper.java:135)
E/AndroidRuntime(16589): 	at android.app.ActivityThread.main(ActivityThread.java:5343)
E/AndroidRuntime(16589): 	at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(16589): 	at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime(16589): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
E/AndroidRuntime(16589): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:702)
D/ActivityManager(  930): IKSWL-9411 handleMessage SHOW_ERROR_MSG

I do not have the same issue with the other provider, so maybe it is a packaging issue?

Your Environment

  • Plugin version: "^0.2.0-alpha.5",
  • Platform: Android
  • OS version: 5.1.1
  • Device manufacturer and model: Moto G3
  • React Native version: 0.36.0
  • Plugin configuration options: Copied from Readme

One thing to note, I had to fight play services dependencies issues between this app and react-native-google-signin. I'm not sure if I could be causing the issue, but I did pin the following compile dependencies to skirt those transitive dep issues:

/android/app/build.gradle
...
    compile 'com.google.android.gms:play-services-auth:9.8.0'
    compile 'com.google.android.gms:play-services-base:9.8.0'
    compile 'com.google.android.gms:play-services-maps:9.8.0'
    compile 'com.google.android.gms:play-services-gcm:9.8.0'
...

Some more logs,

I/FA      (16589): App measurement is starting up, version: 9877
I/FA      (16589): To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
I/FA      (16589): To enable faster debug mode event logging run:
I/FA      (16589):   adb shell setprop firebase.analytics.debug-mode com.astarreactnative
I/FirebaseInitProvider(16589): FirebaseApp initialization successful
I/com.marianhello.bgloc.LocationService(16589): Creating LocationService
W/AccountManagerService(  930): insertAccountIntoDatabase: Account {name=dummy, type=com.astarreactnative.account}, skipping since the account already exists
I/com.marianhello.bgloc.LocationService(16589): Received start startId: 1 intent: Intent { flg=0x4 cmp=com.astarreactnative/com.marianhello.bgloc.LocationService (has extras) }
I/com.marianhello.bgloc.LocationService(16589): Network condition changed hasConnectivity: true
D/com.marianhello.bgloc.LocationService(16589): Will start service with: Config[distanceFilter=50 stationaryRadius=50.0 desiredAccuracy=10 interval=5000 fastestInterval=2000 activitiesInterval=5000 isDebugging=true stopOnTerminate=false stopOnStillActivity=false startOnBoot=false startForeground=true locationProvider=1 nTitle=Background tracking nText=enabled nIconLarge=null nIconSmall=null nIconColor=null url=null syncUrl=null syncThreshold=100 httpHeaders={} maxLocations=10000]
I/art     (16589): Rejecting re-init on previously-failed class java.lang.Class<com.marianhello.bgloc.ActivityRecognitionLocationProvider>
I/art     (16589): Rejecting re-init on previously-failed class java.lang.Class<com.marianhello.bgloc.ActivityRecognitionLocationProvider>
I/art     (16589): Rejecting re-init on previously-failed class java.lang.Class<com.marianhello.bgloc.ActivityRecognitionLocationProvider>
D/AndroidRuntime(16589): Shutting down VM
E/AndroidRuntime(16589): FATAL EXCEPTION: main
E/AndroidRuntime(16589): Process: com.astarreactnative, PID: 16589
E/AndroidRuntime(16589): java.lang.NoClassDefFoundError: com.marianhello.bgloc.ActivityRecognitionLocationProvider
E/AndroidRuntime(16589): 	at com.marianhello.bgloc.LocationProviderFactory.getInstance(LocationProviderFactory.java:37)
E/AndroidRuntime(16589): 	at com.marianhello.bgloc.LocationService.onStartCommand(LocationService.java:237)
E/AndroidRuntime(16589): 	at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2924)
E/AndroidRuntime(16589): 	at android.app.ActivityThread.access$2100(ActivityThread.java:155)
E/AndroidRuntime(16589): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1415)
E/AndroidRuntime(16589): 	at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(16589): 	at android.os.Looper.loop(Looper.java:135)
E/AndroidRuntime(16589): 	at android.app.ActivityThread.main(ActivityThread.java:5343)
E/AndroidRuntime(16589): 	at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(16589): 	at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime(16589): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
E/AndroidRuntime(16589): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:702)
D/ActivityManager(  930): IKSWL-9411 handleMessage SHOW_ERROR_MSG
W/ActivityManager(  930): IKSWL-9411 mShowDialogs:true mSleeping:false mShuttingDown:false
W/DropBoxManagerService(  930): Dropping: data_app_crash (1065 > 0 bytes)
D/WindowManager(  930): IKSWL-9411 focusChangedLw lastFocus=Window{2ea3296f u0 com.google.android.googlequicksearchbox/com.google.android.launcher.GEL} newFocus=Window{37c6b616 u0 Application Error: com.astarreactnative}
V/WindowManager(  930): ** SHOWING status bar: top is not fullscreen

The only react-native logs I see:

I/ReactNativeJS(18357): start recording pressed.
I/ReactNativeJS(18357): new route! 1479574664831
I/ReactNativeJS(18357): [DEBUG] BackgroundGeolocation started successfully

I get the same logs using the ANDROID_DISTANCE_FILTER_PROVIDER provider, but it does seem to work.

Thanks in advance, and let me know if I can provide anything else.

App crashes

Your Environment

  • Plugin version: v0.1.1
  • Platform: iOS or Android: Android
  • OS version: Ubuntu 16.10
  • Device manufacturer and model: Nexus 5
  • React Native version: 0.42.0
  • Plugin configuration options: N/A

Context

The app does not start. Please help

Debug logs

:react-native-mauron85-background-geolocation:generateReleaseBuildConfig UP-TO-DATE
:react-native-mauron85-background-geolocation:generateReleaseResValues UP-TO-DATE
:react-native-mauron85-background-geolocation:generateReleaseResources UP-TO-DATE
:react-native-mauron85-background-geolocation:mergeReleaseResources UP-TO-DATE
:react-native-mauron85-background-geolocation:processReleaseManifest UP-TO-DATE
:react-native-mauron85-background-geolocation:processReleaseResources
:react-native-mauron85-background-geolocation:generateReleaseSources
:react-native-mauron85-background-geolocation:incrementalReleaseJavaCompilationSafeguard UP-TO-DATE
:react-native-mauron85-background-geolocation:compileReleaseJavaWithJavac
Full recompilation is required because at least one of the classes of removed jar 'classes.jar' requires it. Analysis took 0.925 secs.
Note: /home/dinesh/projects/GoLoadDriver/node_modules/react-native-mauron85-background-geolocation/android/lib/src/main/java/com/marianhello/react/BackgroundGeolocationModule.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
:react-native-mauron85-background-geolocation:extractReleaseAnnotations
:react-native-mauron85-background-geolocation:mergeReleaseShaders UP-TO-DATE
:react-native-mauron85-background-geolocation:compileReleaseShaders UP-TO-DATE
:react-native-mauron85-background-geolocation:generateReleaseAssets UP-TO-DATE
:react-native-mauron85-background-geolocation:mergeReleaseAssets UP-TO-DATE
:react-native-mauron85-background-geolocation:mergeReleaseProguardFiles UP-TO-DATE
:react-native-mauron85-background-geolocation:packageReleaseRenderscript UP-TO-DATE
:react-native-mauron85-background-geolocation:packageReleaseResources UP-TO-DATE
:react-native-mauron85-background-geolocation:processReleaseJavaRes UP-TO-DATE
:react-native-mauron85-background-geolocation:transformResourcesWithMergeJavaResForRelease UP-TO-DATE
:react-native-mauron85-background-geolocation:transformClassesAndResourcesWithSyncLibJarsForRelease UP-TO-DATE

-adb logcat

03-16 00:53:54.375 5137 5152 E AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
03-16 00:53:54.375 5137 5152 E AndroidRuntime: Process: com.goloaddriver, PID: 5137
03-16 00:53:54.375 5137 5152 E AndroidRuntime: java.lang.RuntimeException: An error occurred while executing doInBackground()
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:309)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:242)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at java.lang.Thread.run(Thread.java:818)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: Caused by: java.lang.NoClassDefFoundError: com.google.android.gms.maps.GoogleMapOptions
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at com.airbnb.android.react.maps.AirMapManager.(AirMapManager.java:54)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at com.airbnb.android.react.maps.MapsPackage.createViewManagers(MapsPackage.java:39)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at com.facebook.react.ReactInstanceManager.createAllViewManagers(ReactInstanceManager.java:711)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at com.facebook.react.CoreModulesPackage.createUIManager(CoreModulesPackage.java:218)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at com.facebook.react.CoreModulesPackage.access$200(CoreModulesPackage.java:74)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at com.facebook.react.CoreModulesPackage$8.get(CoreModulesPackage.java:151)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at com.facebook.react.CoreModulesPackage$8.get(CoreModulesPackage.java:148)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at com.facebook.react.LazyReactPackage.createNativeModules(LazyReactPackage.java:76)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at com.facebook.react.NativeModuleRegistryBuilder.processPackage(NativeModuleRegistryBuilder.java:88)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at com.facebook.react.ReactInstanceManager.processPackage(ReactInstanceManager.java:950)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at com.facebook.react.ReactInstanceManager.createReactContext(ReactInstanceManager.java:880)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at com.facebook.react.ReactInstanceManager.access$600(ReactInstanceManager.java:104)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at com.facebook.react.ReactInstanceManager$ReactContextInitAsyncTask.doInBackground(ReactInstanceManager.java:218)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at com.facebook.react.ReactInstanceManager$ReactContextInitAsyncTask.doInBackground(ReactInstanceManager.java:197)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:295)
03-16 00:53:54.375 5137 5152 E AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:237)

Status / Plan of this fork

Hi! Amazing work of both of these plugins. Just wondering if you're planning on keeping this fork up to date with the cordova counterpart? Im trying to decide on goin with react native or cordova for my app, which will probably be using one of these :)

Cannot restart the service when users starts to move again if stopOnStillActivity = true

Your Environment

  • Platform: Android

Context

I want the GPS tracking to stop when the users stop moving and restarts when he starts to move again. so i used the config property stopOnStillActivity=true. then i found no way to know that the service had stopped because of StillActivity so i can restart it again.

Possible Fix

It would be better if there is an event exposed that informs us with changing the Activity mode

"property has a previous declaration" while building iOS app

When I setup my project with the newest version, add this library and build the app an error occurs.

Your Environment

  • Plugin version: 0.2.0-alpha.6
  • Platform: iOS
  • OS version: 10.0
  • Device manufacturer and model: iPhone Simulator 6
  • React Native version: 0.40.0

Context

I tried two versions: 0.2.0-alpha.5 (from master) and 0.2.0-alpha.6 (from next).
I followed all the instructions and run react-native run ios

Expected Behavior

The build should not fail and the app should run

Actual Behavior

The build fails with the error message:
error: property has a previous declaration

Possible Fix

I looks like it occur because of a major change in 0.40.0.
See release: https://github.com/facebook/react-native/releases/tag/v0.40.0

So replacing #import "RCTBridge.h" with #import "React/RCTBridge.h" solved my problem.

Steps to Reproduce

  1. react-native init ReactNativeGeolocationBackgroundThread
  2. npm install react-native-mauron85-background-geolocation --save
  3. react-native run-ios

Debug logs

~/ios/build/Build/Products/Debug-iphonesimulator/include/React/RCTBridge.h:1 70:61: error: property has a previous declaration @property (nonatomic, weak, readonly) id<RCTBridgeDelegate> delegate;

Compatibility with React Native 0.40

I upgraded RN to v0.40 and my project can't build anymore on iOS.
Would this be linked to the breaking changes of the version 0.40 ? https://github.com/facebook/react-native/releases/tag/v0.40.0

I precise that it worked well on RN v0.37.

However, it finds me 9 issues on the build in the RTCBackgroundGeolocation library.

Problem #1

/node_modules/react-native/React/Base/RCTBridge.h:65:1: Duplicate interface definition for class 'RCTBridge'

Problem #2

/node_modules/react-native/React/Base/RCTBridge.h:154:55: Property has a previous declaration
/node_modules/react-native/React/Base/RCTBridge.h:159:48: Property has a previous declaration
/node_modules/react-native/React/Base/RCTBridge.h:165:37: Property has a previous declaration
/node_modules/react-native/React/Base/RCTBridge.h:170:61: Property has a previous declaration
/node_modules/react-native/React/Base/RCTBridge.h:175:53: Property has a previous declaration
/node_modules/react-native/React/Base/RCTBridge.h:180:56: Property has a previous declaration
/node_modules/react-native/React/Base/RCTBridge.h:185:54: Property has a previous declaration
/node_modules/react-native/React/Base/RCTBridge.h:190:63: Property has a previous declaration

Leaking ServiceConnection

Hey there, i get this error message a lot of time. And i am not sure how to handle this or how to fix this....

E  Activity com.bal.bla.MainActivity has leaked ServiceConnection com.marianhello.react.BackgroundGeolocationModule$1@39337a07 that was originally bound here
E  android.app.ServiceConnectionLeaked: Activity com.bla.bla.MainActivity has leaked ServiceConnection com.marianhello.react.BackgroundGeolocationModule$1@39337a07 that was originally bound here
E      at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1077)
E      at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:971)
E      at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1782)
E      at android.app.ContextImpl.bindService(ContextImpl.java:1765)
E      at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
E      at com.marianhello.react.BackgroundGeolocationModule.doBindService(BackgroundGeolocationModule.java:277)
E      at com.marianhello.react.BackgroundGeolocationModule.startAndBindBackgroundService(BackgroundGeolocationModule.java:242)
E      at com.marianhello.react.BackgroundGeolocationModule.start(BackgroundGeolocationModule.java:215)
E      at java.lang.reflect.Method.invoke(Native Method)
E      at java.lang.reflect.Method.invoke(Method.java:372)
E      at com.facebook.react.bridge.BaseJavaModule$JavaMethod.invoke(BaseJavaModule.java:319)
E      at com.facebook.react.bridge.NativeModuleRegistry$ModuleDefinition.call(NativeModuleRegistry.java:187)
E      at com.facebook.react.bridge.NativeModuleRegistry.call(NativeModuleRegistry.java:62)
E      at com.facebook.react.bridge.CatalystInstanceImpl$NativeModulesReactCallback.call(CatalystInstanceImpl.java:432)
E      at com.facebook.react.bridge.queue.NativeRunnableDeprecated.run(Native Method)
E      at android.os.Handler.handleCallback(Handler.java:739)
E      at android.os.Handler.dispatchMessage(Handler.java:95)
E      at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:31)
E      at android.os.Looper.loop(Looper.java:135)
E      at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:193)
E      at java.lang.Thread.run(Thread.java:818)

Any ideas on this?

RN 29.2
Android

isLocationEnabled usage?

Hi there, was wondering how to use the function isLocationEnabled. I tried calling it but I keep getting this error:

screen shot 2016-10-06 at 4 28 26 pm

Still a novice in JS so sorry if I misread the docs! ๐Ÿ™

Update notificationText

How can I update notificationText in drawer dynamically? Let's say I want user know how long the distance by see text on notification drawer. Thanks.

Cause react-native-fingerprint-android not working when installed

Your Environment

Context

When mauron85/react-native-background-geolocation is installed, jariz/react-native-fingerprint-android not able to work properly. But if the bg geolocation package is removed, it's working fine.

Debug logs

Debug logs of fingerprint package when background geolocation package is installed

isHardwareDetected= false -->!This should return true
hasPermission = true
hasEnrolledFingerprints = false -->!This should return true

react-native run-android build fail

Your Environment

  • Plugin version: react-native-mauron85-background-geolocation": "^0.2.0-alpha.5",
  • Platform: Android
  • OS version: MACOS 10.1
  • Device manufacturer and model: N/A
  • React Native version: 0.39.2, "react": "^15.4.1", "react-native-maps": "^0.12.2",
  • Plugin configuration options: N/A
  • Link to your project:

react-native run-ios is OK!

BUT, > react-native run-android ...build fail
:when except 'react-native-mauron85-background-geolocation' module, android build success.
why? how to fix it? help me please...

Context

-- StackTrace result =>
at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:127)
at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
Caused by: org.gradle.api.UnknownProjectException: Cannot evaluate module react-native-mauron85-background-geolocation : Configuration with name 'default' not found.
at
com.android.build.gradle.internal.DependencyManager.ensureConfigured(DependencyManager.java:728)
at com.android.build.gradle.internal.DependencyManager.resolveDependencyForConfig(DependencyManager.java:240)

22:08:37.485 [DEBUG] [org.gradle.api.internal.artifacts.ivyservice.resolveengine.oldresult.TransientConfigurationResultsBuilder] Flushing resolved configuration data in Binary store in /private/var/folders/r3/h0j25sqs7l19n4ntqjtq17040000gn/T/gradle2243088338185070650.bin. Wrote root ddpstyleapp:react-native-mauron85-background-geolocation:unspecified:classpath.
22:08:37.489 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Waiting to acquire shared lock on proj remapped class cache for c89y9hb456dzckosaoecwcvdm (/Users/mskim/.gradle/caches/2.14.1/scripts-remapped/build_8cu99wbepomhawmoowtsxpnnw/c89y9hb456dzckosaoecwcvdm/proj-6772558678143434850).
22:08:37.542 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Lock acquired.
22:08:37.542 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Releasing lock on proj remapped class cache for c89y9hb456dzckosaoecwcvdm (/Users/mskim/.gradle/caches/2.14.1/scripts-remapped/build_8cu99wbepomhawmoowtsxpnnw/c89y9hb456dzckosaoecwcvdm/proj-6772558678143434850).
22:08:37.552 [DEBUG] [org.gradle.configuration.project.BuildScriptProcessor] Timing: Running the build script took 0.081 secs
22:08:37.559 [ERROR] [org.gradle.BuildExceptionReporter]
22:08:37.559 [ERROR] [org.gradle.BuildExceptionReporter] FAILURE: Build failed with an exception.
22:08:37.559 [ERROR] [org.gradle.BuildExceptionReporter]
22:08:37.560 [ERROR] [org.gradle.BuildExceptionReporter] * What went wrong:
22:08:37.560 [ERROR] [org.gradle.BuildExceptionReporter] A problem occurred configuring project ':app'.
22:08:37.560 [ERROR] [org.gradle.BuildExceptionReporter] > Cannot evaluate module react-native-mauron85-background-geolocation : Configuration with name 'default' not found.
22:08:37.560 [ERROR] [org.gradle.BuildExceptionReporter]
22:08:37.560 [ERROR] [org.gradle.BuildExceptionReporter] * Try:
22:08:37.560 [ERROR] [org.gradle.BuildExceptionReporter] Run with --stacktrace option to get the stack trace.
22:08:37.560 [LIFECYCLE] [org.gradle.BuildResultLogger]
22:08:37.560 [LIFECYCLE] [org.gradle.BuildResultLogger] BUILD FAILED
22:08:37.560 [LIFECYCLE] [org.gradle.BuildResultLogger]
22:08:37.560 [LIFECYCLE] [org.gradle.BuildResultLogger] Total time: 7.799 secs
22:08:37.578 [DEBUG] [org.gradle.api.internal.artifacts.ivyservice.ivyresolve.memcache.InMemoryCachedRepositoryFactory] In-memory dependency metadata cache closed. Repos cached: 617, cache instances: 7, modules served from cache: 8433, artifacts: 1128

Expected Behavior

Build OK

Actual Behavior

Build Fail

Possible Fix

Steps to Reproduce

  1. Android setup OK (following your guide)
  2. Dependencies OK

Context

Debug logs

on location event i am getting continous location object.

i am getting continous gettting location object on location event i have bind it with firebase and it frequent writing data if device is in steady status(not moving)

it should be return location object only when we move given moving radious.

kindly guide me if i am in wrong direction

please have a look on code which i have written for firebase io
BackgroundGeolocation.on('location', (location) => {
//handle your locations here
//location = JSON.stringify(location);
timekey = JSON.stringify(location.time);
timekey = timekey.toString();
newPostKey = firebase.database().ref().child('gps').push().key;
if(uid != 0)
{
firebaseApp.database().ref('gps/' + uid+"/"+newPostKey).set({
location
});
}
});

i want location object only in moving status of device
can you please elaborate me more in this that how it would it be possible?

Actual Behavior

Possible Fix

Steps to Reproduce

Context

Debug logs

Conflicting provider when trying to install multiple build types on one device

Your Environment

  • Plugin version: 0.2.0-alpha.6
  • Platform: Android
  • OS version: Android API 25
  • React Native version: 0.40.0

Context

I've created multiple buildTypes for android - debug, releaseStaging and release in order to update the app via code push. When trying to install staging build on the device where there is a debug build already installed I am getting an error:

INSTALL_FAILED_CONFLICTING_PROVIDER: Package couldn't be installed in /data/app/com.myapp.app.staging-1: Can't install because provider name com.marianhello.authority (in package com.myapp.app.staging) is already used by com.myapp.app.debug

I already have applicationId defined

android {
    defaultConfig {
        applicationId 'com.example.myproject'
    }
}

Also tried this fix http://gradlewhy.ghost.io/overcoming-install-failed-conflicting-provider/ which did not help - not sure what to write in AndroidManifest.xml in take as android:name as my app has no content provider.

Any ideas how to solve this?

Disable all notifications.

Environment

  • Plugin version: "react-native-mauron85-background-geolocation": "^0.2.0-alpha.5"
  • Platform: Android
  • OS version: 7.0
  • Device manufacturer and model: Motorola Nexus 6
  • React Native version: "react-native": "^0.29.2"

Context

This bug does not seem to be new (#3)

I also tried this approach (#29), which didn't help either

I also changed the debug value inside of BackgroundGeolocationModule.java to false to test this - didn't affect it in any way ... help please..

./gradlew clean and rebuild does not help either.

The Notification stays even after I manually close the App - the only thing that "helps" is to uninstall the App.

UPDATE:
Just looked through the README and found this debug description:

When enabled, the plugin will emit sounds for life-cycle events of background-geolocation! See debugging sounds table.

So ... Is this really just for the debug sounds? Or is the part about "showing the notification" just missing in there?

Unable to start service

Your Environment

  • Plugin version: 0.2.0-alpha.6
  • Platform: Android
  • OS version: 5.1.1
  • React Native version:0.34
  • Plugin configuration options:

Context

java.lang.RuntimeException: Unable to start service com.marianhello.bgloc.LocationService@33bd9b8e with null: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Boolean com.marianhello.bgloc.Config.getStopOnTerminate()' on a null object reference
	at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3124)
	at android.app.ActivityThread.access$2100(ActivityThread.java:176)
	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1550)
	at android.os.Handler.dispatchMessage(Handler.java:111)
	at android.os.Looper.loop(Looper.java:192)
	at android.app.ActivityThread.main(ActivityThread.java:5619)
	at java.lang.reflect.Method.invoke(Native Method)
	at java.lang.reflect.Method.invoke(Method.java:372)
	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:976)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Boolean com.marianhello.bgloc.Config.getStopOnTerminate()' on a null object reference
	at com.marianhello.bgloc.LocationService.onTaskRemoved(LocationService.java:200)
	at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3109)
	... 9 more
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Boolean com.marianhello.bgloc.Config.getStopOnTerminate()' on a null object reference
	at com.marianhello.bgloc.LocationService.onTaskRemoved(LocationService.java:200)
	at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3109)
	at android.app.ActivityThread.access$2100(ActivityThread.java:176)
	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1550)
	at android.os.Handler.dispatchMessage(Handler.java:111)
	at android.os.Looper.loop(Looper.java:192)
	at android.app.ActivityThread.main(ActivityThread.java:5619)
	at java.lang.reflect.Method.invoke(Native Method)
	at java.lang.reflect.Method.invoke(Method.java:372)
	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:976)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)

notification icons not working

Your Environment

  • Plugin version: 0.2.0-alpha.5
  • Platform: Android
  • OS version: Android 7.0
  • Device manufacturer and model: Emulator
  • React Native version: 0.37.0
  • Plugin configuration options: {
    desiredAccuracy: 10,
    stationaryRadius: 50,
    distanceFilter: 10,
    locationTimeout: 10,
    notificationIconLarge: '../../images/ic_directions_walk_black_48dp.png',
    notificationTitle: 'Recording track...',
    notificationText: 'Tap to show more details',
    startOnBoot: false,
    stopOnTerminate: false,
    locationProvider: BackgroundGeolocation.provider.ANDROID_ACTIVITY_PROVIDER,
    interval: 5000,
    fastestInterval: 5000,
    activitiesInterval: 10000,
    stopOnStillActivity: false
    }

Context

I've tried to set an image based on the current component (../../) and also android folders but doesn't work. How should the image url be formatted?
No icon was shown; I've tried both the icon large and small.

Possible Fix

Would be nice to be able to set images easily. And one off-topic; would be possible to disable completely the notification or that would not work then in background?

Location update event not fired

I have just set up on my Android Emulator (Genymotion) and tried changing GPS location from command line tool as well from provided Genymotion GUI but the location doesn't seem to be updated. Did i missed config something?

BackgroundGeolocation.configure({
  desiredAccuracy: 0,
  stationaryRadius: 30,
  debug: true,
  distanceFilter: 30,
  startOnBoot: true,
  interval: 1000,
  notificationTitle: "Location Service",
  syncThreshold: 1,
  maxLocations: 1,
  locationProvider: 1,
  fastestInterval: 1000,
  activitiesInterval: 1000,
  stopOnStillActivity: true
});

BackgroundGeolocation.on('location', (location) => {
  console.log("Callback -> Lat: " + location.latitude + ", Long: " + location.longtitude)
  Actions.sendLocation(location);
});

BackgroundGeolocation.on('error', (error) => {
  console.log('[ERROR] BackgroundGeolocation error:', error);
});

BackgroundGeolocation.start(() => {
  console.log('[DEBUG] BackgroundGeolocation started successfully');
});

I have checked device log, only the start message came up

undefined is not an object (evaluating 'RNBackgroundGeolocation.configure')

  • Plugin version: 0.2.0-alpha.5"
  • Platform: iOS
  • OS version: 10.0 (14A345)
  • Device manufacturer and model: Simulator iPhone 6
  • React Native version: 0.34.0

Here's the code snippet:

BackgroundGeolocation.configure({
  desiredAccuracy: 10,
  stationaryRadius: 1,
  distanceFilter: 1,
  interval: 5000,
  fastestInterval: 5000,
  saveBatteryOnBackground: false,
  activityType: 'Fitness',
  url: apiUrl,
  stopOnStillActivity: false,
})
BackgroundGeolocation.start()

Expected Behavior

Getting the location to work

Actual Behavior

Nothing worked, log message shows undefined is not an object (evaluating 'RNBackgroundGeolocation.configure')

Steps to Reproduce

  1. Install the library
  2. Run the code snippet

Location Paused Message

The app seems to be tracking fine for a while. After some inactivity I get a "Location Updated Paused" Notification, and then no more updates.
By the looks of it. My CLLocationManager is pausing after 10-20 minutes of inactivity as described in:
http://stackoverflow.com/questions/17484352/iphone-gps-in-background-never-resumes-after-pause.

My questions:

  • Am I on the right track?
  • Is there a way to prevent the pause from ever coming on? I can handle inactivity on my own.

** I know this is an apple core issue more that yours. Just wondering if you guys found a way around it.

  • Plugin version: v0.1.1
  • Platform: iOS
  • OS version: 9
  • Device manufacturer and model: Iphone 5 SE
  • React Native version: 0.42
  • Plugin configuration options:
    BackgroundGeolocation.configure({
    desiredAccuracy: 1,
    stationaryRadius: 1,
    distanceFilter: 1,
    debug: true,
    stopOnTerminate: false,
    interval: 1000,
    httpHeaders: {
    'X-FOO': 'bar'
    }
    }, function () {});
  • Link to your project: I'm not allowed..

IOS Significant change or Region monitoring only

Hi, this not an issue or bug. But i would like to know is there a way to have just significant change or region monitoring only. So in ios info.plist the background mode location key would not be necessary.

Android, Build failed

Trying to get this up and running, but seems to fail when running "react-native run-android". Totally new at react-native so would very much appreciate some guidance to get this running!

:react-native-mauron85-background-geolocation:processReleaseResources FAILED

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':react-native-mauron85-background-geolocation:processReleaseResources'.

    com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'D:\Android\android-sdk\build-tools\23.0.1\aapt.exe'' finished with non-zero exit value 1

Location set by GPS notification on Android

Your Environment

  • Plugin version: 0.2.0-alpha.6
  • Platform: Android API 25
  • OS version: Ubuntu 16.04
  • Device manufacturer and model: Xiaomi Redmi Note 3 Pro
  • React Native version: 0.41.2

configure object:

startForeground: false,
desiredAccuracy: 10,
stationaryRadius: 20,
distanceFilter: 50,
locationTimeout: 30,
startOnBoot: false,
stopOnTerminate: true,
locationProvider: BackgroundGeolocation.provider.ANDROID_ACTIVITY_PROVIDER,
interval: 10000,
fastestInterval: 5000,
activitiesInterval: 10000,
stopOnStillActivity: false

Context

When GPS is available I've got notification "Location set by GPS" every several seconds (maybe it's interval configure option) and notification badge on app icon. Everytime this notification wakes up device. Only real device is affected, not simulator.

API link called only once.

Your Environment

  • Plugin version: 0.2.0-alpha.5
  • Platform: iOS and Android
  • OS version:
  • Device manufacturer and model:
  • React Native version: 0.40
  • Plugin configuration options:
  • Link to your project:

Context

I was trying to use it for testing and I just follow basic example in the documentation it shows the geolocation started in the debug log and also send the info to api (I add a url) but only once after that it never call the Api or never show anything in debug am I missing something ?

Expected Behavior

Calling the API link after x milliseconds based on interval

Actual Behavior

only call the API link once on start.

continues track location changes when the app get closed

hi
my app logs location whether app is on forground or background.
when app is on forground or goes background with android "Home" key (not back key) , everything works as expected.
but when the app closed with back key , callback for changing in location not gets fired anymore .

my code is :
BackgroundGeolocation.on('location',location=>console.log(location))

Your Environment

  • Plugin version:0.2.0-alpha.5
  • Platform: Android
  • OS version: 5
  • Device manufacturer and model: genymotion
  • React Native version:0.39.2
  • Plugin configuration options:
    { desiredAccuracy: 100, stationaryRadius: 50, distanceFilter: 10, debug: false, locationProvider: BackgroundGeolocation.provider.ANDROID_DISTANCE_FILTER_PROVIDER, interval: 1000, fastestInterval: 100, stopOnStillActivity: false, stopOnTerminate: false, startForeground:false, maxLocations: 100, }

Expected Behavior

expected location change callback fired even when the app is goes background with 'Back' key

Change settings when plugin already started?

Is it possible to change some settings when the plugin is already running, for example to request a higher/lower accuracy depending on what the user is doing in the app? Or do I need to stop the plugin, re-configure it with the new settings and restart it?
Also, is it possible to force a request of the current location? I do not see any function for this...

[Android] GPS crash and shutdown after first location update received

After first location update received, GPS shut down and stop working

  • Plugin version: 0.2.0-alpha.1
  • Platform: Android
  • OS version: 5.0.2
  • Device manufacturer and model: LG G2
  • React Native version: 0.32
  • Plugin configuration options:

BackgroundGeolocation.configure({
desiredAccuracy: 10,
stationaryRadius: 50,
distanceFilter: 10,
debug: false,
stopOnTerminate: false,
interval: 10000,
startOnBoot: false,
stopOnStillActivity: false
})

Expected Behavior

GPS still active receiving updates

Actual Behavior

GPS stop working after first update

Steps to Reproduce

  1. Configure plugin in componentWillMount
  2. Start

Service not registered

I am unable to replicate this issue but i am receiving this error on the production version of this app for some of my users.

Fatal Exception: java.lang.IllegalArgumentException: Service not registered: com.marianhello.react.BackgroundGeolocationModule$1@24a2165 at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:1048) at android.app.ContextImpl.unbindService(ContextImpl.java:1323) at android.content.ContextWrapper.unbindService(ContextWrapper.java:616) at com.marianhello.react.BackgroundGeolocationModule.doUnbindService(BackgroundGeolocationModule.java:502) at com.marianhello.react.BackgroundGeolocationModule.stop(BackgroundGeolocationModule.java:286) at java.lang.reflect.Method.invoke(Method.java) at com.facebook.react.bridge.BaseJavaModule$JavaMethod.invoke(BaseJavaModule.java:319) at com.facebook.react.cxxbridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:158) at com.facebook.react.bridge.queue.NativeRunnable.run(NativeRunnable.java) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:31) at android.os.Looper.loop(Looper.java:234) at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:196) at java.lang.Thread.run(Thread.java:818)

Get location data after app is cleared from task manager.

I have integrated this in my app. I want to perform task in background when location meets specific latitude and longitude.
BackgroundGeolocation.on('location', (location) => { ToastAndroid.show("Location: latitude: " + location.latitude + " longitude: " + location.longitude, ToastAndroid.SHORT); });

I have tried to toast message here. But it is not working when my app is killed from task manager.

Guide me that how can I make it run in background.

Not working on Android 6.0

The same code works on Android 5.0.

When started on 6.0 it says that location updates have started, but no the on('location') and on('stationary' handlers are not called. In debug mode, no beeps or any toast messages. No error messages in logcat.

My sample config is:

BackgroundGeolocation.configure({
    desiredAccuracy: 0,
    stationaryRadius: 10,
    distanceFilter: 30,
    locationTimeout: 30,
    notificationTitle: '',
    notificationText: '',
    debug: true,
    startOnBoot: false,
    stopOnTerminate: false,
    locationProvider: BackgroundGeolocation.provider.ANDROID_ACTIVITY_PROVIDER,
    interval: 10000,
    fastestInterval: 5000,
    activitiesInterval: 15000,
    stopOnStillActivity: false,
  });

location.time showing unexpected time

Your Environment

  • Plugin version: 0.2.0-alpha.6
  • Platform: Android
  • OS version: 6.0
  • Device manufacturer and model: Simulator
  • React Native version: 0.40
  • Plugin configuration options:
  • Link to your project:

Context

new Date().toUTCString() is different from the time reported by the http posting or location callback (my phone is on GMT-3)

Expected Behavior

BackgroundGeolocation.on('location', (location) => { console.log(location.time); });
that log should return the current time (UTC) on the phone, which was supposed to be 1489108911353 or Thu, 09 Mar 2017 22:21:51 GMT (Thu Mar 09 2017 19:21:51 GMT-0300 (BRT))

Actual Behavior

It is returning 1489123434000 (2017-03-10 05:23:54)
As you can see, the return value is several hours ahead from the correct UTC time.

Possible Fix

I don't know

Steps to Reproduce

  1. console.log(location.time)

IOS Build Issue, duplicate RCTBridge

Your Environment

  • Plugin version: 0.2.0-alpha.6
  • Platform: iOS
  • OS version: Mac OS X El Capitan
  • React Native version: 0.41.2

Context

Having issue build with IOS, in Xcode 8.

Expected Behavior

Actual Behavior

Possible Fix

Seem to fix with removal of import RCTBridge.h in RCTBackgroundGeolocation.m

#if __has_include("RCTBridge.h") <!--- remove this
#import "RCTBridge.h" <!--- remove this
#else <!--- remove this
#import <React/RCTBridge.h>
#endif <!--- remove this

Steps to Reproduce

Context

Debug logs

Rare onLocationChanged events on iOS

Running the module 0.2.0-alpha.5 with RN 0.33 on the iPhone6 simulator (iOS 10) I have very rare onLocationChanged events. I would like to get them every 5 meters. Or, ideally, every 1 second, but this is not available under iOS, as I got from the readme. The configure options are:

desiredAccuracy: 0,
stationaryRadius: 0,
distanceFilter: 5,

For the testing purposes I use "City bicycle ride" gps mode.

In average I have the event push on every 40 meters. I also see the following lines in the logs rather often (several times more often than I have the event fired):

<Warning>: LocationManager updated distanceFilter, new: 30.000000, old: 105.000000
...
<Error>: LocationManager#flushQueue has to kill an out-standing background-task!
<Warning>: LocationManager#sync Location: id=-5764607523034207997 time=105553124672096 lat=37.33193356 lon=-122.03785871 accu=5 aaccu=-1 speed=7.6 head=93.40000000000001 alt=0 type=current
...
<Warning>: LocationManager updated distanceFilter, new: 25.000000, old: 100.000000
<Error>: LocationManager#flushQueue has to kill an out-standing background-task!

Is this something wrong with the configuration?

Error

  • What went wrong:
    A problem occurred configuring project ':app'.

    Cannot evaluate module react-native-mauron85-background-geolocation : Configuration with name 'default' not found.

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.