onStart static method

void onStart(
  1. ServiceInstance service
)

This is the entry point for the background service.

sets the foreground notification title and content. It also listens for the 'stopService' event and stops the service when it is received.

Implementation

@pragma('vm:entry-point')
static void onStart(ServiceInstance service) async {
  final prefs = await SharedPreferences.getInstance();
  final configJson = prefs.getString('bg_service_config');
  Map<String, dynamic> configData = {};

  if (configJson != null) {
    try {
      configData = jsonDecode(configJson);
    } catch (e) {
      if (kDebugMode) {
        print('Error parsing config: $e');
      }
    }
  }

  final title = configData['title'] ?? 'Step Tracker';
  final content =
      configData['content'] ?? 'Tracking your steps in background';

  if (service is AndroidServiceInstance) {
    service.setForegroundNotificationInfo(title: title, content: content);
  }

  // Add step tracking in background
  StreamSubscription<StepCount>? stepSubscription;

  try {
    stepSubscription = Pedometer.stepCountStream.listen((event) {
      // Update shared preferences with latest step count
      prefs.setInt('currentSteps', event.steps);

      // Calculate session steps if initial steps are set
      final initialSteps = prefs.getInt('initialSteps') ?? -1;
      if (initialSteps != -1) {
        final sessionSteps = event.steps - initialSteps;
        prefs.setInt('sessionSteps', sessionSteps);
      }
    });
  } catch (e) {
    debugPrint('Error initializing step tracking in background: $e');
  }

  service.on('stopService').listen((event) {
    stepSubscription?.cancel();
    service.stopSelf();
  });
}