stopService method

  1. @override
Future<bool> stopService()
override

Implementation

@override
Future<bool> stopService() async {
  if (!await isRunningService) {
    return true;
  }

  final bool reqResult = await methodChannel.invokeMethod('stopService');
  if (!reqResult) {
    return false;
  }

  final Stopwatch stopwatch = Stopwatch()..start();
  bool stopState = false;
  await Future.doWhile(() async {
    stopState = !await isRunningService;

    // official doc: Once the service has been created, the service must call its startForeground() method within five seconds.
    // ref: https://developer.android.com/guide/components/services#StartingAService
    if (stopState || stopwatch.elapsedMilliseconds > 5 * 1000) {
      return false;
    } else {
      await Future.delayed(const Duration(milliseconds: 100));
      return true;
    }
  });

  return stopState;
}