gdelataillade / alarm

A Flutter plugin to easily manage alarms on iOS and Android
https://pub.dev/packages/alarm
MIT License
132 stars 86 forks source link

[Alarm] Notification with id 1 canceled #89

Closed robertnicjoo closed 11 months ago

robertnicjoo commented 1 year ago

Alarm plugin version ^1.2.2

Describe the bug when I open the app it schedule next alarm then automatically cancel it! I have no stop or stopAll call anywhere in my code yet it does it by itself.

To Reproduce Steps to reproduce the behavior:

  1. open app
  2. schedule alarm by api data
  3. gets cancelled automatically!

Expected behavior

  1. open app.
  2. schedule alarm by api data

Screenshots ~If applicable, add screenshots to help explain your problem.~

Device info Provide device info (RealMe, Infinix) Android 12 , Android 13

Additional context

W/AlarmService(  871): Attempted to start a duplicate background isolate. Returning...
I/flutter (  871): [Alarm] Notification with id 1 canceled
I/flutter (  871): [Alarm] NotificationOnKillService stopped with success
I/flutter (  871): [Alarm] Notification with id 1 scheduled successfuly at 2023-09-12 06:01:00.000Z (GMT - Zulu time)
I/flutter (  871): [Alarm] Alarm with id 1 scheduled successfully at 2023-09-12 13:01:00.000
I/flutter (  871): [Alarm] Notification with id 4 canceled
I/flutter (  871): [Alarm] NotificationOnKillService stopped with success
I/flutter (  871): [Alarm] Notification with id 4 scheduled successfuly at 2023-09-12 08:04:00.000Z (GMT - Zulu time)
I/flutter (  871): [Alarm] Alarm with id 4 scheduled successfully at 2023-09-12 15:04:00.000
I/flutter (  871): [Alarm] Notification with id 1 canceled
I/flutter (  871): [Alarm] NotificationOnKillService stopped with success
I/flutter (  871): [Alarm] Notification with id 1 scheduled successfuly at 2023-09-12 06:01:00.000Z (GMT - Zulu time)
I/flutter (  871): [Alarm] Alarm with id 1 scheduled successfully at 2023-09-12 13:01:00.000
I/flutter (  871): alarm1::: AlarmSettings: {id: 1, dateTime: 2023-09-12 13:01:00.000, assetAudioPath: assets/audio/abc.mp3, loopAudio: false, vibrate: true, volumeMax: false, fadeDuration: 3.0, notificationTitle: abc, notificationBody: At 13:01, enableNotificationOnKill: true, stopOnNotificationOpen: true}
I/flutter (  871): [Alarm] Notification with id 1 canceled
I/flutter (  871): [Alarm] NotificationOnKillService stopped with success
I/flutter (  871): [Alarm] Notification with id 1 scheduled successfuly at 2023-09-12 06:01:00.000Z (GMT - Zulu time)
I/flutter (  871): [Alarm] Alarm with id 1 scheduled successfully at 2023-09-12 13:01:00.000
I/flutter (  871): alarm1::: AlarmSettings: {id: 4, dateTime: 2023-09-12 15:04:00.000, assetAudioPath: assets/audio/abc.mp3, loopAudio: false, vibrate: true, volumeMax: false, fadeDuration: 3.0, notificationTitle: abc, notificationBody: At 15:04, enableNotificationOnKill: true, stopOnNotificationOpen: true}

Here is my code

main.dart


int alarmId = 1;

@pragma('vm:entry-point')
void NotifiBg(DateTime targetTime, String nextNameOnly) async {
  goAlarm(targetTime, nextNameOnly);
}

