0

I have a small issue with Scheduled Notification on Android - Xamarin Forms Project. I want to schedule a daily notification at 17:00. It works ok on simulator but when I deploy it on a Samsung S7 Edge - Android 8.0, it notifies me at 17:00 and after I open the notification, it will keep notify every minute or so.

Here is my code, MainActivity.cs:

[Activity(Label = "SpiritMobile", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        static readonly string CHANNEL_ID = "location_notification";
        internal static readonly string COUNT_KEY = "count";

        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

            LoadApplication(new App());

            CreateNotificationChannel();

            Intent alarmIntent = new Intent(this, typeof(AlarmReceiver));
            PendingIntent pending = PendingIntent.GetBroadcast(this, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
            AlarmManager alarmManager = GetSystemService(AlarmService).JavaCast<AlarmManager>();

            var calendar = Calendar.Instance;
            calendar.TimeZone = Java.Util.TimeZone.GetTimeZone("Europe/Bucharest");
            calendar.Set(CalendarField.HourOfDay, 17);
            calendar.Set(CalendarField.Minute, 00);

            alarmManager.SetRepeating(AlarmType.RtcWakeup, calendar.TimeInMillis, AlarmManager.IntervalDay, pending);
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            ServicePointManager.ServerCertificateValidationCallback += (o, cert, chain, errors) => true;

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }

        void CreateNotificationChannel()
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                return;
            }

            var channel = new NotificationChannel(CHANNEL_ID, "reminders", NotificationImportance.Default)
            {
                Description = "reminder's channel"
            };

            var notificationManager = (NotificationManager)GetSystemService(NotificationService);
            notificationManager.CreateNotificationChannel(channel);
        }
    }

Then I have AlarmReceiver.cs:

[BroadcastReceiver]
    public class AlarmReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            var message = "Don't forget to submit your daily rates.";

            Intent backIntent = new Intent(context, typeof(MainActivity));
            backIntent.SetFlags(ActivityFlags.NewTask);

            var resultIntent = new Intent(context, typeof(MainActivity));

            PendingIntent pending = PendingIntent.GetActivities(context, 0,
                new Intent[] { backIntent, resultIntent },
                PendingIntentFlags.OneShot);

            var builder = new NotificationCompat.Builder(context, "location_notification")
                 .SetAutoCancel(true)
                 .SetContentTitle("Submit your daily feeling!")
                 .SetContentText(message)
                 .SetSmallIcon(Resource.Drawable.icon);

            builder.SetContentIntent(pending);
            var notificationManager = NotificationManagerCompat.From(context);
            notificationManager.Notify(1000, builder.Build());
        }
    }

Could you please tell me what is wrong here? What can be the cause of this?

Cfun
  • 8,442
  • 4
  • 30
  • 62
codirxd
  • 37
  • 1
  • 7
  • A tick is 100nsec in c# DateTime on windows. In Android it is 1nsec. See : https://developer.android.com/reference/java/time/Clock – jdweng Oct 02 '20 at 15:16
  • Ok, but how this helps me? I get the notification on Android at correct time, but the problem is that another notifications are displayed every minute after the first one. – codirxd Oct 02 '20 at 15:38
  • There are 3600 minutes in a day. So it is notifying you 100 times sooner. So it is notifying you every 36 minutes instead of once a day. – jdweng Oct 02 '20 at 17:11
  • @ClaudiuL93 According to the code you provided, it seems you have already set the alarm. Have you test on another device? Does this issue only occur on Samsung S7 Edge? – Wendy Zang - MSFT Oct 28 '20 at 06:43

1 Answers1

0

You are setting your repeating alarm in OnCreate method of the Activity. So every time app is launched, a new alarm is registered with the AlarmManager. As it is repeating alarm you need to set it only once.

It can be achieved by checking if your alarm is already set.

Rajesh Sonar
  • 279
  • 3
  • 11
  • Yes, this this the cause of my issue... But I can't manage to check if the alarm is already set.. – codirxd Oct 03 '20 at 15:44