Skip to main content

React Native background location (background & terminated app)

 React Native background location (background & terminated app)

So… I've recently finished my bachelor thesis. The app had to fetch the user's location even when it is in the background or terminated. And here the issue began…

Basically, I couldn't find any valuable resources on the internet that would help me solve the issue (except an article from Sourab Kumar — https://itnext.io/react-native-background-location-tracking-without-timeout-and-with-app-killed-3dbfbc80ad01). He presented a solution for android. I'd like to sum it up a bit and add a solution for requesting permissions and tracking users on iOS. So let's begin!

1. Requesting permissions

In order to get the user's permission, we have to request it. Fortunately, OS creators did a pretty good job in designing the API for us. So let's start!

Personally, I don't think that it is a good practice to use packages build-in functions for requesting permissions (i.e. react-native-location's RNLocation.requestPermission). If you find yourself using 3–4 packages that use device API, you'd be banging your head against the wall why you didn't choose a unified approach in the beginning.

My suggestion is to use react-native-permissionThe way that you are able to request permission with this package is simple and unified! Of course, you still have to choose the permissions that you want to request.

For our purpose, we will have to distinguish between iOS and Android devices.

import { check, request, PERMISSIONS, RESULTS, Permission } from 'react-native-permissions'
import { Platform } from 'react-native'

let targetPermission = Platform.OS === 'ios' ? PERMISSIONS.IOS.LOCATION_ALWAYS : PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION
Now, let's request the permissions.
check(targetPermission)
  .then(result => {
    switch (result) {
      case RESULTS.DENIED:
        console.log('LOCATION: Denied, requesting permission!')
        request(targetPermission).then(
          res => {
            if (res === 'granted') {
              console.log('LOCATION: Permission granted!')

              if (Platform.OS === 'android' && Platform.Version > 28) {
                console.log('LOCATION: Android system detected -- requesting Background location')
                request(PERMISSIONS.ANDROID.ACCESS_BACKGROUND_LOCATION).then(bgRes => {
                  if (bgRes === 'granted') {
                    console.log("LOCATION: BG location granted!")
                    callback()
                  }
                }, bgErr => {
                  console.error(bgErr)
                })
              } else {
                callback()
              }
            }
          },
          err => {
            console.error(err)
          }
        )
        break

      case RESULTS.GRANTED:
        console.log('LOCATION: Permission granted!')
        callback()
        break

      case RESULTS.UNAVAILABLE:
        console.log('LOCATION: This feature is not available (on this device / in this context)');
        break;
        
      case RESULTS.LIMITED:
        console.log('LOCATION: The permission is limited: some actions are possible');
        break;
        
      case RESULTS.BLOCKED:
        console.log('LOCATION: The permission is denied and not requestable anymore');
        break;
          
      default:
        console.error('LOCATION: FAILED TO GET PERMISSION')
  }
}).catch(error => {
  console.error(error.message)
})
Notice, that in the example above, we've additionally checked whether we have Android API > 28. If we do, we have to check for another permission.

Perfect! Now that we have all the permissions, we can proceed to the implementation of the location sniffer! 🎉

For sniffing the location, we will use react-native-location.

2. Configure RNLocation

First of all, we have to configure our RNLocation. Actually… for iOS it is pretty simple. The only thing that you have to take care of is to check only for “significant changes”. For Android, we have multiple choices available. Please refer to docs for more of a comprehensive explanation. For our purpose, the configuration below will work 😎

import RNLocation from 'react-native-location';

RNLocation.configure({
  distanceFilter: 100, // Meters
  desiredAccuracy: {
    ios: 'best',
    android: 'balancedPowerAccuracy',
  },
  // Android only
  androidProvider: 'auto',
  interval: 5000, // Milliseconds
  fastestInterval: 10000, // Milliseconds
  maxWaitTime: 5000, // Milliseconds
  // iOS Only
  allowsBackgroundLocationUpdates: true,
  showsBackgroundLocationIndicator: true,
})

AppRegistry.registerComponent('app', () => App)

3. Sniffing for a location

3.1 Sniffing for a location with iOS

With our RNLocation configured, we can start sniffing! It is pretty simple. Somewhere in the app just make sure that you have permissions (otherwise it will fail) and that you call subscribeToSignificantLocationUpdates().

Now you can sniff for location changes on iOS! Go ahead and try it out!

3.2 Sniffing for a location with Android
export const startiOSBGWorker = () => {
  ensureLocationPermission(() => {
    RNLocation.subscribeToSignificantLocationUpdates(
      ([ locations ]) => {
        userUpdatePosition({
          id: auth().currentUser!.uid,
          latitude: locations.latitude,
          longitude: locations.longitude
        })
      }
    )
  })
}

Here it is a bit more complex. Unfortunately, you cannot sniff for a location without the user knowing that you do that… I think that Sourab explained that quite well in his article, so go ahead and check it out! https://itnext.io/react-native-background-location-tracking-without-timeout-and-with-app-killed-3dbfbc80ad01

By the way, my final code is a bit different from his, so I'll still share it with you 😌 I do use foreground service in exactly the same way that Sourab does, but I have changed how the service is refreshed (Android shuts down your app after some time if it doesn't meet some criteria — which unfortunately differs DEVICE PER DEVICE).

export const startAndroidBGWorker = () => {
  if (!ReactNativeForegroundService.is_running()){
    ReactNativeForegroundService.add_task(
      () => {
        ensureLocationPermission(() => {
          RNLocation.subscribeToLocationUpdates(
            ([ locations ]) => {
              userUpdatePosition({
                id: auth().currentUser!.uid,
                latitude: locations.latitude,
                longitude: locations.longitude
              })
            }
          )
        })
      }, {
        delay: 1000,
        onLoop: false,
        taskId: 'background_location_sniff',
        onError: (e: any) => console.log('Error logging:', e),
      },
    )

    ReactNativeForegroundService.start({
      id: 144,
      title: 'We use your location',
      message: 'Dont worry... everything is ok',
    })
  }
}

4. Conclusion

The above example did work in my bachelor thesis, so I'm 100% sure that you can accomplish the same results with a bit of tweak. Unfortunately, the environment in React Native community and especially the way that devs can interact with device APIs are changing quite fast. So you will most likely have to edit something. But generally, the idea should work.

If you have any further questions you can always contact me on Comments...

Thank You.

Comments

Popular Posts

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...

An introduction to Size Classes for Xcode 8

Introduction to Size Classes for Xcode In iOS 8, Apple introduced  size classes , a way to describe any device in any orientation. Size classes rely heavily on auto layout. Until iOS 8, you could escape auto layout. IN iOS8, Apple changed several UIKit classes to depend on size classes. Modal views, popovers, split views, and image assets directly use size classes to determine how to display an image. Identical code to present a popover on an iPad  causes a iPhone to present a modal view. Different Size Classes There are two sizes for size classes:  compact , and  regular . Sometime you’ll hear about any.  Any  is the generic size that works with anything. The default Xcode layout, is  width:any height:any . This layout is for all cases. The Horizontal and vertical dimensions are called  traits , and can be accessed in code from an instance of  UITraitCollection . The  compact  size descr...

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...