Daily notifications at specific times

I would like to achieve this:

After the first inclusion of the application, the user receives notifications every day at 2 p.m. if a certain condition is true. If the condition is false, we do not show a notification on this day. The condition is checked at 2 pm, it downloads some data from the Internet.

So far I have used AlarmManager and its setRepeating () method with an interval of 24 hours. AlarmManager starts the Service . In this service, I load data, checking the condition, and if it is true, Notification is displayed. Since the download may take more than 5 seconds, I declared android:process=":background" for this service, to run it in a separate process, and not block my user interface.

This approach has two drawbacks:


1: If the user opens the application, say at 4 pm (and the condition is true), he will receive a notification immediately . From setRepeating ():

If the time is in the past, the alarm is triggered immediately, with an alarm counting, depending on how far in the past the response time relative to the repetition interval.

I would like this user not to receive notifications on this day, only the next day, etc.


2: I am worried that my notifications will not be displayed after the user turns off the phone. From AlarmManager documentation:

The registered alarms are saved when the device is asleep (and, if necessary, can activate the device if it is turned off during this time), but will be cleared if it is turned off and rebooted.

I do not know if it is possible to make it work all the time.


If you have ideas on how to do this better, please.

+7
source share
1 answer

1: I'm not quite sure if I understood your question, but I think that all you need to do is that 2 hours have passed, add a day until 2 pm:

 GregorianCalendar twopm = new GregorianCalendar(); twopm.set(GregorianCalendar.HOUR_OF_DAY, 14); twopm.set(GregorianCalendar.MINUTE, 0); twopm.set(GregorianCalendar.SECOND, 0); twopm.set(GregorianCalendar.MILLISECOND, 0); if(twopm.before(new GregorianCalendar())){ twopm.add(GregorianCalendar.DAY_OF_MONTH, 1); } alarmManager.setRepeating(type, twopm.getTimeInMillis(), 1000*60*60*24, intent); 

2: You can register BroadcastReceiver to download and start your alarm again. Take a look at this: Android BroadcastReceiver on startup - keep running when Activity is in the background

+6
source

All Articles