简体   繁体   中英

MonoDroid - Daily scheduled service using alarm manager?

I am trying to schedule a service to run daily at a user specified time. I am using a timepicker to give the user control over what time of day the service is run.

Each time the user changes the time of day for the service to run I am updating the alarm manager.

Here is my code to do this:

void RescheduleOpeningRatesRetriever (string strTime)
{
    var i = new Intent (this.ApplicationContext, typeof (OpenRatesService));            
    var src = PendingIntent.GetService (this.ApplicationContext, 0, i, PendingIntentFlags.UpdateCurrent);
    var am = (AlarmManager)this.ApplicationContext.GetSystemService (Context.AlarmService);

    var hour = TimePickerPreference.GetHour (strTime);
    var minute = TimePickerPreference.GetMinute (strTime);

    var cal = Java.Util.Calendar.GetInstance (Java.Util.TimeZone.Default);
    cal.Set (Java.Util.CalendarField.HourOfDay, hour);
    cal.Set (Java.Util.CalendarField.Minute, minute);

    am.SetRepeating (AlarmType.RtcWakeup, cal.TimeInMillis, AlarmManager.IntervalDay, src);
}

I am not 100% sure if the code is scheduling the service to run properly as I have had mixed results from my tests.

The problem that I am experiencing now is each time I re-schedule the service to run with the above code, the service is started instantly.... I don't want to start the service until the configured time of day.

How can I schedule and update the service to run at a specified time of day without running the service instantly upon scheduling it with the alarm manager?

If the time for which you are setting the alarm is in the past then the alarm will goes off instantly. so first check whether the time is in past, if it is then set it for next day.

like::

Calendar rightNow = Calendar.getInstance()

if( cal.after( rightNow )  )
{
      am.SetRepeating (AlarmType.RtcWakeup, cal.TimeInMillis, AlarmManager.IntervalDay, src);
}
else
{
      cal.roll(Java.Util.CalendarField.DAY_OF_MONTH, 1);
      SetRepeating (AlarmType.RtcWakeup, cal.TimeInMillis, AlarmManager.IntervalDay, src);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM