예제 #1
0
        private void ScheduleCallbackAlarm(ScheduledCallback callback, PendingIntent callbackPendingIntent)
        {
            AlarmManager alarmManager = _service.GetSystemService(global::Android.Content.Context.AlarmService) as AlarmManager;

            // cancel the current alarm for this callback id. this deals with the situations where (1) sensus schedules callbacks
            // and is subsequently restarted, or (2) a probe is restarted after scheduling callbacks (e.g., script runner). in
            // these situations, the originally scheduled callbacks will remain in the alarm manager, and we'll begin piling up
            // additional, duplicate alarms. we need to be careful to avoid duplicate alarms, and this is how we manage it.
            alarmManager.Cancel(callbackPendingIntent);

            long callbackTimeMS = callback.NextExecution.Value.ToJavaCurrentTimeMillis();

            // see the Backwards Compatibility article for more information
#if __ANDROID_23__
            if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                alarmManager.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, callbackTimeMS, callbackPendingIntent);  // API level 23 added "while idle" option, making things even tighter.
            }
            else if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
            {
                alarmManager.SetExact(AlarmType.RtcWakeup, callbackTimeMS, callbackPendingIntent);  // API level 19 differentiated Set (loose) from SetExact (tight)
            }
            else
#endif
            {
                alarmManager.Set(AlarmType.RtcWakeup, callbackTimeMS, callbackPendingIntent);  // API 1-18 treats Set as a tight alarm
            }

            SensusServiceHelper.Get().Logger.Log("Alarm scheduled for callback " + callback.Id + " at " + callback.NextExecution.Value + ".", LoggingLevel.Normal, GetType());
        }
예제 #2
0
        static public void AddAlarmEvent(int seconds = 60)
        {
            DateTime alarmtime = DateTime.Now.AddSeconds(seconds);

            Intent alarmIntent = new Intent(Android.App.Application.Context, typeof(AlarmReceiver));

            PendingIntent pendingIntent = PendingIntent.GetBroadcast(Android.App.Application.Context, AlarmId++, alarmIntent, PendingIntentFlags.UpdateCurrent);
            AlarmManager  alarmManager  = (AlarmManager)Android.App.Application.Context.GetSystemService(Context.AlarmService);

            Java.Util.Calendar calendar = Java.Util.Calendar.Instance;
            calendar.TimeInMillis = Java.Lang.JavaSystem.CurrentTimeMillis();
            calendar.Set(alarmtime.Year, alarmtime.Month - 1, alarmtime.Day, alarmtime.Hour, alarmtime.Minute, alarmtime.Second);

            if (Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.M)
            {
                if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
                {
                    //API 19 이상 API 23미만
                    alarmManager.SetExact(AlarmType.RtcWakeup, calendar.TimeInMillis, pendingIntent);
                }
                else
                {
                    //API 19미만
                    alarmManager.Set(AlarmType.RtcWakeup, calendar.TimeInMillis, pendingIntent);
                }
            }
            else
            {
                //API 23 이상
                alarmManager.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, calendar.TimeInMillis, pendingIntent);
            }
        }
예제 #3
0
        public void SetAlarm(Context Activity, long miliseconds, PendingIntent pendingIntent)
        {
            AlarmManager alarmManager = (AlarmManager)Activity.GetSystemService(Context.AlarmService);

            //Intent intent = new Intent(Activity, typeof(AlarmReceiver));

            //intent.PutExtra("repeat", true);

            //PendingIntent pendingIntent = PendingIntent.GetBroadcast(Activity, /*id de la alarma que sea unico */0, intent, PendingIntentFlags.CancelCurrent);
            //alarmManager.SetInexactRepeating(AlarmType.RtcWakeup, miliseconds, AlarmManager.IntervalDay, pendingIntent);
            //API19 NOt work  https://stackoverflow.com/questions/27806336/alarmmanager-setinexactrepeating-not-working-in-android-4-1-2-works-on-android
            if (Build.VERSION.SdkInt < BuildVersionCodes.Kitkat)
            {
                alarmManager.Set(AlarmType.RtcWakeup, miliseconds, pendingIntent);
            }

            else if (BuildVersionCodes.Kitkat <= Build.VERSION.SdkInt && Build.VERSION.SdkInt < BuildVersionCodes.M)
            {
                alarmManager.SetExact(AlarmType.RtcWakeup, miliseconds, pendingIntent);
            }

            else if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                alarmManager.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, miliseconds, pendingIntent);
            }
        }
