flutter_foreground_task icon indicating copy to clipboard operation
flutter_foreground_task copied to clipboard

Foreground service is active but doesn't run as it's supposed to after upgrading package to ^3.7.3.

Open behradkhadem opened this issue 2 years ago • 0 comments

Hello everyone!

I need to have a socket connection inside my foreground service in order to send location information to the server. And the code worked while I was using version ^3.5.5 but suddenly after I upgraded to version ^3.7.3 (in order to use FlutterForegroundTask.launchApp() method.) foreground service stops sending the location using socket even though it's active! Code below is the Schema of my foreground task.

class UpdateLocationTaskHandler extends TaskHandler {
  SocketConnection socketConnection =
      SocketConnection(); // This is a new instance of socket connection class.


  @override
  Future<void> onStart(DateTime timestamp, SendPort? sendPort) async {
    log('Sendport in onStart before socket Connection in ${sendPort.runtimeType}');
    socketConnection.initializeSocketConnection(sendPort: sendPort);
    // ! These three lines below is the main reason I upgraded version.
    socketConnection.socket.on('new-travel', (data) {
      FlutterForegroundTask.launchApp();
    });
  }

  @override
  void onButtonPressed(String id) {
    // debugPrint(id);
    if (id == 'checkSocket') {
      log('Socket connection status is: ${socketConnection.socket.connected}');
    }
  }

  @override
  Future<void> onEvent(DateTime timestamp, SendPort? sendPort) async {
    log('Event is triggered at ${timestamp.minute}:${timestamp.second}');
    log('Status of socket connection is ${socketConnection.socket.connected}');
    if (socketConnection.socket.connected == false) {
            socketConnection.initializeSocketConnection(sendPort: sendPort);
    }
    if (socketConnection.socket.connected) {
      Position position = await Geolocator.getCurrentPosition(
          desiredAccuracy: LocationAccuracy.bestForNavigation);
      double long = position.longitude;
      double lat = position.latitude;
      final info = UpdateLocationInfo(
          locationLat: lat, longitude: long);
      socketConnection.updateLocation(
        info,
      );
    }
  }

  @override
  Future<void> onDestroy(DateTime timestamp, SendPort? sendPort) async {
    socketConnection.socket.dispose();
  }
}

The weired thing is that log('Status of socket connection is ${socketConnection.socket.connected}') returns true when onEvent gets called but socketConnection.updateLocation(info) doesn't work! What could cause the problem?

Keep up the good work.

behradkhadem avatar Jun 14 '22 05:06 behradkhadem