vadber
vadber

Reputation: 239

How to show Android Notification within a timeframe

I want to show a notification every 15 minutes only between 8:00 and 16:00. Here is the code:

        Calendar calendar = Calendar.getInstance();
        Calendar calendarStartOfTheDay = Calendar.getInstance();
        Calendar calendarEndOfTheDay = Calendar.getInstance();

        calendarStartOfTheDay.set(Calendar.HOUR_OF_DAY, 8);
        calendarStartOfTheDay.set(Calendar.MINUTE, 0);
        calendarStartOfTheDay.set(Calendar.SECOND, 0);

        calendarEndOfTheDay.set(Calendar.HOUR_OF_DAY, 16);
        calendarEndOfTheDay.set(Calendar.MINUTE, 0);
        calendarEndOfTheDay.set(Calendar.SECOND, 0);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        if (alarmManager != null && calendar.getTimeInMillis() > calendarStartOfTheDay.getTimeInMillis() && calendar.getTimeInMillis() < calendarEndOfTheDay.getTimeInMillis()) {
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + 15 * 60 * 1000, AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
        }

Is there a solution except checking the current time before notificationManager.notify() If this is the only solution, wouldn't it drain your battery too much during the night?

Upvotes: 0

Views: 105

Answers (1)

Rajat Beck
Rajat Beck

Reputation: 1633

This can be done by job scheduler in android. As alarm manager is outdated and no longer used. Job scheduler also provide you with the flexibility of scheduling the task to run under specific conditions, such as:

Device is charging

Device is connected to an unmetered network

Device is idle

Start before a certain deadline

Start within a predefined time window, e.g., within the next hour

Start after a minimal delay, e.g., wait a minimum of 10 minutes

you can follow this link to implement this

https://medium.com/google-developers/scheduling-jobs-like-a-pro-with-jobscheduler-286ef8510129

Upvotes: 1

Related Questions