예제 #4
0
        public void ScheduleCallbackAlarm(PendingIntent callbackPendingIntent, string callbackId, DateTime callbackTime)
        {
            lock (_callbackIdPendingIntent)
            {
                // update pending intent associated with the callback id. we'll need the updated pending intent if/when
                // we which to unschedule the alarm.
                _callbackIdPendingIntent[callbackId] = callbackPendingIntent;

                AlarmManager alarmManager = _service.GetSystemService(global::Android.Content.Context.AlarmService) as AlarmManager;

                long delayMS        = (long)(callbackTime - DateTime.Now).TotalMilliseconds;
                long callbackTimeMS = Java.Lang.JavaSystem.CurrentTimeMillis() + delayMS;

                // https://github.com/predictive-technology-laboratory/sensus/wiki/Backwards-Compatibility
#if __ANDROID_23__
                if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
                {
                    alarmManager.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, callbackTimeMS, callbackPendingIntent);  // API level 23 added "while idle" option, making things even tighter.
                }
                else if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
                {
                    alarmManager.SetExact(AlarmType.RtcWakeup, callbackTimeMS, callbackPendingIntent);  // API level 19 differentiated Set (loose) from SetExact (tight)
                }
                else
#endif
                {
                    alarmManager.Set(AlarmType.RtcWakeup, callbackTimeMS, callbackPendingIntent);  // API 1-18 treats Set as a tight alarm
                }
            }
        }
예제 #5
0
        private async Task SetAlarm(String name, String dosage, Notification notification, int id, NotificationOccurrence notificationOccurrence, Intent notificationIntent)
        {
            var firingCal = Java.Util.Calendar.Instance;

            firingCal.Set(CalendarField.Year, notificationOccurrence.OccurrenceDateTime.Year);
            firingCal.Set(CalendarField.Month, notificationOccurrence.OccurrenceDateTime.Month - 1);
            firingCal.Set(CalendarField.DayOfMonth, notificationOccurrence.OccurrenceDateTime.Day);
            firingCal.Set(CalendarField.HourOfDay, notificationOccurrence.OccurrenceDateTime.Hour);
            firingCal.Set(CalendarField.Minute, notificationOccurrence.OccurrenceDateTime.Minute);
            firingCal.Set(CalendarField.Second, notificationOccurrence.OccurrenceDateTime.Second);

            var triggerTime = firingCal.TimeInMillis;

            // for test purposes only
            var dateFormat = new SimpleDateFormat("dd:MM:yy:HH:mm:ss");
            var cal        = dateFormat.Format(triggerTime);

            notificationIntent.PutExtra(NotificationPublisher.NOTIFICATION_ID, notificationOccurrence.Id.Value);
            notificationIntent.PutExtra(NotificationPublisher.MEDICATION_ID, id);
            notificationIntent.PutExtra(NotificationPublisher.NOTIFICATION, notification);
            notificationIntent.PutExtra(NotificationPublisher.NOTIFICATION_FIRE_TIME, triggerTime);

            var           requestId     = notificationOccurrence.Id.Value;
            PendingIntent pendingIntent = PendingIntent.GetBroadcast(this.ctx, requestId, notificationIntent, PendingIntentFlags.CancelCurrent);

            AlarmManager alarmManager = (AlarmManager)this.ctx.GetSystemService(Context.AlarmService);

            alarmManager.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, triggerTime, pendingIntent);
        }
예제 #6
0
        public void SetAlarmForNextReminder(Context context)
        {
            long?nextReminderMillisTimestamp = GetNextReminderMillisTimestamp();

            if (nextReminderMillisTimestamp.HasValue && nextReminderMillisTimestamp.Value > 0)
            {
                // Alarm is started 5 seconds after notification time
                // So, we have a better guarantee that it will be notified
                long delay = 1000 * 5;

                Intent        reminderAlarmReceiver = new Intent(context, Java.Lang.Class.FromType(typeof(ReminderAlarmReceiver)));
                PendingIntent pendingIntent         = PendingIntent.GetBroadcast(context, 0, reminderAlarmReceiver, PendingIntentFlags.UpdateCurrent);
                long          triggerAtMillis       = nextReminderMillisTimestamp.Value + delay;

                AlarmManager alarmManager = context.GetSystemService(Context.AlarmService) as AlarmManager;

                if (alarmManager != null)
                {
                    // Method SetExactAndAllowWhileIdle() is for Doze mode, introduced in Android 6.0
                    if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
                    {
                        alarmManager.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, triggerAtMillis, pendingIntent);
                    }
                    else
                    {
                        alarmManager.SetExact(AlarmType.RtcWakeup, triggerAtMillis, pendingIntent);
                    }
                }
            }
        }
예제 #7
0
        public void ScheduleTask(TimeSpan timeSpan, PendingIntent pendingIntent)
        {
            var triggerAtMillis = Java.Lang.JavaSystem.CurrentTimeMillis() + (long)timeSpan.TotalMilliseconds;

            alarmManager.Cancel(pendingIntent);
            alarmManager.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, triggerAtMillis, pendingIntent);
        }
예제 #8
0
        private void ScheduleCallbackAlarm(PendingIntent callbackPendingIntent, TimeSpan delay)
        {
            AlarmManager alarmManager = _service.GetSystemService(global::Android.Content.Context.AlarmService) as AlarmManager;

            // cancel the current alarm for this callback id. this deals with the situations where (1) sensus schedules callbacks
            // and is subsequently restarted, or (2) a probe is restarted after scheduling callbacks (e.g., script runner). in
            // these situations, the originally scheduled callbacks will remain in the alarm manager, and we'll begin piling up
            // additional, duplicate alarms. we need to be careful to avoid duplicate alarms, and this is how we manage it.
            alarmManager.Cancel(callbackPendingIntent);

            long callbackTimeMS = Java.Lang.JavaSystem.CurrentTimeMillis() + (long)delay.TotalMilliseconds;

            // https://github.com/predictive-technology-laboratory/sensus/wiki/Backwards-Compatibility
#if __ANDROID_23__
            if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                alarmManager.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, callbackTimeMS, callbackPendingIntent);  // API level 23 added "while idle" option, making things even tighter.
            }
            else if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
            {
                alarmManager.SetExact(AlarmType.RtcWakeup, callbackTimeMS, callbackPendingIntent);  // API level 19 differentiated Set (loose) from SetExact (tight)
            }
            else
#endif
            {
                alarmManager.Set(AlarmType.RtcWakeup, callbackTimeMS, callbackPendingIntent);  // API 1-18 treats Set as a tight alarm
            }
        }
        /// <summary>
        /// Schedules an alarm.
        /// </summary>
        /// <param name="alarm">The alarm to be scheduled.</param>
        public int ScheduleAlarm(Alarm alarm)
        {
            var scheduleTime = GetNextAlarmTime(alarm.Hour, alarm.Minute);
            var utcTime      = TimeZoneInfo.ConvertTimeToUtc(scheduleTime);
            var epochDif     = (new DateTime(1970, 1, 1) - DateTime.MinValue).TotalSeconds;
            var notifyTimeInInMilliseconds = utcTime.AddSeconds(-epochDif).Ticks / 10000;

            var intent = new Intent(context, typeof(AlarmIntentService));

            intent.PutExtra("id", alarm.Id);
            intent.PutExtra("year", alarm.Year);
            intent.PutExtra("month", alarm.Month);
            intent.PutExtra("day", alarm.Day);
            intent.PutExtra("hour", alarm.Hour);
            intent.PutExtra("minute", alarm.Minute);
            intent.PutExtra("difficulty", alarm.Difficulty);

            Android.Util.Log.Verbose("notifyFilter", $"register {alarm.Id}");             // adb logcat -s notifyFilter

            PendingIntent pendingIntent;

            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                pendingIntent = PendingIntent.GetForegroundService(context, alarm.Id, intent, PendingIntentFlags.UpdateCurrent);
            }
            else
            {
                pendingIntent = PendingIntent.GetService(context, alarm.Id, intent, PendingIntentFlags.UpdateCurrent);
            }

            // Set inexact repeating
            alarmManager.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, notifyTimeInInMilliseconds, pendingIntent);
            //alarmManager.SetRepeating(AlarmType.RtcWakeup, notifyTimeInInMilliseconds, AlarmManager.IntervalDay, pendingIntent);
            return(alarm.Id);
        }
예제 #10
0
        //set our alarm with a datetime object
        private void setAlarm(DateTime calendar)
        {
            // set my alarm (repeating function taken out)
            Intent intent = new Intent(this, typeof(AlarmReceiver));

            // add information to pending intent !!!
            DateTime tmp = calendar;

            tmp.AddMinutes(2.0);
            intent.PutExtra(Intent.ExtraText, tmp.ToLongTimeString());
            PendingIntent pendingIntent = PendingIntent.GetBroadcast(this, 14532, intent, 0);
            AlarmManager  alarmManager  = (AlarmManager)GetSystemService(Context.AlarmService);

            DateTime dtBasis = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            alarmManager.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, (long)(calendar.ToUniversalTime().Subtract(dtBasis).TotalMilliseconds), pendingIntent);
        }
