react-native-background-geolocation icon indicating copy to clipboard operation
react-native-background-geolocation copied to clipboard

[Help Wanted]: Location not updating

Open maheshscognitivebotics opened this issue 6 months ago • 5 comments

Required Reading

  • [x] Confirmed

Plugin Version

latest

Mobile operating-system(s)

  • [ ] iOS
  • [x] Android

Device Manufacturer(s) and Model(s)

Pixel 8

Device operating-systems(s)

Android 14

React Native / Expo version

0.76.6

What do you require assistance about?

import React, {useEffect} from 'react';
import {Switch, Text, View} from 'react-native';

import BackgroundGeolocation, {
  Location,
  Subscription,
} from 'react-native-background-geolocation';
import BackgroundFetch from 'react-native-background-fetch';

const App = () => {
  const [enabled, setEnabled] = React.useState(false);
  const [location, setLocation] = React.useState('');
  const [isMoving, setIsMoving] = React.useState(false);
  const [odometer, setOdometer] = React.useState(0);

  React.useEffect(() => {
    /// 1.  Subscribe to events.
    const onLocation = BackgroundGeolocation.onLocation(location => {
      console.log('[onLocation]', location);
      setLocation(JSON.stringify(location, null, 2));
    });

    const onMotionChange = BackgroundGeolocation.onMotionChange(event => {
      console.log('[onMotionChange]', event);
    });

    const onActivityChange = BackgroundGeolocation.onActivityChange(event => {
      console.log('[onActivityChange]', event);
    });

    const onProviderChange = BackgroundGeolocation.onProviderChange(event => {
      console.log('[onProviderChange]', event);
    });

    initBackgroundFetch();

    initBackgroundGeolocation();

    return () => {
      // Remove BackgroundGeolocation event-subscribers when the View is removed or refreshed
      // during development live-reload.  Without this, event-listeners will accumulate with
      // each refresh during live-reload.
      onLocation.remove();
      onMotionChange.remove();
      onActivityChange.remove();
      onProviderChange.remove();
    };
  }, []);

  const initBackgroundGeolocation = async () => {
    /// 3. start  const initBackgroundGeolocation = async () => {
    // Get an authorization token from transistorsoft demo server.
    const token =
      await BackgroundGeolocation.findOrCreateTransistorAuthorizationToken(
        'maheshs',
        'mahesh',
        'https://tracker.transistorsoft.com',
      );

    // Ready the SDK and fetch the current state.
    const state = await BackgroundGeolocation.ready({
      // Debug
      reset: false,
      debug: true,
      logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
      transistorAuthorizationToken: token,
      // Geolocation
      desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_NAVIGATION,
      distanceFilter: 10,
      stopTimeout: 5,
      // Permissions
      locationAuthorizationRequest: 'Always',
      backgroundPermissionRationale: {
        title:
          "Allow {applicationName} to access this device's location even when closed or not in use.",
        message:
          'This app collects location data to enable recording your trips to work and calculate distance-travelled.',
        positiveAction: 'Change to "{backgroundPermissionOptionLabel}"',
        negativeAction: 'Cancel',
      },
      // HTTP & Persistence
      autoSync: true,
      maxDaysToPersist: 14,
      // Application
      stopOnTerminate: false,
      startOnBoot: true,
      enableHeadless: true,
    });

    setOdometer(state.odometer);
    setEnabled(state.enabled);
    setIsMoving(state.isMoving || false); // <-- TODO re-define @prop isMoving? as REQUIRED in State
  };

  const initBackgroundFetch = async () => {
    BackgroundFetch.configure(
      {
        minimumFetchInterval: 15,
        enableHeadless: true,
        stopOnTerminate: false,
      },
      async taskId => {
        console.log('[BackgroundFetch]', taskId);
        const location = await BackgroundGeolocation.getCurrentPosition({
          extras: {
            event: 'background-fetch',
          },
          maximumAge: 10000,
          persist: true,
          timeout: 30,
          samples: 2,
        });
        console.log('[getCurrentPosition]', location);
        BackgroundFetch.finish(taskId);
      },
      async taskId => {
        console.log('[BackgroundFetch] TIMEOUT:', taskId);
        BackgroundFetch.finish(taskId);
      },
    );
  };
  React.useEffect(() => {
    if (enabled) {
      BackgroundGeolocation.startGeofences();
    } else {
      BackgroundGeolocation.stop();
      setLocation('');
    }
  }, [enabled]);

  return (
    <View style={{alignItems: 'center'}}>
      <Text>Click to enable BackgroundGeolocation</Text>
      <Switch value={enabled} onValueChange={setEnabled} />
      <Text style={{fontFamily: 'monospace', fontSize: 12}}>{location}</Text>
    </View>
  );
};

export default App;

[Optional] Plugin Code and/or Config


[Optional] Relevant log output


maheshscognitivebotics avatar May 22 '25 17:05 maheshscognitivebotics

Show me plug-in logs of your app launching from a terminated state.

christocracy avatar May 22 '25 18:05 christocracy

