Skip to content

[Help Wanted]: when switching on iOS simulator to vehicle, location is being tracked even its excluded from triggerActivities #2455

@AdamKundracik

Description

@AdamKundracik

Required Reading

  • Confirmed

Plugin Version

4.16.5

Mobile operating-system(s)

  • iOS
  • Android

Device Manufacturer(s) and Model(s)

iPhone 16 Pro

Device operating-systems(s)

iOS 18.6

React Native / Expo version

0.79.6, Expo 53

What do you require assistance about?

Having this config, it let during vehicle ride trigger my location detection even I excluded it from list.
Also would like to know if there is any way to make this config better, or what settings are not necessary

I just need to:

  • Locate user every 15m
  • When user is not moving, last time save his location, and when he moves again, start location again
  • When user is in car, dont track him (Bcs it triggers too many calls to DB too quickly with DistanceFilter set to 15m).

Thanks for help!

[Optional] Plugin Code and/or Config

useEffect(() => {
    if (!userId) {
      console.log('[useLocation] Waiting for userId...', { userId });
      return;
    }

    let onLocationSubscription: { remove: () => void } | null = null;
    let onHttpSubscription: { remove: () => void } | null = null;
    let onMotionChangeSubscription: { remove: () => void } | null = null;
    let onProviderChangeSubscription: { remove: () => void } | null = null;

    const setupBackgroundLocation = async () => {
      console.log(
        '[useLocation] Setting up BackgroundGeolocation with userId:',
        userId
      );

      // Get access token for HTTP requests
      const accessToken = await tokenManager.getAccessToken();
      const locationUrl = `${API_CONFIG.BASE_URL}${ENDPOINTS.USERS.LOCATION(userId)}`;

      console.log('[useLocation] Location URL:', locationUrl);
      console.log('[useLocation] Access token available:', !!accessToken);

      // Location event listener
      onLocationSubscription = BackgroundGeolocation.onLocation(event => {
        if (!event.coords?.latitude || !event.coords?.longitude) return;

        const currentLocation: LocationType = {
          latitude: event.coords.latitude,
          longitude: event.coords.longitude,
        };

        console.log('[useLocation] 📍 onLocation:', {
          lat: currentLocation.latitude.toFixed(6),
          lng: currentLocation.longitude.toFixed(6),
          activity: event.activity?.type,
          isMoving: event.is_moving,
          odometer: Math.round(event.odometer || 0),
        });

        locationRef.current = currentLocation;
        setLocation(currentLocation);
      });

      onMotionChangeSubscription = BackgroundGeolocation.onMotionChange(
        event => {
          console.log('[useLocation] 🚶 onMotionChange:', {
            isMoving: event.isMoving,
            location: event.location?.coords
              ? `${event.location.coords.latitude.toFixed(6)}, ${event.location.coords.longitude.toFixed(6)}`
              : 'N/A',
          });
        }
      );

      onProviderChangeSubscription = BackgroundGeolocation.onProviderChange(
        event => {
          console.log('[useLocation] ⚙️ onProviderChange:', {
            enabled: event.enabled,
            status: event.status,
            gps: event.gps,
            network: event.network,
          });
        }
      );

      onHttpSubscription = BackgroundGeolocation.onHttp(event => {
        console.log('[useLocation] 🌐 HTTP Response:', {
          success: event.success,
          status: event.status,
          responseText: event.responseText?.substring(0, 200),
        });
      });

      const state = await BackgroundGeolocation.ready({
        url: locationUrl,
        method: 'PATCH' as any,
        headers: accessToken
          ? {
              Authorization: `Bearer ${accessToken}`,
              'Content-Type': 'application/json',
            }
          : {
              'Content-Type': 'application/json',
            },
        locationTemplate:
          '{"latitude":<%= latitude %>,"longitude":<%= longitude %>}',
        httpRootProperty: '.', // Place data in root of JSON

        autoSync: true,
        autoSyncThreshold: 0,
        batchSync: false,
        httpTimeout: 30000,
        maxRecordsToPersist: 100,
        locationsOrderDirection: 'ASC',

        disableLocationAuthorizationAlert: true,
        locationAuthorizationRequest: 'Always',
        desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_NAVIGATION,
        distanceFilter: 15,
        debug: __DEV__,
        logLevel: __DEV__
          ? BackgroundGeolocation.LOG_LEVEL_VERBOSE
          : BackgroundGeolocation.LOG_LEVEL_OFF,
        stopOnTerminate: false,
        startOnBoot: true,
        showsBackgroundLocationIndicator: false,
        triggerActivities: 'on_foot, walking, running',

        // Stop detection - go to STATIONARY after stopTimeout
        disableStopDetection: false, // Enable stop detection
        stopTimeout: 5, // 5 minutes without movement -> STATIONARY
        disableMotionActivityUpdates: false,
        stationaryRadius: 5,
        heartbeatInterval: 60,

        locationUpdateInterval: 10000,
        fastestLocationUpdateInterval: 5000,
        locationTimeout: 60,
        deferTime: 0,

        pausesLocationUpdatesAutomatically: false,

        isMoving: true,
      });
      setIsPluginReady(true);
    };

    setupBackgroundLocation();

    return () => {
      onLocationSubscription?.remove();
      onHttpSubscription?.remove();
      onMotionChangeSubscription?.remove();
      onProviderChangeSubscription?.remove();
    };
  }, [userId, setLocation]);

[Optional] Relevant log output

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions