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

Reloading UITableView while Animating Scroll in iOS 11

Reloading UITableView while Animating Scroll Calling  reloadData  on  UITableView  may not be the most efficient way to update your cells, but sometimes it’s easier to ensure the data you are storing is in sync with what your  UITableView  is showing. In iOS 10  reloadData  could be called at any time and it would not affect the scrolling UI of  UITableView . However, in iOS 11 calling  reloadData  while your  UITableView  is animating scrolling causes the  UITableView  to stop its scroll animation and not complete. We noticed this is only true for scroll animations triggered via one of the  UITableView  methods (such as  scrollToRow(at:at:animated:) ) and not for scroll animations caused by user interaction. This can be an issue when server responses trigger a  reloadData  call since they can happen at any moment, possibly when scroll animation is occurring. Example of s...

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

Xcode & Instruments: Measuring Launch time, CPU Usage, Memory Leaks, Energy Impact and Frame Rate

When you’re developing applications for modern mobile devices, it’s vital that you consider the performance footprint that it has on older devices and in less than ideal network conditions. Fortunately Apple provides several powerful tools that enable Engineers to measure, investigate and understand the different performance characteristics of an application running on an iOS device. Recently I spent some time with these tools working to better understand the performance characteristics of an eCommerce application and finding ways that we can optimise the experience for our users. We realised that applications that are increasingly performance intensive, consume excessive amounts of memory, drain battery life and feel uncomfortably slow are less likely to retain users. With the release of iOS 12.0 it’s easier than ever for users to find applications that are consuming the most of their device’s finite amount of resources. Users can now make informed decisions abou...