[Android] Implementing AlarmUtil class in Java

in #kr4 years ago

I am implementing AlarmUtil class in Java to set and cancel alarms more conveniently. Below code is current AlarmUtil class. I will add more set methods.

public class AlarmUtil {

    // To trigger an alarm in durationMinutes.
    public static void setAlarm(
        Context context,
        Class alarmReceiverClass,
        int durationMinutes,
        int alarmType,
        int requestCode,
        int flags,
        Bundle bundle
    ) {
        AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, alarmReceiverClass);
        intent.putExtras(bundle);
        PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(
            context,
            requestCode,
            intent,
            flags
        );

        am.set(
            alarmType,
            SystemClock.elapsedRealtime() + durationMinutes * 60 * 1000,
            pendingAlarmIntent
        );
    }

    // To cancel all alarms of a broadcast receiver of which class is alarmReceiverClass.
    public static void cancelAlarm(Context context, Class alarmReceiverClass, int requestCode, int flags) {
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Intent intent = new Intent(context, alarmReceiverClass);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
            context,
            requestCode,
            intent,
            flags
        );

        am.cancel(pendingIntent);
    }

}