Example usage for android.app AlarmManager setExact

List of usage examples for android.app AlarmManager setExact

Introduction

In this page you can find the example usage for android.app AlarmManager setExact.

Prototype

public void setExact(@AlarmType int type, long triggerAtMillis, PendingIntent operation) 

Source Link

Document

Schedule an alarm to be delivered precisely at the stated time.

Usage

From source file:com.pacoapp.paco.triggering.NotificationCreator.java

@SuppressLint("NewApi")
private void createAlarmToCancelNotificationAtTimeout(Context context, NotificationHolder notificationHolder) {
    DateTime alarmTime = new DateTime(notificationHolder.getAlarmTime());
    int timeoutMinutes = (int) (notificationHolder.getTimeoutMillis() / MILLIS_IN_MINUTE);
    DateTime timeoutTime = new DateTime(alarmTime).plusMinutes(timeoutMinutes);
    long elapsedDurationInMillis = timeoutTime.getMillis();

    Log.info("Creating cancel alarm to timeout notification for holder: " + notificationHolder.getId()
            + ". experiment = " + notificationHolder.getExperimentId() + ". alarmtime = "
            + new DateTime(alarmTime).toString() + " timing out in " + timeoutMinutes + " minutes");

    Intent ultimateIntent = new Intent(context, AlarmReceiver.class);
    Uri uri = Uri.withAppendedPath(NotificationHolderColumns.CONTENT_URI,
            notificationHolder.getId().toString());
    ultimateIntent.setData(uri);//  w ww . jav  a2  s  .  c  o m
    ultimateIntent.putExtra(NOTIFICATION_ID, notificationHolder.getId().longValue());

    PendingIntent intent = PendingIntent.getBroadcast(context.getApplicationContext(), 2, ultimateIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(intent);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, elapsedDurationInMillis, intent);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, elapsedDurationInMillis, intent);
    }

}

From source file:com.pacoapp.paco.triggering.NotificationCreator.java

@SuppressLint("NewApi")
private void createAlarmForSnooze(Context context, NotificationHolder notificationHolder) {
    DateTime alarmTime = new DateTime(notificationHolder.getAlarmTime());
    Experiment experiment = experimentProviderUtil
            .getExperimentByServerId(notificationHolder.getExperimentId());
    Integer snoozeTime = notificationHolder.getSnoozeTime();
    if (snoozeTime == null) {
        snoozeTime = DEFAULT_SNOOZE_10_MINUTES;
    }//from ww  w  . ja v a  2s.  c o  m
    int snoozeMinutes = snoozeTime / MILLIS_IN_MINUTE;
    DateTime timeoutMinutes = new DateTime(alarmTime).plusMinutes(snoozeMinutes);
    long snoozeDurationInMillis = timeoutMinutes.getMillis();

    Log.info("Creating snooze alarm to resound notification for holder: " + notificationHolder.getId()
            + ". experiment = " + notificationHolder.getExperimentId() + ". alarmtime = "
            + new DateTime(alarmTime).toString() + " waking up from snooze in " + timeoutMinutes + " minutes");

    Intent ultimateIntent = new Intent(context, AlarmReceiver.class);
    Uri uri = Uri.withAppendedPath(NotificationHolderColumns.CONTENT_URI,
            notificationHolder.getId().toString());
    ultimateIntent.setData(uri);
    ultimateIntent.putExtra(NOTIFICATION_ID, notificationHolder.getId().longValue());
    ultimateIntent.putExtra(SNOOZE_REPEATER_EXTRA_KEY, true);

    PendingIntent intent = PendingIntent.getBroadcast(context.getApplicationContext(), 3, ultimateIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(intent);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, snoozeDurationInMillis, intent);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, snoozeDurationInMillis, intent);
    }

}

From source file:com.brayanarias.alarmproject.receiver.AlarmReceiver.java

private static void setAlarm(Context context, Alarm alarm) {
    try {//  w  w  w.j a  v  a2 s.c  o m
        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);
    }
}

From source file:com.android.launcher3.widget.DigitalAppWidgetProvider.java

/**
 * Start an alarm that fires on the next quarter hour to update the world clock city
 * day when the local time or the world city crosses midnight.
 *
 * @param context The context in which the PendingIntent should perform the broadcast.
 *///from   ww  w.j a v  a  2s. c  om
private void startAlarmOnQuarterHour(Context context) {
    if (context != null) {
        long onQuarterHour = Utils.getAlarmOnQuarterHour();
        PendingIntent quarterlyIntent = getOnQuarterHourPendingIntent(context);
        AlarmManager alarmManager = ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE));
        if (Utils.isKitKatOrLater()) {
            alarmManager.setExact(AlarmManager.RTC, onQuarterHour, quarterlyIntent);
        } else {
            alarmManager.set(AlarmManager.RTC, onQuarterHour, quarterlyIntent);
        }
    }
}

From source file:com.kaku.weac.fragment.AlarmClockOntimeFragment.java

/**
 * ??//w w w .j ava  2s . co m
 */
@TargetApi(19)
private void nap() {
    // ??X
    if (mNapTimesRan == mNapTimes) {
        return;
    }
    // ??1
    mNapTimesRan++;
    LogUtil.d(LOG_TAG, "??" + mNapTimesRan);

    // ???
    Intent intent = new Intent(getActivity(), AlarmClockBroadcast.class);
    intent.putExtra(WeacConstants.ALARM_CLOCK, mAlarmClock);
    intent.putExtra(WeacConstants.NAP_RAN_TIMES, mNapTimesRan);
    PendingIntent pi = PendingIntent.getBroadcast(getActivity(), -mAlarmClock.getId(), intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Activity.ALARM_SERVICE);
    // XXX
    // ?
    long nextTime = System.currentTimeMillis() + 1000 * 60 * mNapInterval;

    LogUtil.i(LOG_TAG, "??:" + mNapInterval + "");

    // ?194.4
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, nextTime, pi);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, nextTime, pi);
    }

    // ?
    Intent it = new Intent(getActivity(), AlarmClockNapNotificationActivity.class);
    it.putExtra(WeacConstants.ALARM_CLOCK, mAlarmClock);
    // FLAG_UPDATE_CURRENT ???
    // FLAG_ONE_SHOT ??
    PendingIntent napCancel = PendingIntent.getActivity(getActivity(), mAlarmClock.getId(), it,
            PendingIntent.FLAG_CANCEL_CURRENT);
    // 
    CharSequence time = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(nextTime);

    // 
    NotificationCompat.Builder builder = new NotificationCompat.Builder(getActivity());
    // PendingIntent
    Notification notification = builder.setContentIntent(napCancel)
            // ?
            .setDeleteIntent(napCancel)
            // 
            .setContentTitle(String.format(getString(R.string.xx_naping), mAlarmClock.getTag()))
            // 
            .setContentText(String.format(getString(R.string.nap_to), time))
            // ???
            .setTicker(String.format(getString(R.string.nap_time), mNapInterval))
            // ???
            .setSmallIcon(R.drawable.ic_nap_notification)
            // 
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
            .setAutoCancel(true)
            // ??
            .setDefaults(NotificationCompat.DEFAULT_LIGHTS | NotificationCompat.FLAG_SHOW_LIGHTS).build();
    /*        notification.defaults |= Notification.DEFAULT_LIGHTS;
            notification.flags |= Notification.FLAG_SHOW_LIGHTS;*/

    // ???
    mNotificationManager.notify(mAlarmClock.getId(), notification);
}

From source file:com.ayogo.cordova.notification.ScheduledNotificationManager.java

public ScheduledNotification scheduleNotification(String title, JSONObject options) {
    LOG.v(NotificationPlugin.TAG, "scheduleNotification: " + title);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    ScheduledNotification notification = new ScheduledNotification(title, options);

    long alarmTime = notification.at;

    if (alarmTime != 0) { //0 = uninitialized.

        saveNotification(notification);/*from ww w .ja v a 2  s .co m*/

        LOG.v(NotificationPlugin.TAG, "create Intent: " + notification.tag);

        Intent intent = new Intent(context, TriggerReceiver.class);
        intent.setAction(notification.tag);

        PendingIntent pi = PendingIntent.getBroadcast(context, INTENT_REQUEST_CODE, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        LOG.v(NotificationPlugin.TAG, "schedule alarm for: " + alarmTime);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pi);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
        }
    } else {
        // No "at", trigger the notification right now.
        showNotification(notification);
    }

    return notification;
}

From source file:com.lewa.crazychapter11.MainActivity.java

public boolean isLewaRom(Context context, Intent alarmIntent) {
    PackageManager pm = context.getPackageManager();
    boolean isLewaRom = true;
    String version = "";
    int versionCode = 0;
    PackageInfo pi = null;/*from w  w  w. ja v a  2 s  .  c o  m*/

    String testsr = null;
    try {
        // com.lewa.permmanager
        // pm.getPackageInfo("com.lewa.deviceactivate",PackageManager.GET_ACTIVITIES);
        pm.getPackageInfo("com.lewa.permmanager", PackageManager.GET_ACTIVITIES);

        pi = pm.getPackageInfo(context.getPackageName(), 0);
        version = pi.versionName;
        versionCode = pi.versionCode;
    } catch (PackageManager.NameNotFoundException e) {
        isLewaRom = false;
    }
    Log.d("algerheMain00", "isLewaRom : " + isLewaRom);
    Log.i("algerheVersion", "versionname=" + version + " \n getPackageName()=" + getPackageName()
            + " \n versioncode=" + versionCode);
    Log.i("algerheStr", "TextUtils.isEmpty(testsr) = " + TextUtils.isEmpty(testsr));
    // Log.i("algerheStr","testsr.length="+testsr.length());

    ///alarm test
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 16);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    alarmIntent.setAction("com.lewa.alarm.test");
    PendingIntent pipi = PendingIntent.getBroadcast(context, 3359, alarmIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Log.i("algerheAlarm", "send alarm message in time=" + System.currentTimeMillis());

    // alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5000, pipi);

    alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pipi);

    // final Timer timer = new Timer();

    // timer.schedule(new TimerTask() {
    //    @Override
    //    public void run() {
    //       Message msg = new Message();
    //       msg.what = 0x2789;   

    //       handler.sendMessage(msg);

    //       timer.cancel();
    //    }
    // }, 0, 5000);

    return isLewaRom;
}

From source file:org.wso2.iot.agent.services.kiosk.KioskAlarmReceiver.java

/**
 * Generic function to generate alarm to both lock and unlock scenarios.
 * @param context Context of the application.
 * @param enableLock Set whether its a lock alarm or unlock alarm.
 * @param isInitialRun Set if its the initial alarm or not.
 *///from  w  w  w. j a v a 2  s .  c  om
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void buildAlarm(Context context, boolean enableLock, boolean isInitialRun) {
    AlarmManager alarmManager;
    PendingIntent pendingIntent;
    Calendar calendar;
    int currentTime;
    alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (Preference.getBoolean(context, Constants.PreferenceCOSUProfile.ENABLE_LOCKDOWN)) {
        int freezeTime = Preference.getInt(context, Constants.PreferenceCOSUProfile.FREEZE_TIME);
        int releaseTime = Preference.getInt(context, Constants.PreferenceCOSUProfile.RELEASE_TIME);

        Intent receiverIntent = new Intent(context, KioskAlarmReceiver.class);
        receiverIntent.putExtra(Constants.Operation.ENABLE_LOCK, enableLock);

        if (!enableLock) {
            /* if releaseTime is after freezeTime, then needs to set unlock alarm in next day since
             device operation time extends to next day as well. */
            calendar = getCalendar(releaseTime, freezeTime > releaseTime);
        } else if (isInitialRun) {
            currentTime = getCurrentTimeInMinutes();
            /* if currentTime is larger than freezeTime, that means freeze time of current day is
            already passed. Therefore need to set alarm in next day. */
            calendar = getCalendar(freezeTime, currentTime > freezeTime);
        } else {
            /* if releaseTime is larger than freezeTime, that means the next freezeTime comes in
            next day. Therefore need to set alarm in next day. */
            calendar = getCalendar(freezeTime, releaseTime > freezeTime);
        }
        pendingIntent = PendingIntent.getBroadcast(context, 55, receiverIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        Log.d(TAG, "Build alarm to restrict device to " + freezeTime + ":" + releaseTime);
    }
}

From source file:com.battlelancer.seriesguide.service.NotificationService.java

@SuppressLint("CommitPrefEdits")
@TargetApi(android.os.Build.VERSION_CODES.KITKAT)
@Override/*from   ww  w  .  ja  va2 s . co m*/
protected void onHandleIntent(Intent intent) {
    Timber.d("Waking up...");
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    /*
     * Handle a possible delete intent.
     */
    if (handleDeleteIntent(this, intent)) {
        return;
    }

    /*
     * Unschedule notification service wake-ups for disabled notifications
     * and non-supporters.
     */
    if (!NotificationSettings.isNotificationsEnabled(this) || !Utils.hasAccessToX(this)) {
        Timber.d("Notification service disabled, removing wakup-up alarm");
        // cancel any pending alarm
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(this, OnAlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        am.cancel(pi);

        resetLastEpisodeAirtime(prefs);

        return;
    }

    long wakeUpTime = 0;

    /*
     * Get pool of episodes which air from 12 hours ago until eternity which
     * match the users settings.
     */
    StringBuilder selection = new StringBuilder(SELECTION);
    boolean isFavsOnly = NotificationSettings.isNotifyAboutFavoritesOnly(this);
    Timber.d("Do notify about " + (isFavsOnly ? "favorites ONLY" : "ALL"));
    if (isFavsOnly) {
        selection.append(" AND ").append(Shows.SELECTION_FAVORITES);
    }
    boolean isNoSpecials = DisplaySettings.isHidingSpecials(this);
    Timber.d("Do " + (isNoSpecials ? "NOT " : "") + "notify about specials");
    if (isNoSpecials) {
        selection.append(" AND ").append(Episodes.SELECTION_NO_SPECIALS);
    }
    // always exclude hidden shows
    selection.append(" AND ").append(Shows.SELECTION_NO_HIDDEN);

    final long customCurrentTime = TimeTools.getCurrentTime(this);
    final Cursor upcomingEpisodes = getContentResolver().query(Episodes.CONTENT_URI_WITHSHOW, PROJECTION,
            selection.toString(),
            new String[] { String.valueOf(customCurrentTime - 12 * DateUtils.HOUR_IN_MILLIS) }, SORTING);

    if (upcomingEpisodes != null) {
        int notificationThreshold = NotificationSettings.getLatestToIncludeTreshold(this);
        if (DEBUG) {
            Timber.d("DEBUG MODE: notification threshold is 1 week");
            // a week, for debugging (use only one show to get single
            // episode notifications)
            notificationThreshold = 10080;
            // notify again for same episodes
            resetLastEpisodeAirtime(prefs);
        }

        final long nextEpisodeReleaseTime = NotificationSettings.getNextToNotifyAbout(this);
        // wake user-defined amount of time earlier than next episode release time
        final long plannedWakeUpTime = TimeTools.getEpisodeReleaseTime(this, nextEpisodeReleaseTime).getTime()
                - DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

        /*
         * Set to -1 as on first run nextTimePlanned will be 0. This assures
         * we still see notifications of upcoming episodes then.
         */
        int newEpisodesAvailable = -1;

        // Check if we did wake up earlier than planned
        if (System.currentTimeMillis() < plannedWakeUpTime) {
            Timber.d("Woke up earlier than planned, checking for new episodes");
            newEpisodesAvailable = 0;
            long latestTimeNotified = NotificationSettings.getLastNotified(this);

            // Check if there are any earlier episodes to notify about
            while (upcomingEpisodes.moveToNext()) {
                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime < nextEpisodeReleaseTime) {
                    if (releaseTime > latestTimeNotified) {
                        /**
                         * This will not get new episodes which would have
                         * aired the same time as the last one we notified
                         * about. Sad, but the best we can do right now.
                         */
                        newEpisodesAvailable = 1;
                        break;
                    }
                } else {
                    break;
                }
            }
        }

        if (newEpisodesAvailable == 0) {
            // Go to sleep, wake up as planned
            Timber.d("No new episodes, going to sleep.");
            wakeUpTime = plannedWakeUpTime;
        } else {
            // Get episodes which are within the notification threshold
            // (user set) and not yet cleared
            final List<Integer> notifyPositions = new ArrayList<>();
            final long latestTimeCleared = NotificationSettings.getLastCleared(this);
            final long latestTimeToInclude = customCurrentTime
                    + DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

            int position = -1;
            upcomingEpisodes.moveToPosition(position);
            while (upcomingEpisodes.moveToNext()) {
                position++;

                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime <= latestTimeToInclude) {
                    /*
                     * Only add those after the last one the user cleared.
                     * At most those of the last 24 hours (see query above).
                     */
                    if (releaseTime > latestTimeCleared) {
                        notifyPositions.add(position);
                    }
                } else {
                    // Too far into the future, stop!
                    break;
                }
            }

            // Notify if we found any episodes
            if (notifyPositions.size() > 0) {
                // store latest air time of all episodes we notified about
                upcomingEpisodes.moveToPosition(notifyPositions.get(notifyPositions.size() - 1));
                long latestAirtime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (!AndroidUtils.isHoneycombOrHigher()) {
                    /*
                     * Everything below HC does not have delete intents, so
                     * we just never notify about the same episode twice.
                     */
                    Timber.d("Delete intent NOT supported, setting last cleared to: " + latestAirtime);
                    prefs.edit().putLong(NotificationSettings.KEY_LAST_CLEARED, latestAirtime).commit();
                }
                Timber.d("Found " + notifyPositions.size() + " new episodes, setting last notified to: "
                        + latestAirtime);
                prefs.edit().putLong(NotificationSettings.KEY_LAST_NOTIFIED, latestAirtime).commit();

                onNotify(upcomingEpisodes, notifyPositions, latestAirtime);
            }

            /*
             * Plan next episode to notify about, calc wake-up alarm as
             * early as user wants.
             */
            upcomingEpisodes.moveToPosition(-1);
            while (upcomingEpisodes.moveToNext()) {
                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime > latestTimeToInclude) {
                    // store next episode we plan to notify about
                    Timber.d("Storing next episode time to notify about: " + releaseTime);
                    prefs.edit().putLong(NotificationSettings.KEY_NEXT_TO_NOTIFY, releaseTime).commit();

                    // calc actual wake up time
                    wakeUpTime = TimeTools.getEpisodeReleaseTime(this, releaseTime).getTime()
                            - DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

                    break;
                }
            }
        }

        upcomingEpisodes.close();
    }

    // Set a default wake-up time if there are no future episodes for now
    if (wakeUpTime <= 0) {
        wakeUpTime = System.currentTimeMillis() + 6 * DateUtils.HOUR_IN_MILLIS;
        Timber.d("No future episodes found, wake up in 6 hours");
    }

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(this, NotificationService.class);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    Timber.d("Going to sleep, setting wake-up alarm to: " + wakeUpTime);
    if (AndroidUtils.isKitKatOrHigher()) {
        am.setExact(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    }
}