How to set multiple alarms using Alarm Manager in Android

06-12-2019

We can use following class to set alarm for multiple day of weeks:

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import java.util.Calendar;

public class AlarmStartRadioHelper {
    private Context mContext;
    private Class<? extends BroadcastReceiver> mBroadcastReceiverClass;
    private static int RQS_1 = 1002;
    private String mActionName;
    
    public AlarmStartRadioHelper(Context context, Class<? extends BroadcastReceiver> receiver, String actionName) {
        this.mContext = context;
        this.mBroadcastReceiverClass = receiver;
        mActionName = actionName;
    }
    
    public AlarmStartRadioHelper(Context mContext) {
        this.mContext = mContext;
    }
    
    public void setAlarm(int dayOfWeek, int hour, int minute, AlarmHelperResponse alarmHelperResponse) {
        Calendar calNow = Calendar.getInstance();
        Calendar calSet = (Calendar) calNow.clone();
        calSet.setTimeInMillis(System.currentTimeMillis());
        calSet.set(Calendar.DAY_OF_WEEK, dayOfWeek);
        calSet.set(Calendar.HOUR_OF_DAY, hour);
        calSet.set(Calendar.MINUTE, minute);
        calSet.set(Calendar.SECOND, 0);
        if (calSet.compareTo(calNow) <= 0) {
            
            calSet.add(Calendar.DATE, 1);
        }
        
        AlarmManager alarmMgr = getAlarmManager();
        if (alarmMgr == null) return;
        Intent intent = new Intent(mContext, mBroadcastReceiverClass);
        PendingIntent alarmIntent = PendingIntent.getBroadcast(mContext,
        RQS_1 + dayOfWeek, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        
        alarmMgr.set(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), alarmIntent);
        
        alarmHelperResponse.onTimeSet();
        
    }
    
    public void cancelAlarm(int dayOfWeek) {
        Intent intent = new Intent(mContext, mBroadcastReceiverClass);
        intent.setAction(mActionName);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
        mContext, RQS_1 + dayOfWeek, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarmManager = getAlarmManager();
        alarmManager.cancel(pendingIntent);
        pendingIntent.cancel();
        
    }
    
    private AlarmManager getAlarmManager() {
        return (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    }
    
    public boolean isAlarmActive(int dayOfWeek) {
        Intent intent = new Intent(mContext, mBroadcastReceiverClass);
        intent.setAction(mActionName);
        return (PendingIntent.getBroadcast(mContext, RQS_1 + dayOfWeek,
        intent, PendingIntent.FLAG_CANCEL_CURRENT) != null);
    }
    
}

© 2019 All rights reserved. Codesenior.COM