Can I set an end time for AlarmManager in Android?

风流意气都作罢 提交于 2019-12-20 03:18:33

问题


I have set up an AlarmManager to go off at a specific time, and then repeat in intervals. Is it possible to tell it after how many intervals to stop? Or even at what time to stop?

This is what I have so far:

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 13);
    calendar.set(Calendar.MINUTE, 56);
    Intent intent = new Intent(this, MyService.class);
    alarmIntent = PendingIntent.getService(this, 0, intent, 0);
    alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            1000 * 60 * 60, alarmIntent);

Also do I need to do anything to ensure it will go off every day? Or is it already doing that?


回答1:


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);


来源:https://stackoverflow.com/questions/24501493/can-i-set-an-end-time-for-alarmmanager-in-android

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