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

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...

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 = { ...