Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Need Help when app is closed #2187

Open
Sameer98700 opened this issue Oct 24, 2024 · 25 comments
Open

Need Help when app is closed #2187

Sameer98700 opened this issue Oct 24, 2024 · 25 comments

Comments

@Sameer98700
Copy link

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
Copy link
Member

The issue template is required, not optional:

Your Environment

  • Plugin version:
  • Platform: iOS or Android
  • OS version:
  • Device manufacturer / model:
  • React Native version (react-native -v):
  • Plugin config
PASTE_YOUR_CODE_HERE

Expected Behavior

Actual Behavior

Steps to Reproduce

Context

Debug logs

Logs
PASTE_YOUR_LOGS_HERE

@Sameer98700
Copy link
Author

Sameer98700 commented Oct 25, 2024

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
Copy link
Member

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
Copy link
Member

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
Copy link
Member

christocracy commented Oct 25, 2024

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
Copy link
Author

Sameer98700 commented Oct 26, 2024 via email

@christocracy
Copy link
Member

Note -- I added in the index.js file

You added what in the index.js file?

@Sameer98700
Copy link
Author

Sameer98700 commented Oct 28, 2024 via email

@christocracy
Copy link
Member

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

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

@christocracy
Copy link
Member

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
Copy link
Author

Sameer98700 commented Oct 28, 2024 via email

@christocracy
Copy link
Member

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
Copy link
Member

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
Copy link
Author

Sameer98700 commented Oct 28, 2024 via email

@christocracy
Copy link
Member

then how to show updated location

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

@christocracy
Copy link
Member

Search API docs "emailLog"

@Sameer98700
Copy link
Author

Sameer98700 commented Oct 28, 2024 via email

@christocracy
Copy link
Member

"what" is not working for you?

@Sameer98700
Copy link
Author

Sameer98700 commented Oct 28, 2024 via email

@christocracy
Copy link
Member

How "what" works?

@christocracy
Copy link
Member

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

@Sameer98700
Copy link
Author

Sameer98700 commented Oct 28, 2024 via email

@Sameer98700
Copy link
Author

Sameer98700 commented Oct 28, 2024 via email

@christocracy
Copy link
Member

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

@Sameer98700
Copy link
Author

Sameer98700 commented Oct 28, 2024 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants