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

How should I send my current location while on background? #2197

Open Sitallcom opened 2 weeks ago

Sitallcom commented 2 weeks ago

How should I send my current location while on background?

interface LocationContextType { currentLocation: Location | undefined; }

interface LocationContextProps { children: React.ReactNode; }

export const LocationContext = createContext({} as LocationContextType);

export function LocationContextProvider({ children }: LocationContextProps) { const {uid, token} = useContext(UserContext); const [currentLocation, setCurrentLocation] = useState<Location | undefined>(); const [arrayLocations, setArrayLocations] = useState([]);

async function configBackgroundGeolocation() {
    await BackgroundGeolocation.ready({
        desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
        distanceFilter: 0,
        stopTimeout: 1,
        debug: false,
        logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
        disableMotionActivityUpdates: true,
        stopOnTerminate: false,
        startOnBoot: true,
        locationUpdateInterval: 1000,
        fastestLocationUpdateInterval: 1000,
        useSignificantChangesOnly: false,
        disableElasticity: true,
        preventSuspend: true,
        url: 'http://my.server.com',
        params: {
            user_id: 123,
        },
        headers: {
            'my-auth-token': 'secret-key',
        },
    }).then((state) => {

    }).catch((error) => {
        console.error(error);
    });
}

useEffect(() => {
    try {
        configBackgroundGeolocation();
    } catch (error) {
        console.error(error);
    } finally {
        console.log('Finished processing background geolocation');
    }
}, []);

useEffect(() => {
    const saveLocationsToStore = async () => {
        try {
            await saveValue('location', JSON.stringify(arrayLocations)); // Convertendo arrayLocations para string JSON
            console.log('Locations saved to Secure Store');
        } catch (error) {
            console.error('Error saving locations to Secure Store:', error);
        }
    };

    saveLocationsToStore();
}, [arrayLocations]);

 async function sendLocation(body: Location) {
    if (body && uid && token) {
        handleSetCurrentLocation(body);
        const response: AxiosResponse = await updateLocation(uid, token, body);
        handleResponse(response);
    }else{
        console.log('Missing uid, token or body');
    }
}

function handleResponse(response: AxiosResponse){
    if(response.status === 200){
        console.log('Response: ', response.status);
    }else{
        console.log('Error sending location: ', response.status);
    }
}

useEffect(() => {
    BackgroundGeolocation.onLocation(async (location: Location) => {
        handleSetCurrentLocation(location);
        const objectToSend = {
            ...location,
            now: Date.now(),
        };
        sendLocation(objectToSend);
    });

    BackgroundGeolocation.onHeartbeat((heartbeatEvent) => {
        const objectToSend = {
            ...heartbeatEvent.location,
            now: Date.now(),
        };
        sendLocation(objectToSend);
        saveValue('location', JSON.stringify(objectToSend));
        handleSetCurrentLocation(heartbeatEvent.location);

        setArrayLocations((prevLocations) => [...prevLocations, heartbeatEvent.location]);
    });

    BackgroundGeolocation.onMotionChange(async (event) => {
        if (event.isMoving) {
            const objectToSend = {
                ...event.location,
                now: Date.now(),
            };

            sendLocation(objectToSend);
        } else {
            console.log('[onMotionChange] Device has just STOPPED:  ', event.location);
        }
    });

    BackgroundGeolocation.start();

}, []);

 function handleSetCurrentLocation(location: Location){
     setCurrentLocation(location);
}

return (
    <LocationContext.Provider value={{currentLocation}}>
        {children}
    </LocationContext.Provider>
);

}


## Expected Behavior
<!--- Tell us what should happen -->
Send current location to the API( updateLocation() )in foreground and background while moving

## Actual Behavior
<!--- Tell us what happens instead -->
I'm using my API (updateLocation()) to store my current location, but I noticed that it only works when I'm in the foreground.
When I move, the app notifies me that the service is enabled, but it doesn't send my current location

## Steps to Reproduce
<!--- reproduce this issue; include code to reproduce, if relevant -->
1. Start moving
2. The service starts 
3. It doesn't send my current location
4. Open the App
5. Update my location

## Context
<!--- What were you trying to do? -->

## 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 2 weeks ago

url: 'http://my.server.com',

Why are you providing an url to the plugin and performing your own http requests?

Sitallcom commented 2 weeks ago

I removed this but it didn't solve it

christocracy commented 2 weeks ago

Are you testing this while sitting at your desk or going outside to move at least 200 meters?

read the wiki here “Philosophy of Operation”.

Sitallcom commented 2 weeks ago

During my tests I walked out of my office walk for some Kms. One time one of my coworkers went home like (12kms) with the app in background and it didn't communicated

christocracy commented 2 weeks ago

See https://dontkillmyapp.com

also see wiki “Debugging” and learn to fetch the plug-ins incredibly verbose logs via method .emailLog (see API docs for more information).

christocracy commented 2 weeks ago

debug: false,

The first thing you do when something unusual happens is set that to true so you can hear the plug-in operating.