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

Flutter Background Services onBackground Mode not working it's perfectly working on Simulator? #503

Open
rahulinfibrain opened this issue Jan 31, 2025 · 0 comments

Comments

@rahulinfibrain
Copy link

Hello

This is our Background code Service code.
IOS Simulator Background Service Timer. periodic working perfectly
but Real Device iPhone 7 can not support in release and debug mode in background please suggestion how to resolved this issue

AudioServices.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;
}
}

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 = "dev.flutter.background.refresh"
// 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)

}
}

Info.plist
BGTaskSchedulerPermittedIdentifiers

audioTask
dev.flutter.background.refresh

UIBackgroundModes

audio
fetch
processing

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

1 participant