Trying to use expo-location to update location in background but it doesn't work

Viewed 433

I'm trying to update my app location in the background and see it in the console log when I change the android emulator location, but it doesn't work. When I start the app, it shows the following error:

[Unhandled promise rejection: Error: Attempt to invoke interface method 'java.util.Map o.e.c.a.d.getOptions()' on a null object reference]
at node_modules/react-native/Libraries/BatchedBridge/NativeModules.js:103:50 in promiseMethodWrapper
at node_modules/@unimodules/react-native-adapter/build/NativeModulesProxy.native.js:15:23 in moduleName.methodInfo.name
at node_modules/expo-location/build/Location.js:164:10 in startLocationUpdatesAsync
at node_modules/expo-location/build/Location.js:162:7 in startLocationUpdatesAsync
at src/app/services/LocationService.ts:57:10 in startBackgroundServiceAsync
at src/app/services/LocationService.ts:56:2 in startBackgroundServiceAsync
at src/app/hooks/useLocation.ts:16:12 in <anonymous>

I'm using expo v42.0.1, expo-location v12.1.2 and expo-task-manager v9.2.2. I have also added "permissions": ["ACCESS_BACKGROUND_LOCATION"] to the app.json.

App component file (main)

...imports

export default function App() {
  useEffect(() => {
    const locationService = new LocationService();
    (async () => {
      await locationService.requestForegroundPermissionsAsync();
      await locationService.requestBackgroundPermissionsAsync();
      await locationService.startBackgroundServiceAsync();
    })();
  }, []);

  return <View/>
}

Location Service file

...imports

const backgroundLocationTask = 'background-location-task';

defineTask(backgroundLocationTask, async ({ data, error }: any) => {
  console.log('Background Location');
  if (error) return console.error(error);
  const { locations } = data;
  const latitude = locations[0].coords.latitude;
  const longitude = locations[0].coords.longitude;
  console.log(latitude, longitude);
});

export class LocationService {
  async requestForegroundPermissionsAsync() {
    const { status } = await requestForegroundPermissionsAsync();
    if (status !== 'granted')
      throw new Error('ForegroundLocationPermissionNotGranted');
  }

  async requestBackgroundPermissionsAsync() {
    const { status } = await requestBackgroundPermissionsAsync();
    if (status !== 'granted')
      throw new Error('BackgroundLocationPermissionNotGranted');
  }

  async startBackgroundServiceAsync() {
    await startLocationUpdatesAsync(backgroundLocationTask, {
      accuracy: LocationAccuracy.High
    });
  }
}

0 Answers
Related