goAlarm(targetTime, nextNameOnly) async {
  await Alarm.init();

  String formattedDate = DateFormat('HH:mm').format(targetTime);

  final alarmSettings = AlarmSettings(
    id: alarmId,
    dateTime: targetTime,
    assetAudioPath: 'assets/audio/abc.mp3',
    loopAudio: false,
    vibrate: true,
    volumeMax: false,
    fadeDuration: 3.0,
    notificationTitle: 'abc $nextNameOnly',
    notificationBody: 'At $formattedDate',
    enableNotificationOnKill: true,
    stopOnNotificationOpen: true,
  );
  // await Alarm.setNotificationOnAppKillContent("abc $nextNameOnly", "At $formattedDate");
  alarmId = alarmId +1;

  // getting logcat info
  for (final alarm in Alarm.getAlarms()) {
    final now = DateTime.now();
    if (targetTime.isAfter(now)) {
      await Alarm.set(alarmSettings: alarmSettings);
      print('alarm1::: $alarm');
    } else {
      print('alarm2::: $alarm');
    }
  }
}

other_file.dart

// calling background process...
NotifiBg(timeDifference, nextNameOnly);
gdelataillade commented 1 year ago

Hi @robertnicjoo

Are you sure you alarms do not ring ?

What I do when you open your app is that I stop but then I rescheduled all the alarms to make sure they are all perfectly set. It's what I see in your logs: alarms are stopped but rescheduled instantly.

Do you have any other question ?

robertnicjoo commented 1 year ago

@gdelataillade Hi,

let me explain it a bit more to make it clear:

E.g: I set alarm for 13:01 at 12:40 this alarm gets id 1

now when I rebuild (re run) my app this alarm id=1, at=13:01 says canceled and it makes another alarm for 15:45 with id 4 for instance.

The issue here is this:

I am at 12:40 doesn't matter if i rebuild or reopen my app it should not cancel my alarm for 13:01 cause we have not hit that time yet.

Hope i could make it clear.

gdelataillade commented 1 year ago

@robertnicjoo This looks really weird but OK I'll take a look at it when I'll find the time.

In the meantime, could you please provide more examples with logs of your issue ? This way I will have more resources to find the issue. Thank you in advance !

gdelataillade commented 1 year ago

Hi @robertnicjoo

Do you still have the issue ?

robertnicjoo commented 1 year ago

Hi,

Mentioned issue still exist yes. But I had to switch to alternative plugin so I didn't spend more time on this.

Maybe you can fix it for next time/other users.

gdelataillade commented 1 year ago

It's weird, nobody else is mentioning this issue.

I'm working on a big refactoring of the plugin. I'll get rid of all the dependencies and do everything natively (including notifications). I hope it will fix your issue. I'll keep you updated here when I release it.

robertnicjoo commented 1 year ago

Appreciate it.

gdelataillade commented 11 months ago

Hi @robertnicjoo

I just released version 3.0.0, does it fix your issue ?

robertnicjoo commented 11 months ago

@gdelataillade Hi,

I've made new app and tried your new version. I've found couple bugs (I guess)

  1. while alarm rings, notifications won't show (this is for both foreground and background states of app cycle)
  2. terminated app won't even play the alarm let alone showing the notification

here is my sample code for you to help you with timing:

just make new app and replace this with your main.dart file

import 'package:alarm/alarm.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Alarm.init(showDebugLogs: true);
  runApp(const MyApp());
}

setAlarmTime() async {
  DateTime currentDateTime = DateTime.now();
  int myId = DateTime.now().microsecondsSinceEpoch % 1000000;

  final alarmSettings = AlarmSettings(
    id: myId++,
    dateTime: currentDateTime.add(const Duration(seconds: 5)),
    assetAudioPath: 'assets/alarm.mp3',
    loopAudio: false,
    vibrate: true,
    volume: 1,
    fadeDuration: 3.0,
    notificationTitle: 'This is the title',
    notificationBody: 'This is the body',
    enableNotificationOnKill: false,
  );
  await Alarm.set(alarmSettings: alarmSettings);

  for (final alarm in Alarm.getAlarms()) {
    debugPrint('alarm1::: $alarm');
  }
}

setKillAlarm() async {
  DateTime currentDateTime = DateTime.now();
  int myId = DateTime.now().microsecondsSinceEpoch % 1000000;

  final alarmSettings = AlarmSettings(
    id: myId++,
    dateTime: currentDateTime.add(const Duration(seconds: 15)),
    assetAudioPath: 'assets/alarm.mp3',
    loopAudio: false,
    vibrate: true,
    volume: 1,
    fadeDuration: 3.0,
    notificationTitle: 'This is the title',
    notificationBody: 'This is the body',
    enableNotificationOnKill: true,
  );
  await Alarm.set(alarmSettings: alarmSettings);
  await Alarm.setNotificationOnAppKillContent('kill title', 'kill body');

  for (final alarm in Alarm.getAlarms()) {
    debugPrint('alarm1::: $alarm');
  }
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
  }

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('Alarm'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
                onPressed: () {
                  setAlarmTime();
                },
                child: const Text('Set Alarm for 5 seconds from now'),
            ),
            ElevatedButton(
                onPressed: () {
                  setKillAlarm().then((v) => SystemNavigator.pop());
                },
                child: const Text('Set Kill Alarm for 15 seconds from now'),
            ),
          ],
        ),
      ),
    );
  }
}

PS: remember there is no terminate function in android. It just put app in background that's why I set it to 15 seconds so you can have enough time to terminate app manually :wink:

gdelataillade commented 11 months ago

Hi @robertnicjoo

Thanks for your feedback. In 3.0.0, installation steps were updated. Did you follow them ? There are very important and may fix your issues. You can find them in the plugin's README.

hoangan commented 11 months ago

Hi @gdelataillade

I've got the similar issue, even with id != 1. Here the debug log:

flutter: [Alarm] Alarm with id 324800995 scheduled successfully at 2023-12-20 22:51:27.212613 flutter: current time is 2023-12-20 22:51:09.392854

flutter: [Alarm] Alarm with id 808076005 not found.

flutter: [Alarm] Alarm with id 324800995 stopped

flutter: [Alarm] Alarm with id 808076005 scheduled successfully at 2023-12-20 22:51:57.394282 flutter: current time is 2023-12-20 22:51:14.799427

hoangan commented 11 months ago

Look like if the duration between 2 alarms is short (e.g.: 30s or less as above), they're more likely got cancelled unexpectedly.

gdelataillade commented 11 months ago

@hoangan

Thanks for your feedback. I'll check the codebase to see what I could fix. In the meantime if you find more conclusions that could help, I'll be grateful.

robertnicjoo commented 11 months ago

Hi @robertnicjoo

Thanks for your feedback. In 3.0.0, installation steps were updated. Did you follow them ? There are very important and may fix your issues. You can find them in the plugin's README.

Yes I did here also is recording for you. (no notification)

https://github.com/gdelataillade/alarm/assets/8672823/0e2988df-adc8-4ab9-8ffa-5c5cfb8f38ed

hoangan commented 11 months ago

@hoangan

Thanks for your feedback. I'll check the codebase to see what I could fix. In the meantime if you find more conclusions that could help, I'll be grateful.

@gdelataillade

Seem that the safe minimum duration between 2 alarms is 1 mins, lesser than that, the previous sometimes got cancelled unexpectedly. Also, I noticed in the README you wrote:

To avoid unexpected behaviors, if you set an alarm for the same time as an existing one, the new alarm will replace the existing one.

May be there's a bug somewhere here, where you treat the time similarity as down to minute, not as second.

gdelataillade commented 11 months ago

Hi @hoangan

You are totally right. I override an alarm with the new one if they have the same day, hour and minute.

I'll change this and override an alarm only if they have same second too. What do you think ?

hoangan commented 11 months ago

Hi @hoangan

You are totally right. I override an alarm with the new one if they have the same day, hour and minute.

I'll change this and override an alarm only if they have same second too. What do you think ?

@gdelataillade That would be great. Thanks.

gdelataillade commented 11 months ago

Hey @hoangan

I just released the fix in version 3.0.1.

Please let me know if it fixes your issue.

hoangan commented 11 months ago

@gdelataillade It works, like a charm, awesome! Thank you :D

gdelataillade commented 11 months ago

Awesome. I'm closing this issue then. Feel free to reopen if needed.