i want to have alarm set once a day in 20:00 o'clock, when i debug the application in the emulator everything works fine, but in my phone sometimes it works and sometimes not. this is my code
public class AlarmUtility
{
private static TimeSpan AlarmTime = new TimeSpan(20, 00, 0);
private static long CurrentAlarm;
public static void StartAlarm()
{
AlarmManager manager = (AlarmManager)Application.Context.GetSystemService(Context.AlarmService);
Intent myIntent;
PendingIntent pendingIntent;
myIntent = new Intent(Application.Context, typeof(DailyNotificationReciever));
pendingIntent = PendingIntent.GetBroadcast(Application.Context, 0, myIntent, PendingIntentFlags.UpdateCurrent);
long date;
//check if alarm date has passed
if(DateTime.Now.TimeOfDay < AlarmTime)
{
date = getAlarmJavaTime(false);
}
else
{
date = getAlarmJavaTime(true);
}
if (CurrentAlarm != date)
{
manager.SetInexactRepeating(AlarmType.RtcWakeup, date, AlarmManager.IntervalDay, pendingIntent);
CurrentAlarm = date;
}
}
private static long getAlarmJavaTime(bool addDay)
{
Calendar cal = Calendar.Instance;
cal.TimeInMillis = Java.Lang.JavaSystem.CurrentTimeMillis();
cal.Set(CalendarField.HourOfDay, AlarmTime.Hours);
cal.Set(CalendarField.Minute, AlarmTime.Minutes);
cal.Set(CalendarField.Second, AlarmTime.Seconds);
if (addDay)
{
cal.Add(CalendarField.DayOfMonth, 1);
}
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss 'GMT'Z yyyy");
string a = dateFormat.Format(cal.Time);
return cal.TimeInMillis;
}
}
am i doing something wrong? maybe the alarm doesn't set when the app in not active ? update my DailyNotificationReciever code as requested
[BroadcastReceiver(Enabled = true)]
public class DailyNotificationReciever : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Toast.MakeText(context, "DailyNotificationReciever", ToastLength.Long).Show();
//create nofification id
Random rnd = new Random();
int notificationNumber = rnd.Next(1000);
//create the intents
//user click yes
Intent IntentYes = new Intent("UserClickedYes");
PendingIntent pendingIntentYes = PendingIntent.GetBroadcast(context, (int)DateTime.Now.Ticks, IntentYes, PendingIntentFlags.CancelCurrent);
//user click no
Intent IntentNo = new Intent("UserClickedNo");
PendingIntent pendingIntentNo = PendingIntent.GetBroadcast(context, (int)DateTime.Now.Ticks, IntentNo, PendingIntentFlags.CancelCurrent);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.SetAutoCancel(true)
.SetDefaults((int)NotificationDefaults.All)
.SetContentTitle("test")
.SetContentText("test")
.SetAutoCancel(true)
.AddAction(Resource.Drawable.Test_32px, "Yes", pendingIntentYes)
.AddAction(Resource.Drawable.Test_32px, "No", pendingIntentNo);
NotificationManager manager = (NotificationManager)context.GetSystemService(Context.NotificationService);
manager.Notify(
notificationNumber, builder.Build());
}
}
Thanks