transistorsoft / react-native-background-geolocation

Sophisticated, battery-conscious background-geolocation with motion-detection
http://shop.transistorsoft.com/pages/react-native-background-geolocation
MIT License
2.66k stars 426 forks source link

Need Help when app is closed #2187

Open Sameer98700 opened 4 weeks ago

Sameer98700 commented 4 weeks ago

Hi,

We are trying to integrate your React Native Background Geolocation Package in our project and facing below challenges -

  1. When the user app is closed, then we need to send the current location of the user from android and iOS. We are only able to track the user but not able to receive the current location. Can you please guide which package or function we need to use in react native background geolocation package.

  2. When the user is ideal and the app is closed then we are unable to track that user. After that once the user starts moving then also we are unable to track as the starting user was unable to track. Please guide me on how to solve this issue.

  3. We added a geo facing function, when the user is away from the 50 meter radius then when the app is closed, we are unable to receive the log. But as soon as the app is open, we receive the logs. Need solution for this as well.

Facing both above uses majorly on iOS devices.

Kindly help us with the above query and give a solution to it.

christocracy commented 4 weeks ago

The issue template is required, not optional:

Your Environment

Expected Behavior

Actual Behavior

Steps to Reproduce

1. 2. 3. 4.

Context

Debug logs

Logs ``` PASTE_YOUR_LOGS_HERE ```
Sameer98700 commented 4 weeks ago

Plugin version: 4.1.1 Platform: iOS or Android both OS version: Mac OS 15.0.1 (24A348) Device manufacturer / model: 15-inch, M2, 2023 React Native version (react-native -v): 0.74.4 Plugin config ----

React.useEffect(() => {
    BackgroundGeolocation.logger
      .getLog()
      .then(log => {
        console.log('log', log);
      })
      .catch(error => {
        console.error('Error getting log:', error);
      });
    BackgroundGeolocation.deviceSettings.showIgnoreBatteryOptimizations();
    BackgroundGeolocation.onGeofence(geofence => {
      console.log('Geofence event:', geofence);
    });
    BackgroundGeolocation.onActivityChange(s =>
      console.log('onActivityChange', s),
    );

    BackgroundGeolocation.onNotificationAction(button => {
      console.log('[onNotificationAction]', button);
    });

    // Listen to location updates
    BackgroundGeolocation.onLocation(handleLocationUpdate, error => {
      console.log('[BackgroundGeolocation] location error:', error);
    });

    BackgroundGeolocation.onMotionChange(location => {
      console.log('onMotionChange', location);
    });

    initBackgroundFetch();
    initBackgroundGeolocation();

    // // Cleanup on unmount
    // return () => {
    //   // BackgroundGeolocation.removeListeners();
    // };
  }, []);

  const initBackgroundGeolocation = async () => {
    const token =
      await BackgroundGeolocation.findOrCreateTransistorAuthorizationToken(
        'phpoets',
        'Sameer98700',
        'https://tracker.transistorsoft.com',
      );

    // Configure BackgroundGeolocation
    BackgroundGeolocation.ready({
      reset: true,
      desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
      distanceFilter: 50,
      stationaryRadius: 50,
      logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE, // Enable verbose logging
      debug: true,
      activityRecognitionInterval: 1000,
      stopTimeout: 60,
      disableMotionActivityUpdates: false,
      disableElasticity: true,
      startOnBoot: true,
      heartbeatInterval: 60,
      enableHeadless: true,
      stopOnTerminate: false,
      desiredOdometerAccuracy: 10,
      allowIdenticalLocations: false,
      autoSync: true,
      autoSyncThreshold: 0,
      batchSync: true,
      maxBatchSize: 10,
      maxDaysToPersist: 2,
      foregroundService: true,
      locationAuthorizationRequest: 'Always',
      geofenceInitialTriggerEntry: true,
      geofenceModeHighAccuracy: true,
      notification: {
        title: 'Location Tracking',
        text: 'Tracking location in the background',
        color: '#ff00ff',
      },
    }).then(state => {
      // Start the Scheduler
      BackgroundGeolocation.startSchedule();
    });
  };

  // Listen to #onSchedule events:
  BackgroundGeolocation.onSchedule(state => {
    let enabled = state.enabled;
    console.log('[onSchedule] - enabled? ', enabled);
  });

  // Or modify the schedule with usual #setConfig method
  BackgroundGeolocation.setConfig({
    schedule: [
      '1-7 9:00-10:00',
      '1-7 11:00-12:00',
      '1-7 13:41-13:44',
      '1-7 15:00-16:00',
      '1-7 17:00-18:00',
      '2,4,6 19:00-22:00',
    ],
  });

  // Add a geofence.
  BackgroundGeolocation.addGeofence({
    notifyOnExit: true,
    radius: 50,
    identifier: 'ZONE_OF_INTEREST',
    latitude: location?.latitude,
    longitude: location?.longitude,
  });

  const initBackgroundFetch = async () => {
    BackgroundFetch.configure(
      {
        minimumFetchInterval: 15,
        enableHeadless: true,
        stopOnTerminate: false,
      },
      async taskId => {
        console.log('taskId', taskId);

        const location = await BackgroundGeolocation.getCurrentPosition({
          extras: {
            event: 'background-fetch',
          },
          maximumAge: 10000,
          persist: true,
          timeout: 30,
          samples: 2,
        });
        handleLocationUpdate(location);
        BackgroundFetch.finish(taskId);
      },
      async taskId => {
        console.log('[BackgroundFetch] TIMEOUT:', taskId);
        BackgroundFetch.finish(taskId);
      },
    );
  };
christocracy commented 3 weeks ago

Plugin version: 4.1.1

You're using version 4.1.1 from over two years ago?? The latest version is 4.17.4.

When the user app is closed, then we need to send the current location of the user from android and iOS. We are only able to track the user but not able to receive the current location. Can you please guide which package or function we need to use in react native background geolocation package.

For Android, see API docs Config.enableHeadless. For iOS, the OS halts BackgroundFetch events when the user terminates the app. It is impossible to receive periodic location updates on iOS when the user terminates the app. The only thing that will re-awaken a terminated iOS is to move at least 200 meters (see API docs Config.stopOnTerminate.

When the user is ideal and the app is closed then we are unable to track that user. After that once the user starts moving then also we are unable to track as the starting user was unable to track. Please guide me on how to solve this issue.

The plugin will automatically resume tracking after app terminate when the devices moves at least 200 meters. You will hear Debug SoundFX to show it's working.

We added a geo facing function, when the user is away from the 50 meter radius then when the app is closed, we are unable to receive the log. But as soon as the app is open, we receive the logs. Need solution for this as well.

The minimum geofence radius is 200 meters. Both iOS and Android do NOT respond to any radius < 200 meters. 50 meter radius geofence will not work.

christocracy commented 3 weeks ago

Also, your code is wrong.

// Configure BackgroundGeolocation
    BackgroundGeolocation.ready({
      .
      .
      .
    }).then(state => {
      // Start the Scheduler
      BackgroundGeolocation.startSchedule();
    });
  };

  // Listen to #onSchedule events:
  BackgroundGeolocation.onSchedule(state => {
    let enabled = state.enabled;
    console.log('[onSchedule] - enabled? ', enabled);
  });

  // Or modify the schedule with usual #setConfig method
  BackgroundGeolocation.setConfig({
    schedule: [
      '1-7 9:00-10:00',
      '1-7 11:00-12:00',
      '1-7 13:41-13:44',
      '1-7 15:00-16:00',
      '1-7 17:00-18:00',
      '2,4,6 19:00-22:00',
    ],
  });

You're calling .startSchedule() before a schedule is guaranteed to have even been applied via .setConfig. You need to add your schedule to the Config provided to .ready(config) or call .setConfig when .ready(config) has resolved.

Plugin method calls take an unknown amount of time to execute. That's why they return a Promise. It could happen that the .ready(config) method resolves before .setConfig or after -- it's unknown. That's why you must use await or .then() and chain your method calls accordingly.

BackgroundGeolocation.ready({
    .
    .
    .
    schedule: [
      '1-7 9:00-10:00',
      '1-7 11:00-12:00',
      '1-7 13:41-13:44',
      '1-7 15:00-16:00',
      '1-7 17:00-18:00',
      '2,4,6 19:00-22:00',
    ]
}).then((state) => {
  // Here, the Promise of the .ready method has RESOLVED.  Only now has the Config been applied.
  BackgroundGeolocation.startSchedule()
});

// It is unknown if the Promise of the .ready method has resolved yet.
// If .ready(config) resolves first, you will be calling `.startSchedule()` with an empty schedule.
BackgroundGeolocation.setConfig(config);
christocracy commented 3 weeks ago

I have a feeling you're just copy/pasting code with no understanding of how it actually works.

Also see Wiki "Debugging" and "Philosophy of Operation".

BackgroundGeolocation.logger
      .getLog()
      .then(log => {
        console.log('log', log);
      })
      .catch(error => {
        console.error('Error getting log:', error);
      });

It's pretty crazy how you console.log the plugin's getLog each time your app launches. That log con be several megabytes. Put a temporary button on your UI to execute .emailLog instead.

Sameer98700 commented 3 weeks ago

Hey,

I updated to the latest version 4.17.4 in Android, and it is working fine but in ios BackgroundGeoLocation.onLocation function does not fire when the app is closed. previously version 4.1.1 BackgroundGeoLocation.onLocation worked in ios

Note -- I added in the index.js file

Message ID: <transistorsoft/react-native-background-geolocation/issues/2187/2437813071 @github.com>

christocracy commented 3 weeks ago

Note -- I added in the index.js file

You added what in the index.js file?

Sameer98700 commented 3 weeks ago

BackgroundGeoLocation.onLocation

On Mon, 28 Oct 2024 at 7:24 PM, Chris Scott @.***> wrote:

Note -- I added in the index.js file

You added what in the index.js file?

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/react-native-background-geolocation/issues/2187#issuecomment-2441658107, or unsubscribe https://github.com/notifications/unsubscribe-auth/A3DEOKRAGCI2TTWZSGIOYETZ5Y62BAVCNFSM6AAAAABQRC5MT6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDINBRGY2TQMJQG4 . You are receiving this because you authored the thread.Message ID: <transistorsoft/react-native-background-geolocation/issues/2187/2441658107 @github.com>

christocracy commented 3 weeks ago

.onLocation does not belong in index.js. Remove it from there!

For the Android terminated state, see API docs Config.enabledHeadless.

christocracy commented 3 weeks ago

For iOS, there's no such thing as "headless". You must ensure your app calls BackgroundGeolocation.ready(config) each and every time your app launches (even if launched automatically by the OS in the background).

Sameer98700 commented 3 weeks ago

This is for android what we do for ios?

On Mon, 28 Oct 2024 at 8:11 PM, Chris Scott @.***> wrote:

.onLocation does not belong in index.js. Remove it from there!

For the Android terminated state, see API docs Config.enabledHeadless.

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/react-native-background-geolocation/issues/2187#issuecomment-2441783783, or unsubscribe https://github.com/notifications/unsubscribe-auth/A3DEOKRI5AN4VRLRX2SLR4TZ5ZEKHAVCNFSM6AAAAABQRC5MT6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDINBRG44DGNZYGM . You are receiving this because you authored the thread.Message ID: <transistorsoft/react-native-background-geolocation/issues/2187/2441783783 @github.com>

christocracy commented 3 weeks ago

iOS terminated behaviour is easily tested in the iOS simulated with location simulated with Freeway Drive.

Screenshot 2024-10-28 at 10 44 35 AM
christocracy commented 3 weeks ago

what we do for ios?

iOS will automatically relaunch your app in the background when the device is detected to be moving, just as if launched by the user from the foreground.

Sameer98700 commented 3 weeks ago

Yes I know but when app is terminated then how to show updated location logs and which function provide me a logs

On Mon, 28 Oct 2024 at 8:15 PM, Chris Scott @.***> wrote:

iOS terminated behaviour is easily tested in the iOS simulated with location simulated with Freeway Drive. Screenshot.2024-10-28.at.10.44.35.AM.png (view on web) https://github.com/user-attachments/assets/9b7e461d-d937-44ef-9275-11ca93ed17ab

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/react-native-background-geolocation/issues/2187#issuecomment-2441793881, or unsubscribe https://github.com/notifications/unsubscribe-auth/A3DEOKUHMFKEKXNPPL6GL73Z5ZEYNAVCNFSM6AAAAABQRC5MT6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDINBRG44TGOBYGE . You are receiving this because you authored the thread.Message ID: <transistorsoft/react-native-background-geolocation/issues/2187/2441793881 @github.com>

