Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove background location access on Android

I am using react-native-geolocation-service to fetch the location of the user. On iOS it is easy to just ask for location access when the app is in the foreground, you just skip adding background location access as a capability. However, I don't understand how you remove this permission on Android. I don't have the ACCESS_BACKGROUND_LOCATION permission set and I'm still getting the option "Allow all the time" on e.g. my Pixel 2.

This is the code I am using to fetch the location of the user:

const getCurrentPosition = async (onSuccess, onError) => {
  if (Platform.OS === 'android') {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      {
        title: 'My title',
        message: 'My message',
        buttonPositive: 'Continue',
      }
    );
    if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
      onError();
      return;
    }
  }
  Geolocation.getCurrentPosition(
    (result) => {
      const position = {
        longitude: result.coords.longitude,
        latitude: result.coords.latitude,
      };
      onSuccess(position);
    },
    (error) => {
      onError();
    },
    { enableHighAccuracy: true, maximumAge: 10000, timeout: 15000 }
  );
};
like image 732
Daniel Tovesson Avatar asked Oct 26 '20 08:10

Daniel Tovesson


1 Answers

Look into your main AndroidManifest.xml file (and by main I mean under android/app/src/main(COULD_BE_SOMETHING_ELSE_USUALLY_MAIN_BUT_YMMV)/AndroidManifest.xml)

You need to find a bunch of <uses-permission />. Check if one of these bad boys got ACCESS_BACKGROUND_LOCATION:

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

No luck? Fear not, my dear friend. Here's a remedy for your battle-fatigued-from-dealings-with-react-native mind. Add this line under the last <uses-permission> tag.

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

May peace prevail.

Technical nitty gritty:

Actually, a library, like react-native-geolocation-service or react-native-background-geolocation, can alter final AndroidManifest.xml, which will go to a bundle edited heavily.

Simply deleting a line won't cut it, because you don't have an access to that final draft, cause it's auto-generated. You need to be one step ahead and use tools:node="remove" to make sure it will be deleted from the final version of the manifest file.

Sources:

  • [1] https://developer.android.com/studio/build/manifest-merge
  • [2] https://github.com/transistorsoft/react-native-background-geolocation/issues/1149
like image 178
Alex Pogiba Avatar answered Oct 13 '22 11:10

Alex Pogiba