Monday 2 February 2015

How to set a Repeating Alarm ?

I already discussed how to set a simple one-time alarm in previous posts. So let's now consider how we can set an alarm that goes of repeatedly.

Setting a Repeating Alarm :

public void sendRepeatingAlarm()
{
     Calendar cal = Utils.getTimeAfterInSecs(30);
     String s = Utils.getDateTimeString(cal);
    
     // Get an intent to invoke the receiver
     Intent intent = new Intent (this.mContext, TestReceiver.class);
     intent.putExtra("message", "Repeating Alarm");

     PendingIntent pi = this.getDistinctPendingIntent(intent, 2);
     // Schedule the alarm !
     AlarmManager am =
     (AlarmManager)
                            this.mContext.getSystemService(Context.ALARM_SERVICE);

     am.setRepeating(AlarmManager.RTC_WAKEUP,
                             cal.getTimeInMillis(),
                             5*1000,  // 5 secs repeat
                             pi);
}

protected PendingIntent getDistinctPendingIntent(Intent intent, int requestId)
{
     PendingIntent pi =
           PendingIntent.getBroadcast(
                         mContext,  //context, or activity
                         requestId,  // request id
                         intent,       // intent to be delivered
                         0);
    return pi;
}

No comments:

Post a Comment