예제 #11
0
        private void ScheduleNotification(Int64 whenDisplayNotificationInUtcUnixTime, String title,
                                          String message, Int32 scheduleId, DateTime lessonDate, Int32 requestCode)
        {
            Int64 currentUtcUnixTime = GetDateTimeInUtcUnixTime(DateTime.UtcNow);

            if (whenDisplayNotificationInUtcUnixTime <= currentUtcUnixTime)
            {
                return;
            }

            AlarmManager alarmManager = _context.GetSystemService(Context.AlarmService)
                                        as AlarmManager;

            Intent intent = new Intent(_context, typeof(LessonsRemindPublisher));

            intent.PutExtra(
                LessonsRemindPublisher.IntentNotificationScheduleIdKey,
                scheduleId.ToString()
                );
            intent.PutExtra(
                LessonsRemindPublisher.IntentNotificationLessonDateKey,
                lessonDate.Ticks.ToString()
                );
            intent.PutExtra(LessonsRemindPublisher.IntentNotificationTitleKey, title);
            intent.PutExtra(LessonsRemindPublisher.IntentNotificationMessageKey, message);

            PendingIntent pendingIntent = PendingIntent.GetBroadcast(
                _context,
                requestCode,
                intent,
                PendingIntentFlags.UpdateCurrent
                );

            Int64 timeInMilliseconds = whenDisplayNotificationInUtcUnixTime * 1000;

            if (Build.VERSION.SdkInt < BuildVersionCodes.M)
            {
                alarmManager.SetExact(AlarmType.RtcWakeup, timeInMilliseconds, pendingIntent);
            }
            else
            {
                alarmManager.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, timeInMilliseconds, pendingIntent);
            }
        }
예제 #12
0
        public override void OnReceive(Context context, Intent intent)
        {
            //Toast.MakeText(context, "Received intent!", ToastLength.Short).Show();

            AndroidRefreshes.Alarm = DateTime.Now;

            // Launch BirdieLib ControlLoop in script mode.  --Kris
            try
            {
                Shared.BirdieLib.Start();
            }
            catch (Exception) { }

            // Repeat in ~15 minutes.  --Kris
            PendingIntent pendingIntent = PendingIntent.GetBroadcast(context, 0, intent, PendingIntentFlags.UpdateCurrent);

            AlarmManager alarmManager = (AlarmManager)Application.Context.GetSystemService(Context.AlarmService);

            alarmManager.SetExactAndAllowWhileIdle(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + (15 * 1000 * 60), pendingIntent);
        }
예제 #13
0
        public override Result DoWork()
        {
            try
            {
                AndroidRefreshes.Worker = DateTime.Now;

                // If the alarm is not yet active or hasn't refreshed in awhile, attempt to recreate it, then wait for it to fire.  --Kris
                if (!AlarmActive || !AlarmSet)
                {
                    // Set the alarm.  --Kris
                    PendingIntent pendingIntent = PendingIntent.GetBroadcast(Application.Context, 0, AlarmIntent, PendingIntentFlags.UpdateCurrent);
                    AlarmManager  alarmManager  = (AlarmManager)Application.Context.GetSystemService(Context.AlarmService);

                    alarmManager.SetExactAndAllowWhileIdle(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + 5000, pendingIntent);

                    // Wait for the alarm intent to execute.  --Kris
                    DateTime start = DateTime.Now;
                    while (!AlarmActive &&
                           start.AddSeconds(30) > DateTime.Now)
                    {
                        Thread.Sleep(5000);
                    }

                    // If the alarm still hasn't refreshed, fire the script from here, instead.  --Kris
                    if (!AlarmActive)
                    {
                        Shared.BirdieLib.Start();
                    }
                }
                // Otherwise, refresh data from the Birdie API for display purposes.  --Kris
                else
                {
                    Shared.BirdieLib.InvokeStatsUpdate();
                }
            }
            catch (Exception) { }

            return(Result.InvokeSuccess());
        }
        public void ScheduleAlarm(Alarm alarm)
        {
            long millis = Android.OS.SystemClock.ElapsedRealtime() + 1000;



            PendingIntent pendingIntent = CreatePendingIntent(Forms.Context, alarm);
            AlarmManager  alarmManager  = (AlarmManager)Forms.Context.GetSystemService(Context.AlarmService);

            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.M)
            {
                alarmManager.SetExactAndAllowWhileIdle(AlarmType.ElapsedRealtimeWakeup, millis, pendingIntent);
            }
            else if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
            {
                alarmManager.SetExact(AlarmType.ElapsedRealtimeWakeup, millis, pendingIntent);
            }
            else
            {
                alarmManager.Set(AlarmType.ElapsedRealtimeWakeup, millis, pendingIntent);
            }
        }
