Alarm everyday at 5AM morning

2020-08-05 11:14发布

I am working on an android application where I need to trigger an alarm every morning at 5 am. I have already used the concept of Intent(below is the code) and putting AlarmManager in the Service. But I didnt get the problem solution from both implementations. I am just looking for a perfect solution for this. If I add a reminder to the calendar for 1 month once the application is opened for the first time I guess that might work. But if there is any better solution for this, then please provide. It should trigger an alarm at 5 AM every day no matter what. How can I achieve this?

alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent alarmIntent = new Intent(this, MyStartServiceReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 5);
        calendar.set(Calendar.MINUTE, 5);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.AM_PM, Calendar.AM);
        if (System.currentTimeMillis() > calendar.getTimeInMillis()) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        alarmManager.cancel(pendingIntent);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

2条回答
倾城 Initia
2楼-- · 2020-08-05 11:40

try to change the following things

  1. change the alarm type from inexactrepeating to repeating
  2. change calendar.add(Calendar.DAY_OF_MONTH, 1); to calendar.add(Calendar.DATE,1);

let me know if this works.

查看更多
一夜七次
3楼-- · 2020-08-05 11:43

you need to implement services: https://developer.android.com/guide/components/services.html

Moreover, you may find many tutorials on implementing services in app

查看更多
登录 后发表回答