react-native-location: Not working when App in Background (Android)

RNLocation not working in Android in the background but the same configuration method works well in iOS.

RNLocation.configure({
      distanceFilter: 0, // Meters
      desiredAccuracy: {
        ios: "best",
        android: "balancedPowerAccuracy"
      },
      // Android only
      androidProvider: "auto",
      interval: 500, // Milliseconds
      fastestInterval: 1000, // Milliseconds
      // maxWaitTime: 5000, // Milliseconds
      // iOS Only
      activityType: "other",
      allowsBackgroundLocationUpdates: true,
      headingFilter: 1, // Degrees
      headingOrientation: "portrait",
      pausesLocationUpdatesAutomatically: false,
      showsBackgroundLocationIndicator: true,
    })

  • Get Location using RNLocation.subscribeToLocationUpdates method.
RNLocation.requestPermission({
      ios: 'whenInUse', // or 'always'
      android: {
        detail: "fine"
      }
    }).then(granted => {
        if (granted) {
          this.unsubscribe = RNLocation.subscribeToLocationUpdates(locations => {
            console.log("locations : " + JSON.stringify(locations))
          })
        }
      })

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 3
  • Comments: 15

Most upvoted comments

According to the Background location access checklist there is a new permission added in “API level 29” called ACCESS_BACKGROUND_LOCATION which helped me out. You just need to add the following to your android/app/src/main/AndroidManifest.xml:

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

    ...
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    ...

</manifest>

thankyou @andersryanc but I am stuck at what changes are required in both native and react native side

Sorry for the delay on this @GurmeetSingh94 . Just today, I added a list of changes to the readme that outline the necessary changes you’d need to make to the Android native side. As for the react-native specific changes inside your project, you may just want to look over the couple of JS files I provided, as the sample app is very simple, I think it just has 1 or 2 buttons and some hooks I created to handle the location tracking. The only other part you might be interested in, in the app code, is the RNLocation.requestPermission() call in my LocationAccessButton component.

UPDATE: I added more notes to my readme about the react native app code I have in the sample project. You can see it here: Notes about the React Native app code

For anyone interested, I cloned my project and delete all the extra stuff that was specific to my app to create a demo project as I mentioned previously.

https://github.com/andersryanc/ReactNative-LocationSample

Sorry, yes, @yudiz-vipul you are correct, obviously the new background permission would only work for API 29+.

Sorry also because I’m very much new to Android development, so I’ve had to do a lot of research to figure things out. I read through that page pretty quickly the first time around and missed an important note about that particular permission. In the final section Limited updates to background location it mentions “[your app] can receive location updates only a few times each hour”. Which in my particular case, is not frequent enough as I’m developing a fitness / running tracking app and need high frequency and accuracy to track the user’s distance and avg pace and such.

@yudiz-vipul I did try your example at first, which is well done, but it had the same limitation, seeing as you are using a background service to do the location tracking. You also mention in your readme about the 1 minute minimum.

What ended up working out best for me was actually following the LocationUpdatesForegroundService example found in the Request Location Updates page of the Android developer docs. The sample hasn’t been updated for 3 years and took a bit of adjusting to get to work just right and obviously does not include react-native (I may try and release an updated version of it integrated with a fresh react-native app at some point) but I think the main thing that it came down to was that the sample needed one attribute added to the Foreground Service definition in the AndroidManifest.xml. As I continued to read through the docs on Location and Foreground services and such, I found this section on Types of location access which mentions the need to add a foregroundServiceType like so:

<!-- Recommended for Android 9 (API level 28) and lower. -->
<!-- Required for Android 10 (API level 29). -->
<service
    android:name="MyNavigationService"
    android:foregroundServiceType="location" ... >
    <!-- Any inner elements would go here. -->
</service>

In the end, what I basically ended up doing was to merge @yudiz-vipul’s example, which includes the react-native specific stuff and then swapped out the Services from that sample with just the Foreground service from the Android/Location-Samples repo. Again, I will try and put together a sample repo which includes all this if anyone else is interested.

What about Android “API Level 28 or below”?