All Projects → transistorsoft → React Native Background Geolocation

transistorsoft / React Native Background Geolocation

Licence: mit
Sophisticated, battery-conscious background-geolocation with motion-detection

Programming Languages

objective c
16641 projects - #2 most used programming language
javascript
184084 projects - #8 most used programming language
java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to React Native Background Geolocation

cordova-plugin-radar
Cordova plugin for Radar, the leading geofencing and location tracking platform
Stars: ✭ 14 (-99.34%)
Mutual labels:  background-geolocation, location-tracking
radar-sdk-android
Android SDK for Radar, the leading geofencing and location tracking platform
Stars: ✭ 57 (-97.3%)
Mutual labels:  background-geolocation, location-tracking
Multiple.js
Sharing background across multiple elements using CSS
Stars: ✭ 879 (-58.34%)
Mutual labels:  background
React Native Background Actions
React Native background service library for running background tasks forever in Android & iOS.
Stars: ✭ 132 (-93.74%)
Mutual labels:  background
Gradient Screens
🌈 Gradients applied to buttons, texts and backgrounds in Flutter
Stars: ✭ 97 (-95.4%)
Mutual labels:  background
Vanta
Animated 3D backgrounds for your website
Stars: ✭ 1,162 (-44.93%)
Mutual labels:  background
React Background Slideshow
Sexy tiled background slideshow for React 🔥
Stars: ✭ 98 (-95.36%)
Mutual labels:  background
Eager Image Loader
The eager-loading for image files on the web page that loads the files according to your plan. This differs from the lazy-loading, for example, this can be used to avoid that the user waits for the loading.
Stars: ✭ 22 (-98.96%)
Mutual labels:  background
Berkanansdk
Bluetooth mesh messaging SDK for apps
Stars: ✭ 150 (-92.89%)
Mutual labels:  background
Cordova Plugin Background Mode
Keep app running in background
Stars: ✭ 1,306 (-38.1%)
Mutual labels:  background
Vidage
Your solution to full-screen background video & image combined.
Stars: ✭ 1,579 (-25.17%)
Mutual labels:  background
Httptransfertasks
Cross Platform HTTP Transfers for downloading and uploading (supports background operations)
Stars: ✭ 87 (-95.88%)
Mutual labels:  background
Himawari Bg
🌏 Set the latest image from Himawari 8 as your desktop background.
Stars: ✭ 81 (-96.16%)
Mutual labels:  background
Zsnavigationbar
ZSNavigationBar uses category to allow you change UINavigationBar appearance dynamically.(supported iOS 11+ and iPhone X)
Stars: ✭ 109 (-94.83%)
Mutual labels:  background
Geolocator
Location tracking & geofencing the easy way. Supports background, killed app, rebooted device different update intervals.
Stars: ✭ 60 (-97.16%)
Mutual labels:  background
Hydrapaper
A Gtk utility to set two different backgrounds for each monitor on GNOME (which lacks this feature)
Stars: ✭ 134 (-93.65%)
Mutual labels:  background
Fennel
A task queue library for Python and Redis
Stars: ✭ 24 (-98.86%)
Mutual labels:  background
Lowpoly
Lowpoly image generator
Stars: ✭ 83 (-96.07%)
Mutual labels:  background
Xselectorutil
一个可以用代码处理控件的阴影效果,及用代码在TextView、EditText、Button等控件设置selector背景(触摸反馈,样式变化、文字颜色变化、hint文字颜色变化等效果)的组件
Stars: ✭ 98 (-95.36%)
Mutual labels:  background
Fancybackground
FancyBackground is a tiny Android library designed to animate a set of resource Drawables.
Stars: ✭ 153 (-92.75%)
Mutual labels:  background

Background Geolocation for React Native · npm npm


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 Flutter, Cordova, NativeScript and pure native apps.


The Android module 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.


Google Play

Home Settings

Contents

🔷 Installing the Plugin


⚠️ If you have a previous version of react-native-background-geolocation < 3.2.0 installed into react-native >= 0.60, you should first unlink your previous version as react-native link is no longer required.

$ react-native unlink react-native-background-geolocation

With yarn

yarn add react-native-background-geolocation

With npm

$ npm install react-native-background-geolocation --save

🔷 Setup Guides

react-native >= 0.60

iOS

Android

🔷 Configure your license

  1. Login to Customer Dashboard to generate an application key: www.transistorsoft.com/shop/customers

  2. Add your license-key to android/app/src/main/AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.transistorsoft.backgroundgeolocation.react">

  <application
    android:name=".MainApplication"
    android:allowBackup="true"
    android:label="@string/app_name"
    android:icon="@mipmap/ic_launcher"
    android:theme="@style/AppTheme">

    <!-- react-native-background-geolocation licence -->
+     <meta-data android:name="com.transistorsoft.locationmanager.license" android:value="YOUR_LICENCE_KEY_HERE" />
    .
    .
    .
  </application>
</manifest>

🔷 Using the plugin

import BackgroundGeolocation from "react-native-background-geolocation";

Typescript API:

For those using Typescript (recommended), you can also import the interfaces:

import BackgroundGeolocation, {
  State,
  Config,
  Location,
  LocationError,
  Geofence,
  GeofenceEvent,
  GeofencesChangeEvent,
  HeartbeatEvent,
  HttpEvent,
  MotionActivityEvent,
  MotionChangeEvent,
  ProviderChangeEvent,
  ConnectivityChangeEvent
} from "react-native-background-geolocation";

For more information, see this blog post

🔷 Example

There are three main steps to using BackgroundGeolocation

  1. Wire up event-listeners.
  2. .ready(config) the plugin.
  3. .start() the plugin.

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

// NO!  .ready() has not resolved.
BackgroundGeolocation.getCurrentPosition(options);
BackgroundGeolocation.start();

BackgroundGeolocation.ready(config).then((state) => {
  // YES -- .ready() has now resolved.
  BackgroundGeolocation.getCurrentPosition(options);
  BackgroundGeolocation.start();  
});

// NO!  .ready() has not resolved.
BackgroundGeolocation.getCurrentPosition(options);
BackgroundGeolocation.start();

Example 1. — React Functional Component

Show Source
import React from 'react';
import {
  Switch,
  Text,
  View,
} from 'react-native';

import BackgroundGeolocation, {
  Location,
  Subscription
} from "react-native-background-geolocation";

const HelloWorld = () => {
  const [enabled, setEnabled] = React.useState(false);
  const [location, setLocation] = React.useState('');

  React.useEffect(() => {
    /// 1.  Subscribe to events.
    const onLocation:Subscription = BackgroundGeolocation.onLocation((location) => {
      console.log('[onLocation]', location);
      setLocation(JSON.stringify(location, null, 2));
    })

    const onMotionChange:Subscription = BackgroundGeolocation.onMotionChange((event) => {
      console.log('[onMotionChange]', event);
    });

    const onActivityChange:Subscription = BackgroundGeolocation.onActivityChange((event) => {
      console.log('[onMotionChange]', event);
    })

    const onProviderChange:Subscription = BackgroundGeolocation.onProviderChange((event) => {
      console.log('[onProviderChange]', event);
    })

    /// 2. ready the plugin.
    BackgroundGeolocation.ready({
      // Geolocation Config
      desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
      distanceFilter: 10,
      // Activity Recognition
      stopTimeout: 5,
      // Application config
      debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
      logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
      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://yourserver.com/locations',
      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.
      headers: {              // <-- Optional HTTP headers
        "X-FOO": "bar"
      },
      params: {               // <-- Optional HTTP params
        "auth_token": "maybe_your_server_authenticates_via_token_YES?"
      }
    }).then((state) => {
      setEnabled(state.enabled)
      console.log("- BackgroundGeolocation is configured and ready: ", state.enabled);
    });

    return () => {
      // Remove BackgroundGeolocation event-subscribers when the View is removed or refreshed
      // during development live-reload.  Without this, event-listeners will accumulate with
      // each refresh during live-reload.
      onLocation.remove();
      onMotionChange.remove();
      onActivityChange.remove();
      onProviderChange.remove();
    }
  }, []);

  /// 3. start / stop BackgroundGeolocation
  React.useEffect(() => {
    if (enabled) {
      BackgroundGeolocation.start();
    } else {
      BackgroundGeolocation.stop();
      setLocation('');
    }
  }, [enabled]);

  return (
    <View style={{alignItems:'center'}}>
      <Text>Click to enable BackgroundGeolocation</Text>
      <Switch value={enabled} onValueChange={setEnabled} />
      <Text style={{fontFamily:'monospace', fontSize:12}}>{location}</Text>
    </View>
  )
}

