com.brayanarias.alarmproject.receiver.AlarmReceiver.java Source code

Java tutorial

Introduction

Here is the source code for com.brayanarias.alarmproject.receiver.AlarmReceiver.java

Source

/*
 * Copyright (C) 2015 brayanarias.com ing.brayanarias@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.brayanarias.alarmproject.receiver;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;

import com.brayanarias.alarmproject.database.AlarmDataBase;
import com.brayanarias.alarmproject.database.DataBaseManager;
import com.brayanarias.alarmproject.model.Alarm;
import com.brayanarias.alarmproject.service.AlarmService;
import com.brayanarias.alarmproject.util.AlarmUtilities;
import com.brayanarias.alarmproject.util.Constant;

import java.util.Calendar;
import java.util.List;

public class AlarmReceiver extends WakefulBroadcastReceiver {

    public static final String tag = AlarmReceiver.class.getName();

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

    public static void setAlarms(Context context) {
        //First cancelling all alarms
        cancelAlarms(context);
        //Set alarms list
        DataBaseManager dataBaseManager = DataBaseManager.getInstance(context);
        List<Alarm> alarmList = AlarmDataBase.getAlarmList(dataBaseManager);
        int alarmActivatedCount = 0;
        for (Alarm alarm : alarmList) {
            if (alarm.getActivated() == 1) {
                setAlarm(context, alarm);
                alarmActivatedCount++;
            }
        }
        AlarmUtilities.setStatusBarIcon(context, alarmActivatedCount > 0);
        Calendar day = Calendar.getInstance();
        day.set(Calendar.DAY_OF_MONTH, 28);
        day.set(Calendar.MONTH, 8);
        day.set(Calendar.HOUR, 11);
        day.set(Calendar.AM_PM, Calendar.PM);
        if ((day.getTimeInMillis() - Calendar.getInstance().getTimeInMillis()) > 0) {
            setAlarmCumple(context);
        }
    }

    private static void setAlarmCumple(Context context) {
        PendingIntent pendingIntent = null;
        Intent intent = new Intent(context, AlarmService.class);
        intent.putExtra(Constant.alarmIdKey, 2809);
        intent.putExtra(Constant.alarmNameKey, "Feliz cumple mamita");
        pendingIntent = PendingIntent.getService(context, 2809, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = getAlarmManager(context);
        Calendar actual = Calendar.getInstance();
        actual.set(Calendar.MONTH, 8);
        actual.set(Calendar.DAY_OF_MONTH, 28);
        actual.set(Calendar.SECOND, 0);
        actual.set(Calendar.MILLISECOND, 0);
        actual.set(Calendar.HOUR, 5);
        actual.set(Calendar.AM_PM, Calendar.AM);
        actual.set(Calendar.MINUTE, 0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(actual.getTimeInMillis(),
                    pendingIntent);
            alarmManager.setAlarmClock(clockInfo, pendingIntent);
        } else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, actual.getTimeInMillis(), pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, actual.getTimeInMillis(), pendingIntent);
        }
    }

    private static void setAlarm(Context context, Alarm alarm) {
        try {
            PendingIntent pendingIntent = createPendingIntent(context, alarm);
            AlarmManager alarmManager = getAlarmManager(context);
            Calendar actual = Calendar.getInstance();
            actual.set(Calendar.SECOND, 0);
            actual.set(Calendar.MILLISECOND, 0);
            Calendar calendar = (Calendar) actual.clone();
            int ampm = alarm.getAmPm().equals("AM") ? Calendar.AM : Calendar.PM;
            if (alarm.getHour() == 12) {
                calendar.set(Calendar.HOUR, 0);
            } else {
                calendar.set(Calendar.HOUR, alarm.getHour());
            }
            calendar.set(Calendar.AM_PM, ampm);
            calendar.set(Calendar.MINUTE, alarm.getMinute());
            int day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
            if (actual.getTimeInMillis() >= calendar.getTimeInMillis()) {
                if (alarm.getDaysOfAlamr().equals("0000000")) {
                    calendar.add(Calendar.DATE, 1);
                } else {
                    calendar.add(Calendar.DATE, getDaysFromNextAlarm(alarm.getDaysOfAlamr()));
                }
            } else {
                if (!AlarmUtilities.isToday(alarm.getDaysOfAlamr(), day)) {
                    calendar.add(Calendar.DATE, getDaysFromNextAlarm(alarm.getDaysOfAlamr()));
                }
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(calendar.getTimeInMillis(),
                        pendingIntent);
                alarmManager.setAlarmClock(clockInfo, pendingIntent);
            } else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
            } else {
                alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
            }

        } catch (Exception e) {
            Log.e(tag, e.getLocalizedMessage(), e);
        }
    }

    private static int getDaysFromNextAlarm(String daysOfAlarm) {
        int days = 0;
        if (!daysOfAlarm.equals("0000000")) {
            int day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
            days = AlarmUtilities.getDaysToSum(daysOfAlarm, day);
        }
        return days;
    }

    public static void cancelAlarms(Context context) {
        DataBaseManager dataBaseManager = DataBaseManager.getInstance(context);
        List<Alarm> alarmList = AlarmDataBase.getAlarmList(dataBaseManager);
        for (Alarm alarm : alarmList) {
            PendingIntent pendingIntent = createPendingIntent(context, alarm);
            cancelPendingIntent(pendingIntent, context);
        }
    }

    public static PendingIntent createPendingIntent(Context context, Alarm alarm) {
        PendingIntent pendingIntent = null;
        try {
            Intent intent = new Intent(context, AlarmService.class);
            intent.putExtra(Constant.alarmIdKey, alarm.getId());
            intent.putExtra(Constant.alarmNameKey, alarm.getName());
            intent.putExtra(Constant.alarmHourKey, alarm.getHour());
            intent.putExtra(Constant.alarmMinuteKey, alarm.getMinute());
            intent.putExtra(Constant.alarmToneKey, alarm.getTone());
            intent.putExtra(Constant.alarmHourFormattedKey, alarm.getHourFormatted());
            intent.putExtra(Constant.alarmVibrateKey, alarm.getVibrate());
            intent.putExtra(Constant.alarmAmPmKey, alarm.getAmPm());
            intent.putExtra(Constant.alarmSoundHolidayKey, alarm.getOnHoliday());
            intent.putExtra(Constant.alarmDaysKey, alarm.getDaysOfAlamr());
            intent.putExtra(Constant.alarmDeleteAfterKey, alarm.getDeleteOnSound());
            intent.putExtra(Constant.alarmPostponeKey, alarm.getPostpone());
            pendingIntent = PendingIntent.getService(context, alarm.getId(), intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
        } catch (Exception e) {
            Log.e(tag, e.getLocalizedMessage(), e);
        }
        return pendingIntent;
    }

    public static AlarmManager getAlarmManager(Context context) {
        return (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    }

    public static void cancelPendingIntent(PendingIntent pendingIntent, Context context) {
        try {
            getAlarmManager(context).cancel(pendingIntent);
        } catch (Exception e) {
            Log.w(tag, "PendingIntent can not cancelled, maybe does not exists");
        }
    }

    public static void dismissAlarm(int alarmId, int minutes, Context context) {
        try {
            DataBaseManager dataBaseManager = DataBaseManager.getInstance(context);
            Alarm alarm = AlarmDataBase.getAlarmById(dataBaseManager, alarmId);
            PendingIntent pendingIntent = createPendingIntent(context, alarm);
            AlarmManager alarmManager = getAlarmManager(context);
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE, minutes);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(calendar.getTimeInMillis(),
                        pendingIntent);
                alarmManager.setAlarmClock(clockInfo, pendingIntent);
            } else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
            } else {
                alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
            }
        } catch (Exception e) {
            Log.e(tag, e.getMessage(), e);
        }
    }
}