Search code examples
androidandroid-intentnotificationsbroadcastreceiverandroid-alarms

Multiple alarms are getting fired after reboot in android through broadcast receiver


I am making a notification application and for that i am using scheduled alarms for running the notifications using Broadcast receiver class and i am prompting user to select from daily or hourly notifications and i am defining both alarms in the same receiver under the same function and it is working fine but the problems comes when i restart my device,when i restart it both the alarms (daily and hourly) are getting triggered when i am only setting one for example if i set an alarm for 11:20 A.M and restart my device the hourly one and this 11:20 one both are getting triggered,i want that when i restart my device only the alarm which was selected before the device boot only gets triggered.

My receiver class:-

public class alarmreceiver extends BroadcastReceiver {
    int id=0;

    @Override
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context, "Alarm running", Toast.LENGTH_SHORT).show();

        start(context,id);

    }
    static void start(Context context,int id) {
        Intent intent = new Intent(context, notification_receiver.class);
        PendingIntent pendingintent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (id==1) {

            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR, 11);
            calendar.set(Calendar.MINUTE, 9);
            calendar.set(Calendar.AM_PM, Calendar.AM);
            alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingintent);
        }
            else

            if (id==2) {

                alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                        SystemClock.elapsedRealtime(), 60 * 1000
                        , pendingintent);
            }
        }

I am calling this function under button click listener like this:- For daily notifications:-

alarmreceiver.start(getApplicationContext(),1);

For hourly notifications:-

alarmreceiver.start(getApplicationContext(),2);

Solution

  • This code:

    alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                        SystemClock.elapsedRealtime(), 60 * 1000, pendingintent);
    

    sets a repeating alarm that goes off every minute, not every hour!

    Also, this code sets an alarm that goes off right now and again every minute. The second argument to setRepeating() is the time of first alarm. You've passed SystemClock.elapsedRealtime() which basically means "now".