export default HelloWorld;

Example 2. — React Class Component

Show Source
import React from 'react';
import {
  Switch,
  Text,
  View,
} from 'react-native';

import BackgroundGeolocation, {
  Location,
  Subscription
} from "react-native-background-geolocation";

export default class HelloWorld extends React.Component {
  subscriptions:Subscription[] = [];
  state:any = {};
  constructor(props:any) {
    super(props);
    this.state = {
      enabled: false,
      location: ''
    }
  }

  componentDidMount() {
    /// 1.  Subscribe to BackgroundGeolocation events.
    this.subscriptions.push(BackgroundGeolocation.onLocation((location) => {
      console.log('[onLocation]', location);
      this.setState({location: JSON.stringify(location, null, 2)})
    }, (error) => {
      console.log('[onLocation] ERROR:', error);
    }))

    this.subscriptions.push(BackgroundGeolocation.onMotionChange((event) => {
      console.log('[onMotionChange]', event);
    }))

    this.subscriptions.push(BackgroundGeolocation.onActivityChange((event) => {
      console.log('[onActivityChange]', event);
    }))

    this.subscriptions.push(BackgroundGeolocation.onProviderChange((event) => {
      console.log('[onProviderChange]', event);
    }))

    /// 2. ready the plugin.
    BackgroundGeolocation.ready({
      // Geolocation Config
      desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
      distanceFilter: 10,
      // Activity Recognition
      stopTimeout: 5,
      // Application config
      debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
      logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
      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://yourserver.com/locations',
      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.
      headers: {              // <-- Optional HTTP headers
        "X-FOO": "bar"
      },
      params: {               // <-- Optional HTTP params
        "auth_token": "maybe_your_server_authenticates_via_token_YES?"
      }
    }).then((state) => {
      this.setState({enabled: state.enabled});
      console.log("- BackgroundGeolocation is configured and ready: ", state.enabled);
    })
  }

  /// When view is destroyed (or refreshed during development live-reload),
  /// remove BackgroundGeolocation event subscriptions.
  componentWillUnmount() {
    this.subscriptions.forEach((subscription) => subscription.remove());
  }

  onToggleEnabled(value:boolean) {
    console.log('[onToggleEnabled]', value);
    this.setState({enabled: value})
    if (value) {
      BackgroundGeolocation.start();
    } else {
      this.setState({location: ''});
      BackgroundGeolocation.stop();
    }
  }

  render() {
    return (
      <View style={{alignItems:'center'}}>
        <Text>Click to enable BackgroundGeolocation</Text>
        <Switch value={this.state.enabled} onValueChange={this.onToggleEnabled.bind(this)} />
        <Text style={{fontFamily:'monospace', fontSize:12}}>{this.state.location}</Text>
      </View>
    )
  }
}

Promise API

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

BackgroundGeolocation.ready({
  desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH, 
  distanceFilter: 50
}).then(state => {
  console.log('- BackgroundGeolocation is ready: ', state);
}).catch(error => {
  console.warn('- BackgroundGeolocation error: ', error);
});

// Or use await in an async function
try {
  const state = await BackgroundGeolocation.ready({
    desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH, 
    distanceFilter: 50
  })
  console.log('- BackgroundGeolocation is ready: ', state);
} catch (error) {
  console.warn('- BackgroundGeolocation error: ', error);
}

🔷 Demo Application

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

Home Settings

🔷 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.

License

The MIT License (MIT)

Copyright (c) 2018 Chris Scott, Transistor Software

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].