开发者

AlarmManager not setting, Alerting everytime activity is opened

开发者 https://www.devze.com 2023-04-01 01:11 出处:网络
I am trying to use this to set an alarm that goes off everyday. String alarm = Context.ALARM_SERVICE; Calendar calendar = Calendar.getInstance();

I am trying to use this to set an alarm that goes off everyday.

String alarm = Context.ALARM_SERVICE;
                Calendar calendar = Calendar.getInstance();
                AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm);

                    Intent intent = new Intent("NEW_ITEM");
                    PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
                     calendar.setTimeInMillis(System.currentTimeMillis());
                     am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1*AlarmManager.INTERVAL_DAY, sen开发者_开发百科der);


Without running it, the code looks good to me... Obviously, if you set this alarm every time you start the activity, the alarm will go off immediately since: am.setRepeating(AlarmManager.RTC_WAKEUP, **calendar.getTimeInMillis()**, 1*AlarmManager.INTERVAL_DAY, sender); Tells the alarm manager to alert right now (2nd param) and to repeat in a day (3rd param, assuming your constant is correct).

If you want the alert to start only in 24 hours, simply change the line to:

am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, sender);


Code looks good, but you have to be aware of one thing. If the user decides to set the alarm again (for example, by hitting the 'set the alarm' button) the old one will be replaced. If you want to avoid this, check out this topic: Using Alarmmanager to start a service at specific time

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号