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.58k stars 425 forks source link

Push Notifications Not Triggering on Geofence Entry When App is Closed #2083

Open Gentlekboy opened 1 week ago

Gentlekboy commented 1 week ago

Your Environment

const Tab = createBottomTabNavigator();

const TabNavigator = () => { const dispatch = useAppDispatch();

const {onSendPush} = useSendPush();

const {deviceSlice, settingsSlice} = useAppSelector( state => state.rootReducer, ); const {isBackgroundServiceRunning} = settingsSlice; const {deviceId} = deviceSlice;

useEffect(() => { const requestUserPermission = async () => { const authStatus = await messaging().requestPermission(); const enabled = authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL;

  if (enabled) {
    messaging()
      .getToken()
      .then(token => {
        token && dispatch(saveFcmToken(token));
      })
      .catch(error => {
        const errorMessage =
          error || "Something went wrong getting FCM token";
        console.log("FCM ERROR", error);
        Alert.alert("FCM ERROR", `${errorMessage}`);
      });
  }
};

requestUserPermission();

}, [messaging, deviceId]);

useEffect(() => { BackgroundGeolocation.ready({ desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH, distanceFilter: 10, stopTimeout: 5, debug: true, logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE, stopOnTerminate: false, startOnBoot: true, }) .then(state => { console.log("- BackgroundGeolocation Status: ", state.enabled); }) .catch(error => console.log("Background location ready failed", error));

const onGeofenceChangeSubscription = BackgroundGeolocation.onGeofence(
  event => {
    const {action, identifier, extras} = event;

    const message = geoFenceAction(action, extras?.name as string);

    if (action === "ENTER") {
      console.log("[onLocationSubscription for ENTER] ", event);

      if (deviceId) {
        onSendPush({poiId: identifier, userOrDeviceId: deviceId});
      } else {
        onDisplayNotification("No FCM token", message);
      }
    } else {
      console.log("[onLocationSubscription for OTHERS] ", event);

      onDisplayNotification("Geofence Activity Detected", message);
    }
  },
);

const onGeofencesChangeSubscription =
  BackgroundGeolocation.onGeofencesChange(event => {
    let on = event.on;
    let off = event.off;

    on.forEach(geofence => {
      console.log("[new geofences activated] ", geofence);
    });

    off.forEach(identifier => {
      console.log("[geofences that were just de-activated] ", identifier);
    });
  });

const onLocationSubscription = BackgroundGeolocation.onLocation(
  event => {},
);

return () => {
  onLocationSubscription.remove();
  onGeofencesChangeSubscription.remove();
  onGeofenceChangeSubscription.remove();
};

}, []);

useEffect(() => { if (isBackgroundServiceRunning) { BackgroundGeolocation.start() .then(res => console.log("BackgroundGeolocation.start", res.enabled)) .catch(err => console.log("BackgroundGeolocation.start", err)); } else { BackgroundGeolocation.stop() .then(res => console.log("BackgroundGeolocation.stop", res.enabled)) .catch(err => console.log("BackgroundGeolocation.stop", err)); } }, [isBackgroundServiceRunning]);

return ( <Tab.Navigator screenOptions={{ tabBarActiveTintColor: "#e91e63", }}> <Tab.Screen name="Home" component={MapScreen} options={{ tabBarLabel: "Home", tabBarIcon: ({color, size}) => (

      ),
    }}
  />

  <Tab.Screen
    name="GeofenceList"
    component={GeofencesScreen}
    options={{
      headerShown: false,
      unmountOnBlur: true,
      tabBarLabel: "GeoFences",
      tabBarIcon: ({color, size}) => (
        <MaterialCommunityIcons name="apps" color={color} size={size} />
      ),
    }}
  />

  <Tab.Screen
    name="Settings"
    component={SettingsScreen}
    options={{
      unmountOnBlur: true,
      tabBarLabel: "Settings",
      tabBarIcon: ({color, size}) => (
        <MaterialCommunityIcons name="settings" color={color} size={size} />
      ),
    }}
  />
</Tab.Navigator>

); };

export default TabNavigator;


## Expected Behavior
The app should trigger a push notification when a user enters a geofence, regardless of whether the app is in the foreground, background, or closed

## Actual Behavior
When the app is in the foreground, the user receives notifications upon entering a geofence. However, if the app is closed, there are no triggers on geofence entry

## Steps to Reproduce
1. Clone the project from [GitHub](https://github.com/Gentlekboy/pushNotificationApp)
2. Install dependencies and set up the environment
3. Close the app and enter a geofence area

## Context
I am trying to trigger push notifications for users when they enter a geofence. The notifications work fine when the app is in the foreground but fail to trigger when the app is closed

## Debug logs
<!-- include iOS / Android logs
- ios XCode logs,
- use #getLog #emailLog methods (@see docs)
- Android: $ adb logcat -s TSLocationManager
-->
<details><summary>Logs</summary>

``` <!-- Syntax highlighting:  DO NOT REMOVE -->
PASTE_YOUR_LOGS_HERE

christocracy commented 1 week ago

See wiki “Debugging”. Search api docs “emailLog” to learn how to retrieve plug-in logs,