Giter Club home page Giter Club logo

Comments (12)

christocracy avatar christocracy commented on July 21, 2024

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.

souzadeveloper avatar souzadeveloper commented on July 21, 2024

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

  1. 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.

christocracy avatar christocracy commented on July 21, 2024

The plug-in is not involved with React State.

from react-native-background-geolocation.

souzadeveloper avatar souzadeveloper commented on July 21, 2024

Hi Chris, I didn't understand your answer. Could you explain better?

from react-native-background-geolocation.

christocracy avatar christocracy commented on July 21, 2024

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.

souzadeveloper avatar souzadeveloper commented on July 21, 2024

Ok Chris

from react-native-background-geolocation.

souzadeveloper avatar souzadeveloper commented on July 21, 2024

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.

christocracy avatar christocracy commented on July 21, 2024

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.

souzadeveloper avatar souzadeveloper commented on July 21, 2024

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.

christocracy avatar christocracy commented on July 21, 2024

Did you read the docs for Config.enableHeadless?

from react-native-background-geolocation.

christocracy avatar christocracy commented on July 21, 2024

Also carefully read the api docs Config.stopOnTerminate.

from react-native-background-geolocation.

souzadeveloper avatar souzadeveloper commented on July 21, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.