Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Everyday notifications at certain time

I would like to achieve this:

After first turning on the application, user receives notifications, every day at 2pm, if certain condition is true. If condition is false, we are not showing a notification this day. The condition is checked at 2pm, it downloads some data from the Internet.

So far I used AlarmManager and its method setRepeating() with 24h interval. AlarmManager fires up a Service. In this Service I'm downloading the data, checking condition and if it's true - showing Notification. Since downloading can last more than 5 seconds, I've declared android:process=":background" for this Service, to run it in separate process and not block my UI.

This approach has two drawbacks:


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

If the time occurs in the past, the alarm will be triggered immediately, with an alarm count depending on how far in the past the trigger time is relative to the repeat interval.

I would like that user will not receive a notification this day, only the next day and so on.


2: I'm worried that my notifications will not show after user switch the phone off. From AlarmManager documentation:

Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.

I don't know if it's possible to make it work all the time.


If you have any ideas how to make it better, you're welcome.

like image 523
Adam Stelmaszczyk Avatar asked Aug 25 '12 20:08

Adam Stelmaszczyk


People also ask

How do I set Android notifications for a specific date in the future?

This example demonstrate about How to set an Android notification to a specific date in the future. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


1 Answers

1: I'm not quite sure if i understood your question, but I think all you have to do is if it already is past 2pm add a day to 2pm:

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 could register a BroadcastReceiver for booting and start your alarm again there. Take a look at this: Android BroadcastReceiver on startup - keep running when Activity is in Background

like image 100
AntonS Avatar answered Oct 07 '22 15:10

AntonS