how to make Alarm repeats for particular time interval in Xamarin Droid project?

1.5k views Asked by At

Using Xamarin Droid, i have created an alarm application. Setting alarm for the particular time was worked good. when i try to repeat the alarm for the particular time interval, it fails to alarm at the particular time. the application needs to alarm even the application in sleep. The below code was i tried in Xamarin Droid project for setting and repeating alarm. please direct me in right way to achieve my solution for repeating alarm!.

Setting alarm for particular time:

 manager.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + 60 * 1000 * int.Parse(notifytime), pendingIntent);

My need is to repeat the alarm for every 15 min from the alarm rang.

 manager.SetRepeating(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime()+10, AlarmManager.IntervalFifteenMinutes, pendingIntent);

Thanks in advance.

2

There are 2 answers

0
Towfik Alrazihi On BEST ANSWER

change this line...

manager.SetRepeating(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime()+10, AlarmManager.IntervalFifteenMinutes, pendingIntent);

to

 manager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(),15*60*1000, pintent);

also add this

<uses-permission android:name="android.permission.WAKE_LOCK" />

to your AndroidManifest.xml file as #Avi Cherry said !!

schedule a repeating alarm

0
Avi Cherry On

There are several pieces that must be implemented in order for an alarm to reliably trigger an action at the correct time on Android when the device is asleep and they all involve holding a wake lock while the target PendingIntent is being run. I am assuming that your PendingIntent refers to a BroadcastReceiver or a Service rather than an Activity since running Activities on a timer is usually not useful. If the target of your PendingIntent does not hold a wake lock, there is no guarantee that the action will actually take place at the time the alarm is called. This very old thread discusses the lack of guarantees about waking up the device using AlarmManager.

The solution is to make sure that the first thing the target of your PendingIntent does is hold a wakeful lock on the device. The first thing you must do is allow your application permission to hold a wake lock. This is done by adding the following permission to your AndroidManifest.xml file.

<uses-permission android:name="android.permission.WAKE_LOCK" />

Thankfully there is some Xamarin sample code written by @jon-douglas that demonstrates this here. While this will probably get you the result that you want, it seems that the best practice is not to directly call a Service, but instead to use an intermediary WakefulBroadcastReceiver that starts your service for you. There is an example of how to do this in the Android documentation for WakefulBroadcastReceiver.