react-native-background-geolocation: Cannot read property 'ready' of null 

@christocracy

Your Environment

•	Plugin version: react-native-background-geolocation : 4.14.1 , react-native-background-fetch : 4.2.1
•	Platform: Android
•	OS version: Android  12
•	Device manufacturer / model: simulator
•	React Native version (react-native -v): 0.68.2
•	Plugin config : build.gradle and app/bulid.gradle
 this.subscriptions.push(BackgroundGeolocation.onLocation(async (location) => {

            try {
              let oldLatLong = await AsyncStorage.getItem("LOCATION_LAT");
              // let odometer = await BackgroundGeolocation.getOdometer();
              console.log("LOCA ", oldLatLong);
              let meterDistance = 0;
      
              if (oldLatLong && oldLatLong != null) {
      
                oldLatLong = oldLatLong.split('|');
                let oldLat = oldLatLong[0]
                let oldLong = oldLatLong[1]
                let today = moment().format('MM/DD/YYYY');
      
                if (moment(today, 'MM/DD/YYYY').isSame(moment(oldLatLong[2], 'MM/DD/YYYY'), 'day') == true) {
                  const a = { latitude: oldLat, longitude: oldLong }
                  const b = { latitude: location?.coords?.latitude, longitude: location?.coords?.longitude }
                  meterDistance = haversine(a, b);
                }
                else {
                  await AsyncStorage.setItem("LOCATION_LAT", location?.coords?.latitude + '|' + location?.coords?.longitude + '|' + moment().format('MM/DD/YYYY'))
                }
              }
              else {
                await AsyncStorage.setItem("LOCATION_LAT", location?.coords?.latitude + '|' + location?.coords?.longitude + '|' + moment().format('MM/DD/YYYY'))
              }
      
              this.setState({ location: JSON.stringify(location, null, 2) });
      
              const format = 'hh:mm:ss';
              const beforeTime = moment('22:50:00', format);
              const afterTime = moment('24:00:00', format);
              if (moment().isBetween(beforeTime, afterTime)) {
                await AsyncStorage.removeItem("LOCATION_LAT")
                BackgroundGeolocation.stop();
                this.setState({ enabled: 0 })
              }
      
              let callAPI = false;
              if (meterDistance > 49) {
                callAPI = true;
              }
              console.log("meterDistance ", meterDistance);
      
              if (callAPI) {
                console.log("callAPI ", callAPI);
      
                let header = {
                  Accept: "application/json",
                  "Content-Type": "multipart/form-data"
                };
      
                let latilong = location?.coords?.latitude + ',' + location?.coords?.longitude;
      
                let batteryPercentage = location?.battery?.level * 100
                batteryPercentage = batteryPercentage.toString()
      
                let storeLocationData = [{
                  "distance": meterDistance.toString(),
                  "lat_long": latilong,
                  "battery_percentage": batteryPercentage,
                  "location_time": moment().format("DD/MM/YYYY HH:mm:ss"),
                  "fk_user_id": User_Id
                }];
      
                fetch(`not`, {
                  method: "POST",
                  headers: header,
                  body: JSON.stringify(storeLocationData)
                })
                  .then(response => response.json())
                  .then(async responseJson => {
                    this.setState({
                      lastAPI: moment().format("DD/MM/YYYY HH:mm:ss"),
                      meter: meterDistance
                    });
                    await AsyncStorage.setItem("LOCATION_LAT", location?.coords?.latitude + '|' + location?.coords?.longitude + '|' + moment().format('MM/DD/YYYY'))
                    BackgroundGeolocation.resetOdometer().then((location) => {
                      // This is the location where odometer was set at.
                      console.log("[setOdometer] success: ", location);
                    });
      
                  })
                  .catch(error => {
                    console.error(error);
                  });
              }
            } catch (error) {
              console.log("er ", error);
            }
          }))
      
      
          this.subscriptions.push(BackgroundGeolocation.onMotionChange((event) => {
            console.log('[onMotionChange]', event);
          }))
      
          this.subscriptions.push(BackgroundGeolocation.onActivityChange((event) => {
            console.log('[onActivityChange]', event);
          }))
      
          this.subscriptions.push(BackgroundGeolocation.onProviderChange((event) => {
            console.log('[onProviderChange]', event);
          }))
          
          console.log('Background.Ready==>>')
          /// 2. ready the plugin.
          BackgroundGeolocation.ready({
            // Geolocation Config
            desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
            distanceFilter: 50,
            showsBackgroundLocationIndicator: false,
            foregroundService: true,
            enableHeadless: true,
            // Activity Recognition
            stopTimeout: 5,
            maxDaysToPersist: 14,
            //heartbeatInterval: 60,
            locationUpdateInterval: 5000,  // Get a location every 5 seconds
            // Application config
            debug: false, // <-- enable this hear sounds for background-geolocation life-cycle.
            logLevel: BackgroundGeolocation.LOG_LEVEL_ERROR,
            stopOnTerminate: false,   // <-- Allow the background-service to continue tracking when user closes the app.
            startOnBoot: true,        // <-- Auto start tracking when device is powered-up.
            foregroundService: true,
            //   desiredOdometerAccuracy: 10,
})

Expected Behavior

working background location services and track Device

Actual Behavior

Not work it appears an error on console: TypeError: Cannot read property ‘ready’ of null

Steps to Reproduce

Context

trying to tracking device with library

BackgroundGeolocation.ready({ // Geolocation Config desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH, distanceFilter: 50, showsBackgroundLocationIndicator: false, foregroundService: true, enableHeadless: true, // Activity Recognition stopTimeout: 5, maxDaysToPersist: 14, //heartbeatInterval: 60, locationUpdateInterval: 5000, // Get a location every 5 seconds // Application config debug: false, // <-- enable this hear sounds for background-geolocation life-cycle. logLevel: BackgroundGeolocation.LOG_LEVEL_ERROR, stopOnTerminate: false, // <-- Allow the background-service to continue tracking when user closes the app. startOnBoot: true, // <-- Auto start tracking when device is powered-up. foregroundService: true, // desiredOdometerAccuracy: 10, // url: ‘’, // HTTP / SQLite config batchSync: false, // <-- [Default: false] Set true to sync locations to server in a single HTTP request. autoSync: true, // <-- [Default: true] Set true to sync each location to server as it arrives. headers: { // <-- Optional HTTP headers // Accept: “application/json”, // “Content-Type”: “multipart/form-data” },

        // params:
        // {              // <-- Optional HTTP params
        //   "fk_user_id": userid,
        //   "location_time": moment().format("DD/MM/YYYY HH:mm:ss"),
        // }
      }).then(async (state) => {
        this.setState({ enabled: state.enabled });
      });

Debug logs

Logs
PASTE_YOUR_LOGS_HERE

About this issue

  • Original URL
  • State: open
  • Created 9 months ago
  • Comments: 24 (11 by maintainers)

Most upvoted comments

I just did this myself in the SampleApp a few weeks ago.

Use react-native-rename to rename your app as desired.