问题描述
我想制作时间或日期侦听器,例如每天在上午9点调用活动.我不确定这是什么最好的方法吗?我知道我可以使用警报经理,但我不知道如何使它重复?
有谁知道?非常感谢你提前.
欢呼:)
推荐答案
我知道我可以使用警报管理器,但我不知道如何使它重复?
使用 setRepeating() ,并指定 INTERVAL_DAY :
static void scheduleAlarms(Context ctxt) { AlarmManager mgr=(AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE); Intent i=new Intent(ctxt, ScheduledService.class); PendingIntent pi=PendingIntent.getService(ctxt, 0, i, 0); mgr.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, pi); }
上面的代码将设置一个警报,即在现在距离现在和此后每24小时开始24小时.要在上午9点开始,请用RTC替换ELAPSED_REALTIME并用9am(今天或明天)替换SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,例如通过Calendar对象.
问题描述
I want to make a time or date listener which for example invoke an activity every day at 9 AM. I am not sure what is the best way to do that? I know I can use Alarm Manager, but I don't know how to make it repetitive?
Does anyone know? Thank you very much in advance.
Cheer :)
推荐答案
I know I can use Alarm Manager, but I don't know how to make it repetitive?
Use setRepeating() and specify a repeat interval of INTERVAL_DAY:
static void scheduleAlarms(Context ctxt) { AlarmManager mgr=(AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE); Intent i=new Intent(ctxt, ScheduledService.class); PendingIntent pi=PendingIntent.getService(ctxt, 0, i, 0); mgr.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, pi); }
The above code will set up an alarm that will go off 24 hours from right now and every 24 hours thereafter. To have it start at 9am, replace ELAPSED_REALTIME with RTC and replace SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY with 9am (today or tomorrow), such as via a Calendar object.