1

我正在尝试获取某个特定时间的位置数据。每次我们想要获取位置数据时,我们都会向我们的应用程序发送一个静默通知。当应用程序看到静默通知时,它会尝试获取数据并上传回服务器。当应用程序在前台运行时,一切正常,但是当我关闭应用程序并从后台清除时,警报管理器不会被触发来获取和保存位置。

_firebaseMessaging.configure(
      onMessage: (
        Map<String, dynamic> message,
      ) async {
        final Map data =
            message.containsKey('data') ? message['data'] as Map : null;

        if (data?.isEmpty ?? false) {
          _handleNotification(message);
        } else {
          _handleSilentEvent(message); // This method will be called when server will make call to fetch location data
        }
      },
      onResume: (Map<String, dynamic> message) async {},
      onLaunch: (Map<String, dynamic> message) async {},
      onBackgroundMessage: _handleSilentEvent,
    );
Future<dynamic> _handleSilentEvent(
  final Map<String, dynamic> message,
) async {
  final Map data = message.containsKey('data') ? message['data'] as Map : null;

  if (data?.isNotEmpty ?? false) {
    if (data.containsKey('getLocation')) {
      await LocationService.triggerServiceToGetAndSaveLocation();
    } else {
      _handleWebEngage(data);
    }
  }
}

abstract class LocationService {
  static const int _alarmManagerId = 1001;

  static final ILocationFacade _locationFacade = getIt<ILocationFacade>();

  LocationService._();

  static Future<void> triggerServiceToGetAndSaveLocation() async {
    AndroidAlarmManager.oneShotAt(
      DateTime.now(),
      _alarmManagerId,
      LocationService._fetchAndSaveLocation,
      wakeup: true,
      exact: true,
    );
  }

  static Future<void> _fetchAndSaveLocation() async {
    final position = await _getCurrentLocation();
    final capturedAt = DateTime.now().millisecondsSinceEpoch.toString();
    final gpsEnabled = await Geolocator.isLocationServiceEnabled();
    final LocationInfo locationInfo = LocationInfo(
      lat: position.latitude,
      lng: position.longitude,
      capturedAt: capturedAt,
      gpsEnabled: gpsEnabled,
    );

    print(
        'onMessage:: Lat: ${position.latitude} Long: ${position.longitude} capturedAt: $capturedAt gpsEnabled: $gpsEnabled'); // This print is getting called when app is in foreground,  when i kill the app this print is not event getting called.

    // await _locationFacade.saveLocationInfo(locationInfo);
  }

  static Future<Position> _getCurrentLocation() async {
    final _gpsServiceEnabled = await Geolocator.isLocationServiceEnabled();

    if (_gpsServiceEnabled) {
      return Geolocator.getCurrentPosition();
    }
    return Geolocator.getLastKnownPosition();
  }
}

有人能指出我在哪里犯错吗?

4

0 回答 0