Xmstr
Xmstr

Reputation: 229

Android repeating alarm in Broadcast Receiver

My alarm starts notification service. A want my alarm fire every 7th day of every month at 14:00

My receiver:

public class AlarmReceiver extends BroadcastReceiver {
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;

@Override
public void onReceive(Context context, Intent intent) {
    System.out.println("RECEIVER STARTED");
    if (checkForDay()) {
        alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent1 = new Intent(context, AlarmService.class);
        alarmIntent = PendingIntent.getService(context, 0, intent1, 0);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 14);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        alarmMgr.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
        System.out.println("ALARM SET");
    } else
        System.out.println("ALARM NOT SET");
}

private boolean checkForDay() {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    return calendar.get(Calendar.DATE) == 7;

}

My receiver starts at BOOT_COMPLETE and from broadcast in MainActivity onCreate(); But there are problems.

  1. What if user keep the phone 24/7 booted
  2. User can start my app after 14:00 and alarm fires instantly - dont want it. Only at 14:00
  3. Uset can forget to start my app and alarm will not fire at all

How to implement right Repeating Monthly alarm if setInexactRepeating() is not good, because of interval. Its not the same every month?

Upvotes: 0

Views: 504

Answers (1)

VIjay J
VIjay J

Reputation: 766

case 1 : [What if user keep the phone 24/7 booted]

In this case, everything goes straight. When alarm fired on 7th day at 14:00 , you can set next alarm for next 7th day

case 2 : [User can start my app after 14:00 and alarm fires instantly - dont want it. Only at 14:00]

In this case , just add one check to process or not to process your logic you need to execute on 7th day of every month at 14:00

Case 3 : [User can forget to start my app and alarm will not fire at all]

You can use Reboot event ,it works.

Upvotes: 0

Related Questions