11

I want to create a Notification each Day at 8:00am. I have some data in a SQLite database and every day at this time I want to get the data from it and create a notification from it. The creation of a new notification is no problem but how can I display it every day at this time?

I think I have to work with a Service but how can I tell the system to start this service at the special moment? And what kind of Service should I use? I think if the system calls the service it starts a specific function where I can run my code to connect to the database and create and send my notification to the system right?

What I can't understand is if I register the service in my main Activity why can the system start the service if the user close my app? Can anyone explain that to me? I allways think if my main Activity is destroyed the service is destroyed, too.

Cilenco
  • 6,951
  • 17
  • 72
  • 152

2 Answers2

7

Use the Alarm manager class and put the notification in a NotifyService class. This will set an alarm at 8am everyday:

Intent myIntent = new Intent(Current.this , NotifyService.class);     
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(ThisApp.this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 08);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , pendingIntent);  //set repeating every 24 hours
Buneme Kyakilika
  • 1,202
  • 3
  • 13
  • 34
  • I have same settings still i am getting notification every hour instead of once a day. – Roon13 Feb 09 '16 at 15:00
  • This will work until user reboots his phone. To keep AlarmManager working even after reboot, check this post http://stackoverflow.com/questions/12512717/android-alarmmanager-after-reboot – Vikram Singh Mar 08 '16 at 11:40
  • 1
    Same here... It is not sending once a day but everytime i open the app – Si8 Nov 26 '16 at 21:09
  • pre-defined AlarmManager.INTERVAL_DAY can be used instead of 24*60*60*1000, reduces the chances of error... – ked Dec 11 '16 at 06:09
2

You do not need a server. I think the best way to implement this is to use AlarmManager.

Alarm Manager Example

Community
  • 1
  • 1
dongshengcn
  • 6,434
  • 7
  • 35
  • 44