transistorsoft / flutter_background_geolocation

Sophisticated, battery-conscious background-geolocation & geofencing with motion-detection
https://www.transistorsoft.com/shop/products/flutter-background-geolocation
Other
652 stars 240 forks source link

The extras object arrives empty in backend #1384

Closed omejiasq closed 2 days ago

omejiasq commented 3 days ago

Your Environment

Expected Behavior

In the backend, the extra object data should also arrive

Actual Behavior

The extras item is arriving empty

Steps to Reproduce

  1. Extras object: extras: { //"imei": imei, "userId": userId, "smartphone_blocked": _smartphoneBlocked , // Convertir a '1' o '0' "tipos_viajes": tipos_viajes, "company" : company, "ayuda" : ayuda, //"token" : token },
  2. What the onLocation event shows when it prints output: [location] - [Location {odometer: 0, activity: {confidence: 100, type: still}, extras: {help: 0, smartphone_blocked: 0, trip_types: Automatic, company: 5d7b02e62d854d2da428ca0e, userId: 5d7b033e2d854d2da428ca0f}, event: motionchange, battery: {level: 0.26, is_charging: true}, uuid: b15b77ba-2cc8-4b39-957f-e10b8b20b1a9, age: 16582, coords: {altitude: 2579.3, heading: 171.52, latitude: 4.7535074, accuracy: 9.35, heading_accuracy: 45, altitude_accuracy: 1.49, speed_accuracy: 1.5, speed: 1.02, age: 16640, longitude: -74.0995061, ellipsoidal_altitude: 2579.3}, is_moving: false, timestamp: 2024-11-26T05:32:18.893Z}]
  3. How the object arrives at the backend: {"location":{"event":"motionchange","is_moving":false,"uuid":"15ae82f8-2547-43d6-a789-6107669e2348","timestamp":"2024-11- 26T05:29:50.385Z","age":93,"odometer":0,"coords":{"latitude":4.7535831,"longitude":-74.0995261,"accuracy":11.59,"speed":- 1,"speed_accuracy":1.5,"heading":-1,"heading_accuracy":45,"altitude":2579.5,"ellipsoidal_altitude":2579.5,"altitude_accur acy":1.53,"age":96},"activity":{"type":"still","confidence":100},"battery":{"is_charging":true,"level":0.26}, "extras":{}}}

Context

  1. Debug logs

import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_background_geolocation/flutter_background_geolocation.dart' as bg;
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:tracking_itf/api.dart';

class LocationService {
  static const platform = MethodChannel('co.itfusion.protegos/screen_state');
  static String _smartphoneBlocked = '0';

  static Future<void> initPlatformState(BuildContext context) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? userId = prefs.getString("userId");

    String? company = prefs.getString("company");

    if (userId == null) {
      Navigator.pushNamed(context, "/login");
      return;
    }

    //checkScreenLocked();

    bg.BackgroundGeolocation.onLocation(_onLocation, _onLocationError);
    bg.BackgroundGeolocation.onMotionChange(_onMotionChange);
    bg.BackgroundGeolocation.onActivityChange(_onActivityChange);
    bg.BackgroundGeolocation.onProviderChange(_onProviderChange);
    bg.BackgroundGeolocation.onConnectivityChange(_onConnectivityChange);
    bg.BackgroundGeolocation.onHttp(_onHttp);

    bg.BackgroundGeolocation.ready(bg.Config(
      reset: true,
      debug: true,
      logLevel: bg.Config.LOG_LEVEL_VERBOSE,
      desiredAccuracy: bg.Config.DESIRED_ACCURACY_HIGH,
      distanceFilter: 10,
      backgroundPermissionRationale: bg.PermissionRationale(
        title: "Allow {applicationName} to access this device's location even when the app is closed or not in use.",
        message: "This app collects location data to enable recording your trips to work and calculate distance-travelled.",
        positiveAction: 'Change to "{backgroundPermissionOptionLabel}"',
        negativeAction: 'Cancel'
      ),
      url: API_URL + "device/locations2",
            extras: {
              //"imei": imei,
              "userId": userId,
              "smartphone_blocked": 0 , // Convertir a '1' o '0'
              "tipos_viajes": 'Automatic',
              "company" : company,
              "ayuda" : '0',
              //"token" : token
      },   
      stopOnTerminate: false,
      startOnBoot: true,
      enableHeadless: true,
    )).then((bg.State state) {
      print("[ready] ${state.toMap()}");
    }).catchError((error) {
      print('[ready] ERROR: $error');
    });
  }

  static Future<void> checkScreenLocked() async {
    try {
      final bool result = await platform.invokeMethod('isScreenLocked');
      _smartphoneBlocked = result ? '1' : '0';
      print(result ? 'Telefono bloqueado' : 'Telefono desbloqueado');
    } on PlatformException catch (e) {
      print("Failed to get screen lock state: '${e.message}'.");
    }
  }

  static void _onLocation(bg.Location location) async {
    print('[location] - $location');

    //bool smartphoneBlocked = await isSmartphoneBlocked();
    //_smartphoneBlocked = smartphoneBlocked ? '1' : '0';

    // Actualiza el estado de la UI si es necesario
  }

  static void _onLocationError(bg.LocationError error) {
    print('[location] ERROR - $error');
  }

  static void _onMotionChange(bg.Location location) async {
    //bool smartphoneBlocked = await isSmartphoneBlocked();
    //_smartphoneBlocked = smartphoneBlocked ? '1' : '0';
    print('[motionchange] - $location');
  }

  static void _onActivityChange(bg.ActivityChangeEvent event) {
    print('[activitychange] - $event');
  }

  static void _onHttp(bg.HttpEvent event) async {
    //bool smartphoneBlocked = await isSmartphoneBlocked();
    //_smartphoneBlocked = smartphoneBlocked ? '1' : '0';
    print('[${bg.Event.HTTP}] - $event');
  }

  static void _onProviderChange(bg.ProviderChangeEvent event) {
    print('$event');
  }

  static void _onConnectivityChange(bg.ConnectivityChangeEvent event) {
    print('$event');
  }

  static Future<bool> isSmartphoneBlocked() async {
    try {
      final bool result = await platform.invokeMethod('isScreenLocked');
      return result;
    } on PlatformException catch (e) {
      print("Failed to get screen lock state: '${e.message}'.");
      return false;
    }
  }
}

christocracy commented 3 days ago

You likely have other locations in the plug-ins SQLite db that were recorded before you introduced these extras.

Call .count to learn how many records there are. Call .locations to retrieve and analyze them. Call .destroyLocations to get rid of them.

omejiasq commented 2 days ago

thanks! I did what you told me but it wasn't that. I had a flutter app built a couple of years ago but it was very outdated and after updating flutter and the latest version of your plugin some problem occurred, for that reason I did many tests and changes to the old app and nothing solved the problem until I created a new app from scratch and imported/adjusted all the code from the previous app and then this problem of not sending the extras object worked, it was something very strange.