[setConfig] success: {"activityRecognitionInterval": 10000, "allowIdenticalLocations": false, "authorization": {}, "autoSync": false, "autoSyncThreshold": 0, "backgroundPermissionRationale": {"message": "Allow location tracking in background", "negativeAction": "", "positiveAction": "Change to \"{backgroundPermissionOptionLabel}\"", "title": "Allow {applicationName} to access this device's location even when closed or not in use?"}, "batchSync": false, "configUrl": "", "crashDetector": {"accelerometerThresholdHigh": 20, "accelerometerThresholdLow": 4.5, "enabled": false, "gyroscopeThresholdHigh": 20, "gyroscopeThresholdLow": 4.5}, "debug": true, "deferTime": 0, "desiredAccuracy": -1, "desiredOdometerAccuracy": 100, "didDeviceReboot": false, "didLaunchInBackground": false, "disableAutoSyncOnCellular": false, "disableElasticity": false, "disableLocationAuthorizationAlert": false, "disableMotionActivityUpdates": false, "disableProviderChangeRecord": false, "disableStopDetection": false, "distanceFilter": 10, "elasticityMultiplier": 1, "enableHeadless": false, "enableTimestampMeta": false, "enabled": false, "extras": {}, "fastestLocationUpdateInterval": -1, "foregroundService": true, "geofenceInitialTriggerEntry": true, "geofenceModeHighAccuracy": false, "geofenceProximityRadius": 1000, "geofenceTemplate": "", "headers": {}, "headlessJobService": "com.transistorsoft.rnbackgroundgeolocation.HeadlessTask", "heartbeatInterval": -1, "httpRootProperty": "location", "httpTimeout": 60000, "isFirstBoot": false, "isMoving": true, "locationAuthorizationRequest": "Always", "locationTemplate": "", "locationTimeout": 60, "locationUpdateInterval": 1000, "locationsOrderDirection": "ASC", "logLevel": 5, "logMaxDays": 3, "maxBatchSize": -1, "maxDaysToPersist": 1, "maxMonitoredGeofences": 97, "maxRecordsToPersist": -1, "method": "POST", "minimumActivityRecognitionConfidence": 75, "motionTriggerDelay": 0, "notification": {"actions": [], "channelId": "", "channelName": "TSLocationManager", "color": "", "largeIcon": "", "layout": "", "priority": -1, "smallIcon": "", "sticky": false, "strings": {}, "text": "Location Service activated", "title": ""}, "odometer": 61.13440704345703, "params": {}, "persist": true, "persistMode": 2, "schedule": [], "scheduleUseAlarmManager": false, "schedulerEnabled": false, "speedJumpFilter": 300, "startOnBoot": true, "stationaryRadius": 25, "stopAfterElapsedMinutes": 0, "stopOnStationary": false, "stopOnTerminate": true, "stopTimeout": 10, "trackingMode": 1, "triggerActivities": "in_vehicle, on_bicycle, on_foot, running, walking", "url": "", "useSignificantChangesOnly": false}

maheshscognitivebotics avatar May 24 '25 13:05 maheshscognitivebotics

lass GeolocationService {
  constructor() {

  }

  async ready() {
    BackgroundGeolocation.ready(
      {
        distanceFilter: 10,
        //desiredAccuracy: 0,
        desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
        logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
        debug: true,
        stopTimeout: 10,
        stopOnTerminate: true, // <-- Allow the background-service to continue tracking when app terminated.
        startOnBoot: true, // <-- Auto start tracking when device is powered-up.
        batchSync: false, // <-- Set true to sync locations to server in a single HTTP request.
        autoSync: false, // <-- Set true to sync each location to server as it arrives.
        backgroundPermissionRationale: {
          message: 'Allow location tracking in background',
        },
      },
      state => {
        console.log('- BackgroundGeolocation is ready: ', state);
        console.log('- BackgroundGeolocation is ready state: ', state.enabled);
      },
    );
  }
  async configure(config) {
    BackgroundGeolocation.setConfig({
      desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
      // distanceFilter: config.distanceFilter,
      distanceFilter: 10,
      isMoving: true,
    }).then(state => {
      console.log('[setConfig] success: ', state);
    });
  }

  async requestPermission() {
    return await BackgroundGeolocation.requestPermission();
  }

  startTracking() {
    BackgroundGeolocation.start().then(state => {
      console.log('- Start success: ', state);
    });
  }

  stopTracking() {
    BackgroundGeolocation.stop();
  }
}

const geoService = new GeolocationService();
export default geoService;

**When app initialize first time:**
 useEffect(() => {
    geoService.ready();
  }, []);


In screen:
 useEffect(() => {
    geoService.configure(mapConfig);
  }, [mapConfig]);

  useEffect(() => {
    BackgroundGeolocation.onLocation(
      location => {
        console.log('[location] ', location);
        setCurrentLocation({
          latitude: location.coords.latitude,
          longitude: location.coords.longitude,
          heading: location?.coords.heading,
        });
      },
      error => {
        console.log('[location] ERROR: ', error);
      },
    );
    // Start traking
    geoService.startTracking();


  }, []);

maheshscognitivebotics avatar May 24 '25 13:05 maheshscognitivebotics

Some time working this code in background and foreground but not always.

maheshscognitivebotics avatar May 24 '25 13:05 maheshscognitivebotics

See api docs Config.TransistorAuthorizationToken to configure your app to post to my test server. Let me know the params you use so I can view it myself.

christocracy avatar May 24 '25 13:05 christocracy

This issue is stale because it has been open for 30 days with no activity.

github-actions[bot] avatar Jun 24 '25 02:06 github-actions[bot]

This issue was closed because it has been inactive for 14 days since being marked as stale.

github-actions[bot] avatar Jul 08 '25 02:07 github-actions[bot]