예제 #15
0
        public bool CreateAlarm(Reminder reminder)
        {
            Context      context      = Android.App.Application.Context;
            AlarmManager alarmManager = context.GetSystemService(Context.AlarmService) as AlarmManager;
            Intent       intent       = new Intent(context, typeof(Services.RingtoneService));

            intent.PutExtra("Title", reminder.Name);
            intent.PutExtra("ReminderId", reminder.ReminderId);
            intent.PutExtra("PlayOrEnd", true);

            PendingIntent pendingIntent = PendingIntent.GetService(context, reminder.ReminderId, intent, PendingIntentFlags.UpdateCurrent);

            DateTime now = DateTime.Now;

            //Get Change in time
            System.Diagnostics.Debug.WriteLine($"{reminder.Time.Hours}, {now.Hour}");
            int diffHours = reminder.Time.Hours - now.Hour;
            int diffMins  = reminder.Time.Minutes - now.Minute;

            int cHours = (diffHours < 0) ? (24 + diffHours) : diffHours;
            int cMins  = (diffMins < 0) ? (24 + diffMins) : diffMins;

#if DEBUG
            long millis = 1000 * 5;
#else
            //Test
            long millis = ((cHours + reminder.Hours) * 1000 * 60 * 60) + (diffMins * 60 * 1000);
#endif

            alarmManager.SetExactAndAllowWhileIdle(AlarmType.ElapsedRealtimeWakeup, millis, pendingIntent);

            Toast.MakeText(context, $"Alarm Created {DateTime.Now.AddMilliseconds(millis)}", ToastLength.Short).Show();

            //alarmManager.SetRepeating(AlarmType.Rtc, reminder.Hours* 1000, AlarmManager.IntervalDay, pendingIntent);
            WriteLine($"Alarm Created {reminder.Name}, {reminder.ReminderId}");

            return(true);
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.NotificationLayout);

            this.notificationLabel = FindViewById <TextView>(Resource.Id.NotificationText);
            this.btnAlarmManager   = FindViewById <Button>(Resource.Id.btnAlarmManager);
            this.btnJobScheduler   = FindViewById <Button>(Resource.Id.btnJobScheduler);

            notificationLabel.Text      = Intent.GetStringExtra("main_message");
            this.btnAlarmManager.Click += (sender, args) =>
            {
                Intent        amIntent           = new Intent(this, typeof(NotificationReceiver));
                PendingIntent pendingAlarmIntent = PendingIntent.GetBroadcast(
                    this, 1, amIntent, PendingIntentFlags.UpdateCurrent);
                AlarmManager alarmManager = (AlarmManager)GetSystemService(AlarmService);

                DateTime dt = DateTime.Now.AddMilliseconds(100000);
                alarmManager.SetExactAndAllowWhileIdle(
                    AlarmType.ElapsedRealtimeWakeup,
                    1000000000000000000,
                    pendingAlarmIntent);
            };

            btnJobScheduler.Click += (sender, args) =>
            {
                var builder      = CreateBuilderJobSchedulerObject <ToastJobService>(this, 1);
                var jobInfo      = builder.Build();
                var jobScheduler = GetSystemService(JobSchedulerService) as JobScheduler;
                jobScheduler.Schedule(jobInfo);
            };

            var notificationManager = (NotificationManager)GetSystemService(NotificationService);

            notificationManager.Cancel(1);
        }
예제 #17
0
        public AlarmActiveEventArgs StartBirdieLib()
        {
            AndroidRefreshes.Alarm = DateTime.Now;

            // Set the alarm.  --Kris
            PendingIntent pendingIntent = PendingIntent.GetBroadcast(Application.Context, 0, AlarmIntent, PendingIntentFlags.UpdateCurrent);
            AlarmManager  alarmManager  = (AlarmManager)Application.Context.GetSystemService(AlarmService);

            alarmManager.SetExactAndAllowWhileIdle(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + 5000, pendingIntent);

            // Start the WorkManager.  --Kris
            if (PeriodicWorkRequest == null)
            {
                PeriodicWorkRequest = PeriodicWorkRequest.Builder.From <BirdieWorker>(TimeSpan.FromMinutes(20)).Build();
            }
            PeriodicWorkRequest.Tags.Add("BirdieWorker");

            WorkManager.Instance.Enqueue(PeriodicWorkRequest);

            return(new AlarmActiveEventArgs
            {
                IsScheduled = true
            });
        }
