[Unhandled promise rejection: Error: Not authorized to use background location services.]

  1. SDK Version: 40
  2. Platforms(Android/iOS/web/all): expo cli on Android

I’m using expo-cli in the managed flow. I’m trying to get background location but when the app reaches await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
accuracy: Location.Accuracy.BalancedHighest,
timeInterval: 10000,
foregroundService: {
notificationTitle: “BackgroundLocation Is On”,
notificationBody: ‘To turn off, go back to the app and switch something off.’,
}});
it appears the following error:
Unhandled promise rejection: Error: Not authorized to use background location services.]

node_modules/react-native/Libraries/BatchedBridge/NativeModules.js:103:50 in promiseMethodWrapper
node_modules/@unimodules/react-native-adapter/build/NativeModulesProxy.native.js:15:23 in moduleName.methodInfo.name
node_modules/expo-location/build/Location.js: in startLocationUpdatesAsync
node_modules/regenerator-runtime/runtime.js:63:36 in tryCatch
node_modules/regenerator-runtime/runtime.js:293:29 in invoke
node_modules/regenerator-runtime/runtime.js:63:36 in tryCatch
node_modules/regenerator-runtime/runtime.js:154:27 in invoke

And here is my code:

import React from 'react';
import {connect} from 'react-redux';
import {View, TouchableHighlight, Text, StyleSheet} from 'react-native';
import { activateSearch, actualLocation, arriveToken, logging, localFound, arriveShop, arriveShops } from '../redux/actions';
import { Alert, Platform } from 'react-native'
import * as Permissions from 'expo-permissions';
import * as Linking from 'expo-linking';
import * as Location from 'expo-location';
import * as TaskManager from 'expo-task-manager';
import axios from 'axios';

import {baseURL} from '../consts/url';

const LOCATION_TASK_NAME = 'background-location-tasks'

const hasGeolocationPermission = async () => {
  try {
    const { status } = await Location.requestPermissionsAsync();
    let finalStatus = status
    if (finalStatus === 'granted') return true;
    if (finalStatus !== 'granted') {
      Alert.alert(
        'Warning',
        'You will not search if you do not enable geolocation in this app. If you would like to search, please enable geolocation for Fin in your settings.',
        [
          { text: 'Cancel'},
          // we can automatically open our app in their settings
          // so there's less friction in turning geolocation on
          { text: 'Enable Geolocation', onPress: () => Platform.OS === 'ios' ? Linking.openURL('app-settings:') : Linking.openSettings() }
        ]
      )
      return false;
      
    }
  } catch (error) {
    Alert.alert(
      'Error',
      'Something went wrong while check your geolocation permissions, please try again later.'
    );
    return false;
  }
}

const checkIfLocationEnabled = async () => {
  let enabled = await Location.hasServicesEnabledAsync();
  if (!enabled){
    alert('Location service not enabled, please enable it to continue')
  }
  else {
    return enabled;
  }
}

class IndexScreen extends React.Component {

  async componentDidMount() {
    hasGeolocationPermission()
    
    this.myInterval = setInterval(async () => {
      if (this.props.activated){
        let Geopermission = await hasGeolocationPermission();
        let EnableLocation = await checkIfLocationEnabled();
        if (Geopermission && EnableLocation){
          this.getPosition();
        } //Si cambia algo de los permisos, se deja de enviar.
        else {return}
      }
    }, 5000)
    this.myInterval2 = setInterval(async () => {
      if (this.props.activated){
        let Geopermission = await hasGeolocationPermission();
        let EnableLocation = await checkIfLocationEnabled();
        if (Geopermission && EnableLocation){
          this.sendLocation();
        } //Si cambia algo de los permisos, se deja de enviar.
        else {return}
      }
    }, 35000)
  }

  async componentWillUnmount(){
    clearInterval(this.myInterval)
    clearInterval(this.myInterval2)
  }


  activate = async () => {
    let Geopermission = await hasGeolocationPermission();
    let EnableLocation = await checkIfLocationEnabled();
    if (Geopermission && EnableLocation){
      if (!this.props.activated){
        this.props.dispatch(activateSearch());
        this.getPosition();
        const { status } = await Location.requestPermissionsAsync();
        if (status === 'granted') {
          console.log("Entra aquí")
          await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
            accuracy: Location.Accuracy.BalancedHighest,
            timeInterval: 10000,
            foregroundService: {
              notificationTitle: "BackgroundLocation Is On",
              notificationBody: 'To turn off, go back to the app and switch something off.',
          }});
        }
    }
      else
        this.props.dispatch(activateSearch())
        if (this.props.locationdetected)
          this.props.dispatch(localFound());
    }
    else{
        return
    }
  }

  async getPosition() {
    try{
      const { coords } = await Location.getCurrentPositionAsync({});
      let position = coords;
      this.props.dispatch(actualLocation(position.latitude, position.longitude))
      console.log(this.props.latitud)
    } 
    catch (error) {
      console.log("getPosition -> error", error);
    }
  }
  
  render() {
    if (this.props.logged){
      return(
          <View style={styles.container}>
              <Text style={{alignSelf: 'flex-start', color:"#d9931c", fontSize: 25}}> Bienvenido, </Text> 
              <Text style={styles.usernametext}> {this.props.username}</Text> 
              <Text style={{alignSelf: 'flex-end', color:"#d9931c", fontSize: 25}}> a esta App </Text> 
            <View style={{marginTop:100}}>
              <Text style={{color:"#d9931c",fontSize: 25, textAlign: 'center'}}> Pulsa 'Empezar búsqueda' para encontrar tu tienda </Text>
            </View> 
              <TouchableHighlight style={styles.startBtn} onPress = {() => this.activate()}>
                  <Text style={styles.loginText}>{this.props.activated ? "Parar búsqueda" : "Empezar búsqueda"}</Text>
              </TouchableHighlight>
              <TouchableHighlight style={styles.logoutBtn} onPress = {() => this.logout()}>
                  <Text style={styles.loginText}>Logout</Text>
              </TouchableHighlight>
          </View>
      )
      }
      else{
        return(
          <View style={{ flex:1, flexDirection: 'column', alignItems:'center', justifyContent:'space-around'}}>
              <Text style={{flex:1, fontSize: 35 }}> You need to be logged </Text> 
          </View>
        )
      }
  }
}

TaskManager.defineTask(LOCATION_TASK_NAME, async ({ data: {locations}, error }) => {
  if (error) {
    // Error occurred - check `error.message` for more details.
    return;
  }
  const [location] = locations;
  console.log(location);
  try{
    await axios.post(baseURL+'/location', {location})
  }catch (err) {
    console.log(err)
  }
}); 


const styles = StyleSheet.create({
  container: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      backgroundColor: 'white',
  },
  text:{
      color:"#d9931c",
      fontSize: 25,
      alignSelf:'flex-start'
  },
  usernametext:{
    color:"#465881",
    fontSize: 30,
    fontWeight: "bold"
  },
  startBtn:{
      width:"80%",
      backgroundColor:"#465881",
      borderRadius:25,
      height:50,
      alignItems:"center",
      justifyContent:"center",
      marginTop:120,
      marginBottom:10,
    },
  logoutBtn:{
    width:"80%",
    backgroundColor:"darkgray",
    borderRadius:25,
    height:50,
    alignItems:"center",
    justifyContent:"center",
    marginTop:30,

  },
  loginText:{
      color:"white",
      fontSize:20
    }

}
);

function mapStateToProps(state) {
    return {
      ...state
    };
}
      
      //export default App;
export default connect(mapStateToProps)(IndexScreen);

(post withdrawn by author, will be automatically deleted in 24 hours unless flagged)