Can I set an end time for AlarmManager in Android?

ⅰ亾dé卋堺 提交于 2019-12-01 23:09:55

Is it possible to tell it after how many intervals to stop? Or even at what time to stop?

There's no way to specify an end time for an AlarmManager, but what you can do is, every time you receive your pending intent in your broadcast receiver, check to see if you need to cancel that alarm. To cancel the alarm, you need to call alarmManager.cancel(pendingIntent), where pendingIntent has the same requestCode that you used for the PendingIntent that you originally created the alarm with.

Also do i need to do anything to ensure it will go off every day?

You need to set the interval to: 1000 * 60 * 60 * 24 if you want it to fire once per day.

You also need to take care of the situation of a device reboot. If the user reboots the device, the alarms will be cleared and you need to recreate them. You will need to implement another BroadcastReceiver that listens for RECEIVE_BOOT_COMPLETED, and add logic in your onReceive() to recreate your alarms.

Also, this line is unnecessary:

calendar.setTimeInMillis(System.currentTimeMillis());

This line:

Calendar calendar = Calendar.getInstance();

already gives you a Calendar object set to the exact time you create it.

You should also add the following lines to make sure your alarm fires at exactly 13:56 each day:

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