Scheduling tasks
Some tasks need to be performed at a particular time in the future, some may even be required to recur.
How to do it...
We can schedule tasks for the future using the AlarmManager
instance:
As scheduling tasks involves running code when the app is closed by the user, we have to get permission to do this:
[assembly: UsesPermission(Manifest.Permission.SetAlarm)]
Then, we need a broadcast receiver that will receive a notification when the alarm is triggered:
[BroadcastReceiver] [IntentFilter(new[] { "xamarincookbook.Alarm" })] public class AlarmReceiver : BroadcastReceiver { public override void OnReceive( Context context, Intent intent) { // alarm has triggered } }
When we want to schedule a task, we set an alarm for a specific time and then provide an intent that should be broadcast when the time expires:
var ringTime = JavaSystem.CurrentTimeMillis() + (long)TimeSpan.FromSeconds(5).TotalMilliseconds; var intent = new Intent("xamarincookbook.Alarm"); var alarm = PendingIntent...