flutter_background_geolocation
flutter_background_geolocation copied to clipboard
Getting debug sound even in production builds
Your Environment
- Plugin version:
- Platform: iOS or Android
- OS version:
- Device manufacturer / model:
- Flutter info (
flutter doctor
): Doctor summary (to see all details, run flutter doctor -v): [✓] Flutter (Channel stable, 3.13.5, on macOS 13.3.1 22E261 darwin-x64, locale en-IN) [✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0) [✓] Xcode - develop for iOS and macOS (Xcode 14.3.1) [✓] Chrome - develop for the web [✓] Android Studio (version 2022.1) [✓] VS Code (version 1.72.2) [✓] Connected device (3 available) [✓] Network resources
• No issues found!
- Plugin config:
@pragma('vm:entry-point')
void backgroundGeolocationHeadlessTask(bg.HeadlessEvent headlessEvent) async {
switch (headlessEvent.name) {
case bg.Event.BOOT:
bg.State state = await bg.BackgroundGeolocation.state;
print("📬 didDeviceReboot: ${state.didDeviceReboot}");
break;
case bg.Event.TERMINATE:
try {
bg.Location location =
await bg.BackgroundGeolocation.getCurrentPosition(
samples: 1, extras: {"event": "terminate", "headless": true});
print("[getCurrentPosition] Headless: $location");
} catch (e) {
return;
}
break;
// TODO: RECHECK
// case bg.Event.HEARTBEAT:
// break;
// case bg.Event.LOCATION:
// bg.Location location = headlessEvent.event;
// print(location);
// break;
// case bg.Event.MOTIONCHANGE:
// bg.Location location = headlessEvent.event;
// print(location);
// break;
// case bg.Event.GEOFENCE:
// bg.GeofenceEvent geofenceEvent = headlessEvent.event;
// print(geofenceEvent);
// break;
// case bg.Event.GEOFENCESCHANGE:
// bg.GeofencesChangeEvent event = headlessEvent.event;
// print(event);
// break;
// case bg.Event.SCHEDULE:
// bg.State state = headlessEvent.event;
// print(state);
// break;
// case bg.Event.ACTIVITYCHANGE:
// bg.ActivityChangeEvent event = headlessEvent.event;
// print(event);
// break;
// case bg.Event.HTTP:
// bg.HttpEvent event = headlessEvent.event;
// print(event);
// break;
// case bg.Event.POWERSAVECHANGE:
// bool enabled = headlessEvent.event;
// print(enabled);
// break;
// case bg.Event.CONNECTIVITYCHANGE:
// bg.ConnectivityChangeEvent event = headlessEvent.event;
// print(event);
// break;
// case bg.Event.ENABLEDCHANGE:
// bool enabled = headlessEvent.event;
// print(enabled);
// break;
// TODO: RECHECK
case bg.Event.AUTHORIZATION:
bg.AuthorizationEvent event = headlessEvent.event;
print(event);
bg.BackgroundGeolocation.setConfig(bg.Config(
url:
"https://example.com/AddbackgroundLocation",
headers: {"Authorization": "Bearer ${prefs!.getString('token')}"}));
break;
}
}
/// Receive events from BackgroundFetch in Headless state.
@pragma('vm:entry-point')
void backgroundFetchHeadlessTask(HeadlessTask task) async {
String taskId = task.taskId;
// Is this a background_fetch timeout event? If so, simply #finish and bail-out.
if (task.timeout) {
BackgroundFetch.finish(taskId);
return;
}
try {
await bg.BackgroundGeolocation.getCurrentPosition(
samples: 1,
timeout: 30,
extras: {"event": "background-fetch", "headless": true})
.then((v) {})
.onError((e, s) {})
.catchError((e) {});
} catch (error) {
return;
}
BackgroundFetch.finish(taskId);
}
bg.BackgroundGeolocation.ready(bg.Config(
enableHeadless: true,
heartbeatInterval: 60,
url:
"https://example.com/AddbackgroundLocation",
headers: {"Authorization": "Bearer ${prefs!.getString('token')}"},
desiredAccuracy: bg.Config.DESIRED_ACCURACY_HIGH,
distanceFilter: 150,
// scheduleUseAlarmManager: true,
// schedule: ['1-7 21:19-21:20'],
stopOnTerminate: false,
disableElasticity: false,
elasticityMultiplier: 1,
desiredOdometerAccuracy: 100,
maxDaysToPersist: 3,
locationUpdateInterval: 1000,
stopTimeout: 5,
disableMotionActivityUpdates: false,
useSignificantChangesOnly: true, // need to remove in android builds
disableStopDetection: false,
motionTriggerDelay: 0,
autoSync: true,
disableAutoSyncOnCellular: false,
persistMode: 1,
preventSuspend: true,
notificationPriority: 1,
startOnBoot: true,
debug: false,
logLevel: bg.Config.LOG_LEVEL_VERBOSE,
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'),
notificationLargeIcon: "drawable/op_logo",
notificationSmallIcon: "drawable/op_logo",
notification: bg.Notification(
title: 'Day Started - FieldMagna',
text: 'Retail day started',
priority: bg.Config.NOTIFICATION_PRIORITY_HIGH,
sticky: true,
smallIcon:
"drawable/op_logo", // <-- defaults to app icon
largeIcon: "drawable/op_logo",
channelId: 'my_channel_id',
actions: [])));
bg.BackgroundGeolocation.registerHeadlessTask(
backgroundGeolocationHeadlessTask);
BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
runApp(const MyApp());
Expected Behavior
Actual Behavior
Steps to Reproduce
Context
Just created application build in production and it making location sound in background mode
Debug logs
Logs
PASTE_YOUR_LOGS_HERE
You should not be executing BackgroundGeolocation.ready
in your lib/main.dart
. That's supposed to be executed within your App
.
we have already done this bg.BackgroundGeolocation.ready(bg.Config( enableHeadless: true, heartbeatInterval: 60,
Show me your entire lib/main.dart
This is my entire code i am still getting background noise, what is wrong here, please suggest or share the fixed one
import 'dart:async'; import 'dart:developer';
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:get_storage/get_storage.dart'; import 'package:moover_driver2/utils/localisations/custom_widgets.dart'; import 'package:moover_driver2/utils/services/network_services/endpoints.dart'; import 'package:onesignal_flutter/onesignal_flutter.dart'; import 'package:socket_io_client/socket_io_client.dart' as IO; import 'utils/app_pages.dart'; import 'utils/app_routes.dart'; import 'utils/localisations/app_colors.dart'; import 'package:flutter_background_geolocation/flutter_background_geolocation.dart' as bg;
void main() async { WidgetsFlutterBinding.ensureInitialized(); OneSignal.Debug.setLogLevel(OSLogLevel.verbose); OneSignal.initialize("ae590879-074f-4e51-872b-b2c665007075"); OneSignal.Notifications.requestPermission(true);
GetStorage.init();
runApp(const MyApp()); }
void configOneSignal() async { OneSignal.initialize('ae590879-074f-4e51-872b-b2c665007075'); OneSignal.Notifications.addClickListener( (dynamic result) { Get.toNamed(AppRoutes.notification); }, ); }
GetStorage getStorage = GetStorage();
late IO.Socket socket; String? _currentLocation; bool isMoving = false; Timer? locationTimer;
Future
socket.onConnect((_) async {
GetStorage.init();
printData("Connected: ${socket.connected}");
var userId = getStorage.read('id');
var token = getStorage.read('token');
printData("userId:$userId");
printData("token:$token");
if (socket != null && socket.connected) {
// socket.emit('socket_data', locationData);
printData("SOCKET CONNECTED ");
}
});
socket.on('socket_data', (data) {
printData("Received data from server: $data");
});
socket.onConnectError((error) {
printData("ERROR: $error");
});
socket.connect();
} catch (e, st) { print("ERROR: $e"); print("STACKTRACE: $st"); } }
Future
printData('Latitude: $latitude'); printData('Longitude: $longitude');
var locationData = { 'latitude': latitude.toString(), 'longitude': longitude.toString(), 'userId': userId.toString(), };
if (socket != null && socket.connected) { socket.emit('socket_data', locationData); printData("$locationData"); } }
class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key);
@override State<MyApp> createState() => _MyAppState(); }
class _MyAppState extends State<MyApp> { @override void initState() { super.initState(); configOneSignal(); initSocket(); _currentLocation = '';
bg.BackgroundGeolocation.onMotionChange((bg.Location location) {
if (location.isMoving) {
isMoving = true;
if (locationTimer != null && locationTimer!.isActive) {
locationTimer!.cancel();
}
locationTimer = Timer.periodic(const Duration(minutes: 5), (_) {
bg.BackgroundGeolocation.getCurrentPosition(
desiredAccuracy: bg.Config.DESIRED_ACCURACY_HIGH,
persist: true,
samples: 1,
).then((bg.Location location) {
_onLocation(location);
});
});
} else {
isMoving = false;
if (locationTimer != null && locationTimer!.isActive) {
locationTimer!.cancel();
}
locationTimer = Timer.periodic(const Duration(minutes: 5), (_) {
bg.BackgroundGeolocation.getCurrentPosition(
desiredAccuracy: bg.Config.DESIRED_ACCURACY_HIGH,
persist: true,
samples: 1,
).then((bg.Location location) {
_onLocation(location);
});
});
}
});
bg.BackgroundGeolocation.ready(bg.Config(
desiredAccuracy: bg.Config.DESIRED_ACCURACY_HIGH,
stopOnTerminate: false,
disableElasticity: false,
elasticityMultiplier: 1,
desiredOdometerAccuracy: 100,
maxDaysToPersist: 3,
locationUpdateInterval: 1000,
stopTimeout: 5,
disableMotionActivityUpdates: false,
useSignificantChangesOnly: true, // need to remove in android builds
disableStopDetection: false,
motionTriggerDelay: 0,
autoSync: true,
disableAutoSyncOnCellular: false,
persistMode: 1,
preventSuspend: true,
notificationPriority: 1,
startOnBoot: true,
debug: false,
logLevel: bg.Config.LOG_LEVEL_VERBOSE,
notification: bg.Notification(
title: "Moover Driver",
text: "Keep Moover Driver in background",
),
)).then((bg.State state) {
bg.BackgroundGeolocation.start().then((bg.State state) {
printData('[start] success $state');
});
});
}
void _onLocation(bg.Location location) { try { printData('[location] - $location'); String currentLocation = 'Lat: ${location.coords.latitude}, Lng: ${location.coords.longitude}'; setState(() { _currentLocation = currentLocation; });
sendData(
latitude: location.coords.latitude,
longitude: location.coords.longitude,
);
} catch (e, st) {
printData("ERROR : $e");
printData("ST : $st");
}
}
@override Widget build(BuildContext context) { return GetMaterialApp( debugShowCheckedModeBanner: false, title: 'Moover Rider', theme: ThemeData( fontFamily: "VisbyRoundCF", useMaterial3: false, primarySwatch: Colors.deepPurple, inputDecorationTheme: InputDecorationTheme( enabledBorder: OutlineInputBorder( borderSide: BorderSide(width: 1.5, color: Colors.grey.shade500), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(width: 1.5, color: AppColors.primaryVoilet), ), ), ), getPages: AppPages.route, initialRoute: AppPages.initialRoute, ); } }
Learn to syntax highlight code
This issue is stale because it has been open for 30 days with no activity.
This issue was closed because it has been inactive for 14 days since being marked as stale.