AlarmManager to fire notification at every 24 hours

廉价感情. 提交于 2019-12-08 01:50:45

问题




I am using AlarmManager() to fire Notification. I am setting it to fire at 10:30 AM of the morning and repeat at every 24 hours.

My code is as follow. I have tested yesterday and the problem is that It was repeated around 4-5 times in just next 2 hours. I am not understanding that what is the problem. I want to fire it only at 10:30 AM of the morning and repeat at only 24 hours.

Please help me solve the problem. I am calling this code on my app's Splash screen onCreate()

My Code :

Intent myIntent = new Intent(Splash.this, AlarmReceiver.class);

PendingIntent pendingIntent = PendingIntent.getBroadcast(Splash.this,
        0, myIntent, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

Calendar firingCal = Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();

firingCal.set(Calendar.HOUR_OF_DAY, 10);
firingCal.set(Calendar.MINUTE, 30);
firingCal.set(Calendar.SECOND, 0);

long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();

if (intendedTime >= currentTime) {
    alarmManager.setRepeating(AlarmManager.RTC, intendedTime,
            AlarmManager.INTERVAL_DAY, pendingIntent);

} else {
    firingCal.add(Calendar.DAY_OF_MONTH, 1);
    intendedTime = firingCal.getTimeInMillis();

    alarmManager.setRepeating(AlarmManager.RTC, intendedTime,
            AlarmManager.INTERVAL_DAY, pendingIntent);
}

回答1:


You can use CommonsWare cwac-wakeful library. It has an inbuilt support to set alarms.




回答2:


// Retrieve a PendingIntent that will perform a broadcast
            Intent alarmIntent = new Intent(HomeContactActivity.this,
                    AlarmReceiver.class);
            pendingIntent = PendingIntent.getBroadcast(
                    HomeContactActivity.this, 0, alarmIntent, 0);

            AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

            // Set the alarm to start at 10:00 AM
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.set(Calendar.HOUR_OF_DAY, 10);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);



            manager.setRepeating(AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(), 86400000, 
                    pendingIntent);  // for repeating in every 24 hours


来源:https://stackoverflow.com/questions/17017395/alarmmanager-to-fire-notification-at-every-24-hours

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!