Create Notification each day

2019-03-25 09:49发布

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.

2条回答
萌系小妹纸
2楼-- · 2019-03-25 10:29

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
查看更多
Emotional °昔
3楼-- · 2019-03-25 10:55

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

Alarm Manager Example

查看更多
登录 后发表回答