Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Background Task -- in iOS not running when the app is minimised #501

Open
maheswarsiva opened this issue Jan 21, 2025 · 1 comment
Open

Comments

@maheswarsiva
Copy link

Hi,

I am using this package for iOS background task for getting the location continuously using a Timer.periodic, but work's well in debug mode, even when I minimise the app or when the app is in foreground, but in release mode, It only works well when the app is in the foreground, completely not working when it is in the background (minimised), need solution ASAP

@rahulinfibrain
Copy link

I have the same issue.
I have Timer.periodic play sound

Info.plist

BGTaskSchedulerPermittedIdentifiers

audioTask
be.tramckrijte.workmanagerExample.iOSBackgroundAppRefresh
dev.flutter.background.refresh

AppDelegate.swift
import UIKit
import Flutter
import UserNotifications
import alarm
import flutter_background_service_ios
//import workmanager

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
SwiftFlutterBackgroundServicePlugin.taskIdentifier = "id.flutter.flutter_background_service.BackgroundService"
// WorkmanagerPlugin.setPluginRegistrantCallback { (registry) in
// GeneratedPluginRegistrant.register(with: registry)
// }
// WorkmanagerPlugin.registerPeriodicTask(withIdentifier: "com.therapo.audioTask", frequency: NSNumber(value: 1))
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
}
SwiftAlarmPlugin.registerBackgroundTasks()

GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)

}
}

Audio.dart
class AudioServices {
AudioServices();

Future initializeService() async {
final service = FlutterBackgroundService();

await service.configure(
  androidConfiguration: AndroidConfiguration(
    onStart: onStartTime,
    autoStart: false, // Set to false initially; start manually via button
    isForegroundMode: true,
    initialNotificationTitle: 'Therapon',
    initialNotificationContent: 'Chime sound enable',
    foregroundServiceTypes: [AndroidForegroundType.mediaPlayback]
  ),
  iosConfiguration: IosConfiguration(
    onForeground: onStartTime,
    autoStart: false,
    onBackground: onIosBackground,
  ),
);

}

Future startService() async {
final service = FlutterBackgroundService();
await service.startService();
}

Future stopService() async {
final service = FlutterBackgroundService();
if (await service.isRunning()) {
service.invoke('stop');
AppGlobal.printLog("Services Stop");
}
}

@pragma('vm:entry-point')
static Future onStartTime(ServiceInstance service) async {
Timer? timer; // Declare a timer reference
if (service is AndroidServiceInstance) {
service.setAsForegroundService();
}
timer = Timer.periodic(const Duration(minutes: 1), (timer) async {
AppGlobal.printLog("Sound Timer : ${timer.tick}");
if (service is AndroidServiceInstance && !(await service.isForegroundService())) {
timer.cancel();
AppGlobal.printLog("Services STOP and Timer Cancel return here");
return;
}

  final now = DateTime.now();
  String fromDate = "";
  String toDate ="";
  fromDate = await SharedPref.readPreferenceValue(fromDateStore, PrefEnum.STRING) ?? '';
  toDate = await SharedPref.readPreferenceValue(toDateStore, PrefEnum.STRING) ?? '';
  bool soundRepeatCountStr = await SharedPref.readPreferenceValue(isMultipleTime, PrefEnum.BOOL) ?? false; // Default to 1 repeat

  int soundRepeatCount = soundRepeatCountStr?2:1; // Fallback to 1 if parsing fails

  AppGlobal.printLog("Form Time : ${fromDate}");
  AppGlobal.printLog("To Time : ${toDate}");
  AppGlobal.printLog("Current Time : ${now.hour}:${now.minute}");
  if(fromDate.isNotEmpty && toDate.isNotEmpty){
    final startTime = DateTime(now.year, now.month, now.day, int.parse(fromDate.toString().split(":")[0]),  int.parse(fromDate.toString().split(":")[1])); // 9:00 AM
    final endTime = DateTime(now.year, now.month, now.day,  int.parse(toDate.toString().split(":")[0]), int.parse(toDate.toString().split(":")[1]));  // 9:00 PM
    // Check if the current time is outside the 9:00 AM to 9:00 PM range
    if (now.isBefore(endTime) && now.isAfter(startTime)) {
      AppGlobal.printLog("No sound played.");
    }
    else {
      AppGlobal.printLog("Playing sound");
      final player = AudioPlayer();
      for(int i=0; i<soundRepeatCount; i++){
        try {
          await player.play(
            AssetSource('animation/sound.mp3'),
            volume: 1.0,
            mode: PlayerMode.lowLatency,
          );
          await Future.delayed(const Duration(seconds: 5)); // Wait for 5 seconds
          await player.stop();
        } catch (e) {
          print('Error playing sound: $e');
        }
      }
      await player.dispose();
    }
  }
  else{
    AppGlobal.printLog("Timer Can empty.");
  }

});

// Listen for the stop signal from the service
service.on('stop').listen((event) {
  if (timer != null) {
    timer.cancel();
    AppGlobal.printLog("Timer canceled on service stop");
  }
  service.stopSelf(); // Stop the service
});

}

@pragma('vm:entry-point')
Future onIosBackground(ServiceInstance service) async {
WidgetsFlutterBinding.ensureInitialized();
DartPluginRegistrant.ensureInitialized();
AppGlobal.printLog("App Background Mode.");
return true;
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants