Issue with Expo-Location using in background in android

Hi! In those days I’ve made an app, learning about expo and localizations, in the end, everything work well, until integrate taskmanager to take in background the latitude and longitude. When the app is open (android), in each moment, I get my lat and long, but when I lock the phone or even close de app (but still open in multitasking), the data is stopped. I know it because I send all my data to supabase. Here is my App Component.

const Stack = createNativeStackNavigator();
const LOCATION_TASK = "background-location-task";

/**
 * This function requests foreground and background location permissions and starts location updates if
 * granted.
 */
const requestPermissions = async () => {
  const { status: foregroundStatus } =
    await Location.requestForegroundPermissionsAsync();
  if (foregroundStatus === "granted") {
    const { status: backgroundStatus } =
      await Location.requestBackgroundPermissionsAsync();
    if (backgroundStatus === "granted") {
      await Location.startLocationUpdatesAsync(LOCATION_TASK, {
        accuracy: Location.Accuracy.Highest,
        distanceInterval: 1,
        timeInterval: 1500,
      });
    }
  }
};

export function Index() {
  const { supabase, onUpdate, onSignOut } = useSupabase();
  const [session, setSession] = useState<Session>({
    access_token: undefined,
  } as Session);
  const data = useSelector((state: any) => state.location);

  /**
   * This function updates the location of a user by retrieving their current position and updating their
   * latitude, longitude, and speed in a database.
   * @param {string} userId - The `userId` parameter is a string that represents the unique identifier of
   * a user. It is used to update the location data of a specific user in the database.
   * @returns The `onUpdateLocation` function is returning the result of calling the `onUpdate` function
   * with the arguments "usersdata", `userId`, and an object containing the latitude, longitude, and
   * speed properties of the current location. The `onUpdate` function is not shown in the code snippet,
   * so it is unclear what it returns.
   */
  const onUpdateLocation = async (userId: string) => {
    const speed = data?.speed != null ? data?.speed * (3600 / 1000) : 0;
    const info = await onUpdate("usersdata", userId, {
      lat: data?.latitude,
      long: data?.longitude,
      speed: speed,
    });
    return info;
  };

  const onLogOut = async () => {
    await onSignOut();
    Location.stopLocationUpdatesAsync(LOCATION_TASK);
  };

  useEffect(() => {
    requestPermissions();
    supabase.auth.onAuthStateChange((event: any, session: any) => {
      setSession(session);
    });
  }, []);
  useEffect(() => {
    if (session?.user != undefined) {
      onUpdateLocation(session?.user?.id);
    }
  }, [data]);

  return (
    <NativeBaseProvider>
      <NavigationContainer>
        <Stack.Navigator>
          {session?.access_token == undefined ? (
            <>
              <Stack.Screen
                name="Login"
                component={Login}
                options={{ title: "Iniciar sesión" }}
              />
            </>
          ) : (
            <>
              <Stack.Screen
                name="TrackList"
                component={TrackList}
                options={{
                  title: "Listado de ordenes",
                  headerBackVisible: false,
                  headerRight: () => (
                    <Entypo
                      onPress={() => onLogOut()}
                      name="log-out"
                      size={24}
                      color="black"
                    />
                  ),
                }}
              />
              <Stack.Screen name="Order" component={Order} />
            </>
          )}
        </Stack.Navigator>
      </NavigationContainer>
    </NativeBaseProvider>
  );
}

const mapState = ({ latitude, longitude, speed }: any) => ({
  latitude,
  longitude,
  speed,
});

const _App = connect(mapState)(Index);

TaskManager.defineTask(LOCATION_TASK, ({ data, error }: any) => {
  if (error) {
    // Error occurred - check `error.message` for more details.
    console.log(error);
    return;
  }
  if (data) {
    const { latitude, longitude, speed } = data?.locations[0]?.coords;
    LocationStore.dispatch(updateLocation({ latitude, longitude, speed }));
    // do something with the locations captured in the background
  }
});

export default _App;

Expo CLI Version: 6.3.2
Expo SDK: 48.0.10
Expo Location: ~15.1.1
Task Manager: ~11.1.1
React: 18.2.0
React-native: 0.71.6
Platforms: Android and iOS

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.