Comments (12)
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
from react-native-background-geolocation.
Your Environment
- Plugin version: 4.16.2
- Platform: Android
- OS version: Windows 11
- Device manufacturer / model: Motorola Edge 20
- React Native version (
react-native -v
): 0.71.14 - Plugin config
import React from 'react';
import * as Network from 'expo-network';
import useStorage from "../hooks/useStorage";
import documentRepository from "../repositories/documentRepository";
import http from "../services/http";
import moment from "moment";
import BackgroundGeolocation from "react-native-background-geolocation";
const AppContext = React.createContext();
export function useApp() {
return React.useContext(AppContext);
}
export function AppProvider(props) {
const [config, setConfig] = React.useState(null);
const [deliveries, setDeliveries] = React.useState(0);
const [locationStarted, SetLocationStarted] = React.useState(false);
const subscriptionsEvents = [];
const storage = useStorage();
React.useEffect(() => {
(async () => {
await initBackgroundLocation();
await loadConfig();
})();
return () => {
unsubscribe();
}
}, []);
React.useEffect(() => {
if (!config) return;
console.log("[Config]", config);
console.log("[Deliveries]", deliveries);
if (!locationStarted && config.capturaLocalizacao && deliveries > 0) {
BackgroundGeolocation.start();
SetLocationStarted(true);
console.log("[LOCATION STARTED]");
}
if (locationStarted && (!config.capturaLocalizacao || deliveries == 0)) {
BackgroundGeolocation.stop();
SetLocationStarted(false);
console.log("[LOCATION STOPED]");
}
}, [config, deliveries]);
function subscribe(subscription) {
subscriptionsEvents.push(subscription);
}
function unsubscribe() {
subscriptionsEvents.forEach((subscription) => subscription.remove());
}
async function loadConfig() {
const configData = await storage.get('config-data');
setConfig(configData);
}
async function initBackgroundLocation() {
subscribe(BackgroundGeolocation.onLocation(async(location) => {
console.log('[onLocation]', location);
await processLocation(location);
}));
// subscribe(BackgroundGeolocation.onMotionChange((event) => {
// console.log('[onMotionChange]', event);
// }));
// subscribe(BackgroundGeolocation.onActivityChange((event) => {
// console.log('[onActivityChange]', event);
// }));
// subscribe(BackgroundGeolocation.onProviderChange((event) => {
// console.log('[onProviderChange]', event);
// }));
BackgroundGeolocation.ready({
locationAuthorizationRequest: "Always",
desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
distanceFilter: 4,
stopTimeout: 3,
debug: true,
logLevel: BackgroundGeolocation.LOG_LEVEL_OFF,
stopOnTerminate: false,
startOnBoot: true,
allowIdenticalLocations: false,
showsBackgroundLocationIndicator: true
}).then((state) => {
SetLocationStarted(state.enabled);
});
}
async function processLocation(location) {
const storage = useStorage();
const userData = await storage.get('user-data');
const lastLocationData = await storage.get('lastLocation-data');
const {isConnected} = await Network.getNetworkStateAsync();
console.log("[processLocations]", config, deliveries);
if (isConnected && userData && config && config.capturaLocalizacao && deliveries > 0) {
const {cpf, plate, code} = userData;
const document = await documentRepository.first(code, plate, cpf);
const dataLocalizacao = moment();
const latitude = String(location.coords.latitude);
const longitude = String(location.coords.longitude);
//Valida se a Localização deve ser processada
if (lastLocationData) {
const difLocalizacao = dataLocalizacao.diff(lastLocationData.dataLocalizacao, 'minutes');
if (difLocalizacao < config.intervaloLocalizacao || (lastLocationData.latitude === latitude && lastLocationData.longitude === longitude)) {
return;
}
}
//Valida se tem Documento de Transporte informado
if (document && document?.documento_transporte !== null && document?.documento_transporte !== '') {
const lastLocation = {
transportadora: {
transportadoraId: parseInt(code),
},
filialSigla: document.filial_sigla,
motoristaCpf: cpf.replace('-', '').replaceAll('.', ''),
veiculoPlaca: plate.replace('-', ''),
tipoDocTransporte: {
tipoDocumentoId: parseInt(document.tipo_doc_transporte),
},
documentoTransporte: document.documento_transporte,
latitude,
longitude,
dataLocalizacao
};
console.log('Nova Localização: ', lastLocation);
await storage.set('lastLocation-data', lastLocation);
await http.setLocalizacaoMotorista(lastLocation);
}
}
}
return (
<AppContext.Provider
value={{
config,
setConfig,
setDeliveries
}}
>
{props.children}
</AppContext.Provider>
);
};
Expected Behavior
Understand state changes
Actual Behavior
The Plugin does not recognize state changes in the "config" and "deliveries" variables when calling the processLocation function in onLocation event.
Steps to Reproduce
- npx expo run:android
Context
Test Plugin
Debug logs
Logs
PASTE_YOUR_LOGS_HERE
Chris, maybe it's something I'm doing wrong, as I'm no expert in RN, but I have the following situation, as soon as I start the application for the first time, the plugin doesn't get the updated values of my state, and in the onLocation event I'm calling an asynchronous function that checks the values of my states and executes some routines in my application... but as the values are null, my routine is wrong. The first thing I do is start the plugin and then my state variables. It's okay that in the first onLocation events they will be null, but even after they have a value, the plugin continues to understand that they are null... The plugin cannot recognize changes in the RN's state??? Now if I make any change to the code that generates a live reload then it gets the updated state value.
Thank you!
from react-native-background-geolocation.
The plug-in is not involved with React State.
from react-native-background-geolocation.
Hi Chris, I didn't understand your answer. Could you explain better?
from react-native-background-geolocation.
the plugin doesn't get the updated values of my state
The plug-in is not responsible for your State variables.
from react-native-background-geolocation.
Ok Chris
from react-native-background-geolocation.
Hi Chris, I refactored my code to no longer use anything related to React State, everything works perfectly when I'm in the foreground and background, but when I close the application the location sounds continue to come, but my function called in onLocation stops working. When you open the application again, everything works again. Could you help me with this problem?
from react-native-background-geolocation.
See api docs Config.enableHeadless.
Your JavaScript App no longer exists (including event handlers such as .onLocation) when an Android app is terminated.
from react-native-background-geolocation.
Ok Chris, so this is the only thing I need to do on Android, ok? Is it necessary to do something for iOS as well or does iOS not have this same behavior?
from react-native-background-geolocation.
Did you read the docs for Config.enableHeadless?
from react-native-background-geolocation.
Also carefully read the api docs Config.stopOnTerminate.
from react-native-background-geolocation.
Hi Chris, I made a lot of progress in testing with your tips, but I have a few more questions:
1 - To use preventSuspend, is it mandatory to implement the Heartbeat event?
2 - Is there any configuration so that the location search only starts after BackgroundGeolocation.start()? Because I noticed that sometimes the plugin starts right after ready().
3 - getCurrentPosition returns the current position if I am in a Moving state and the last known position when I am in a stationary state? Any settings to return the most accurate position possible?
4 - How do I know if users have granted the necessary permissions for the plugin to fetch the location?
Thanks!!!
from react-native-background-geolocation.
Related Issues (20)
- Question about preventSuspend HOT 5
- Basic Doubts HOT 6
- Expo integration HOT 6
- Post Payload Optimization HOT 2
- Permissions in Background Tracking HOT 5
- Start Tracking on Closed Application HOT 8
- App Hanging -[TSLocationManager queue:type:] HOT 17
- Permissions
- StopTimeout not Working HOT 13
- Background Location not detecting on few devices like Oneplus , Apple Iphone 15 pro HOT 3
- Background Location not detecting on few devices like Oneplus , Apple Iphone 15 pro HOT 1
- Background Location Stop Detecting Very Late After Stopped HOT 1
- Background Location Stop Detecting Very Late After Stopped HOT 4
- java.lang.IncompatibleClassChangeError upon update from Expo SDK 49 to 51 HOT 1
- The operation couldn’t be completed. Background procssing task was not registered in AppDelegate didFinishLaunchingWithOptions. See iOS Setup Guide. HOT 1
- Realtime Database Firebase HOT 10
- Strange background location indicator - can't turn off HOT 4
- onEnabled and onGeofence not triggering on production but does work on development HOT 2
- Schedule is not working as expected in IOS HOT 11
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react-native-background-geolocation.