christocracy commented 3 weeks ago

then how to show updated location

on iOS, every recorded location is sent to your .onLocation event-listener.

christocracy commented 3 weeks ago

Search API docs "emailLog"

Sameer98700 commented 3 weeks ago

This is not working for me

On Mon, 28 Oct 2024 at 8:21 PM, Chris Scott @.***> wrote:

then how to show updated location

on iOS, every recorded location is sent to your .onLocation event-listener.

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/react-native-background-geolocation/issues/2187#issuecomment-2441810163, or unsubscribe https://github.com/notifications/unsubscribe-auth/A3DEOKVMQH4UGA7Z7MQ24TDZ5ZFNXAVCNFSM6AAAAABQRC5MT6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDINBRHAYTAMJWGM . You are receiving this because you authored the thread.Message ID: <transistorsoft/react-native-background-geolocation/issues/2187/2441810163 @github.com>

christocracy commented 3 weeks ago

"what" is not working for you?

Sameer98700 commented 3 weeks ago

How it works?

On Mon, 28 Oct 2024 at 8:21 PM, Chris Scott @.***> wrote:

Search API docs "emailLog"

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/react-native-background-geolocation/issues/2187#issuecomment-2441811716, or unsubscribe https://github.com/notifications/unsubscribe-auth/A3DEOKUEEBLBOEPVQQZWIS3Z5ZFPHAVCNFSM6AAAAABQRC5MT6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDINBRHAYTCNZRGY . You are receiving this because you authored the thread.Message ID: <transistorsoft/react-native-background-geolocation/issues/2187/2441811716 @github.com>

christocracy commented 3 weeks ago

How "what" works?

christocracy commented 3 weeks ago

Are you testing your app in the iOS Simulator, simulating location with Freeway Drive?

Sameer98700 commented 3 weeks ago

.onLocation not working when app is terminated. It only works on foreground

On Mon, 28 Oct 2024 at 8:24 PM, Chris Scott @.***> wrote:

"what" is not working for you?

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/react-native-background-geolocation/issues/2187#issuecomment-2441818863, or unsubscribe https://github.com/notifications/unsubscribe-auth/A3DEOKWZMAQZHILP2ASRHE3Z5ZFYTAVCNFSM6AAAAABQRC5MT6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDINBRHAYTQOBWGM . You are receiving this because you authored the thread.Message ID: <transistorsoft/react-native-background-geolocation/issues/2187/2441818863 @github.com>

Sameer98700 commented 3 weeks ago

Yes

On Mon, 28 Oct 2024 at 20:25, Chris Scott @.***> wrote:

Are you testing your app in the iOS Simulator, simulating location with Freeway Drive?

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/react-native-background-geolocation/issues/2187#issuecomment-2441823592, or unsubscribe https://github.com/notifications/unsubscribe-auth/A3DEOKVKZQ6N7I4DYBJTU43Z5ZF6LAVCNFSM6AAAAABQRC5MT6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDINBRHAZDGNJZGI . You are receiving this because you authored the thread.Message ID: <transistorsoft/react-native-background-geolocation/issues/2187/2441823592 @github.com>

christocracy commented 3 weeks ago

Show me logs of your app launching in the iOS simulator.

Sameer98700 commented 3 weeks ago

Ok wait

On Mon, 28 Oct 2024 at 22:00, Chris Scott @.***> wrote:

Show me logs of your app launching in the iOS simulator.

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/react-native-background-geolocation/issues/2187#issuecomment-2442070978, or unsubscribe https://github.com/notifications/unsubscribe-auth/A3DEOKRJKML7EA7US7GDH3LZ5ZRD3AVCNFSM6AAAAABQRC5MT6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDINBSGA3TAOJXHA . You are receiving this because you authored the thread.Message ID: <transistorsoft/react-native-background-geolocation/issues/2187/2442070978 @github.com>