예제 #18
0
        public void SetAlarm(long crashCueMillis, string cueText)
        {
            Context context = Android.App.Application.Context;

            Intent alarmIntent = new Intent(context, typeof(CrashAlarmReceiver));

            alarmIntent.PutExtra("title", CueConstants.NotifTitle);
            alarmIntent.PutExtra("message", CueConstants.NotifMessage + cueText);
            alarmIntent.PutExtra("Id", CueConstants.UniqueId);

            bool alreadyExists = (PendingIntent.GetBroadcast(context, CueConstants.UniqueId, alarmIntent, PendingIntentFlags.NoCreate) != null);

            PendingIntent pendingIntent = PendingIntent.GetBroadcast(context, CueConstants.UniqueId, alarmIntent, PendingIntentFlags.UpdateCurrent);
            AlarmManager  alarmManager  = (AlarmManager)context.GetSystemService(Context.AlarmService);

            if (alreadyExists)
            {
                alarmManager.Cancel(pendingIntent);
            }

            if (Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.M)
            {
                if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
                {
                    alarmManager.SetExact(AlarmType.RtcWakeup, crashCueMillis, pendingIntent);
                }
                else
                {
                    alarmManager.Set(AlarmType.RtcWakeup, crashCueMillis, pendingIntent);
                }
            }
            else
            {
                alarmManager.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, crashCueMillis, pendingIntent);
            }
        }
예제 #19
0
 public static void ScheduleIntentExactAllowIdle(this AlarmManager manager, DateTime dateTime, PendingIntent intent) =>
 manager.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, dateTime.ToUnix(), intent);
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        protected virtual bool ShowLater(NotificationRequest request)
        {
            if (request.Schedule.NotifyTime is null ||
                request.Schedule.NotifyTime <= DateTime.Now) // To be consistent with iOS, Do not Schedule notification if NotifyTime is earlier than DateTime.Now
            {
                return(false);
            }

            var dictionaryRequest = NotificationCenter.GetRequestSerialize(request);

            var intent = new Intent(Application.Context, typeof(ScheduledAlarmReceiver));

            foreach (var item in dictionaryRequest)
            {
                intent.PutExtra(item.Key, item.Value);
            }
            var pendingIntent = PendingIntent.GetBroadcast(
                Application.Context,
                request.NotificationId,
                intent,
                PendingIntentFlags.UpdateCurrent
                );

            var utcAlarmTimeInMillis = (request.Schedule.NotifyTime.Value.ToUniversalTime() - DateTime.UtcNow).TotalMilliseconds;
            var triggerTime          = (long)utcAlarmTimeInMillis;

            if (request.Schedule.RepeatType != NotificationRepeat.No)
            {
                TimeSpan?repeatInterval = null;
                switch (request.Schedule.RepeatType)
                {
                case NotificationRepeat.Daily:
                    // To be consistent with iOS, Schedule notification next day same time.
                    repeatInterval = TimeSpan.FromDays(1);
                    break;

                case NotificationRepeat.Weekly:
                    // To be consistent with iOS, Schedule notification next week same day same time.
                    repeatInterval = TimeSpan.FromDays(7);
                    break;

                case NotificationRepeat.TimeInterval:
                    if (request.Schedule.NotifyRepeatInterval.HasValue)
                    {
                        repeatInterval = request.Schedule.NotifyRepeatInterval.Value;
                    }
                    break;
                }

                if (repeatInterval == null)
                {
                    return(true);
                }
                var intervalTime = (long)repeatInterval.Value.TotalMilliseconds;

                MyAlarmManager.SetInexactRepeating(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + triggerTime, intervalTime, pendingIntent);
            }
            else
            {
                if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
                {
                    MyAlarmManager.SetExactAndAllowWhileIdle(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + triggerTime, pendingIntent);
                }
                else
                {
                    MyAlarmManager.SetExact(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + triggerTime, pendingIntent);
                }
            }

            AddPreferencesNotificationId(PreferencesPendingIdListKey, request.NotificationId);

            return(true);
        }