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

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

16 AWS Gotchas

16 AWS Gotchas In January I launched the MVP for my own startup,  Proximistyle , which helps you find what you’re looking for nearby. On advice from friends and industry contacts I chose AWS as my cloud provider. Having never had to set up my own cloud infrastructure before, the learning curve to get from no experience to a stable VPC system I was happy with was significantly steeper than expected, and had its fair share of surprises. #1 Take advantage of the free resources offered AWS offers a free tier for new accounts. If you have recently bought a domain and set up a company you qualify for the free tier for a year. Additionally, if you are a bootstrapped startup you can apply for  the Startup Builders package  and get $1000 in AWS credits. After doing the above, you’re now ready to get started with setting up the AWS infrastructure for your startup. #2 Set up billing budgets and alerting The very first thing you should do after setting up billing, is enabling a budge...

Ultimate Folder Structure For Your React Native Project

  Ultimate Folder Structure For Your React Native Project React native project structure React Native is a flexible framework, giving developers the freedom to choose their code structure. However, this can be a double-edged sword for beginners. Though it offers ease of coding, it can soon become challenging to manage as your project expands. Thus, a structured folder system can be beneficial in many ways like better organization, simplified module management, adhering to coding practices, and giving a professional touch to your project. This write-up discusses a version of a folder arrangement that I employ in my React Native projects. This structure is based on best practices and can be modified to suit the specific needs of your project. Before we get into the project structure let’s give credit to @sanjay who has the original idea of the structure but I modify his version of the code, to make it better. Base library axios  — For network calling. react-navigation ...