使用闹钟管理器启动服务

3

我有一些代码,想要每天早上3点执行一次。我已经阅读了Service类文档,似乎可以使用AlarmManager触发一个意图(Activity或Service),然后在该意图中创建并发布一个消息到Android通知区域。

Calendar threeAM = Calendar.getInstance();
threeAM.set(Calendar.HOUR_OF_DAY,2);
threeAM.set(Calendar.MINUTE,0);
threeAM.set(Calendar.SECOND,0);
threeAM.set(Calendar.MILLISECOND,0);
AlarmManager alarmManager =
         (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, myNotifier.class);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, threeAM.getTimeInMillis(),
        AlarmManager.INTERVAL_DAY, PendingIntent.getService(context, 1, i , 0));
Log.i("Service TEST", "Alarm set?" );

代码运行没有问题,但没有任何迹象表明警报已设置,并且活动没有启动。我使用的是一个我知道可用的活动。我尝试了try/catch包装,logcat中没有输出信息...

2个回答

2

1

你的代码只有在凌晨3点之前才能正常运行。否则,你将会设置一个过去的闹钟。


我在测试时尝试将其设置为提前几分钟。似乎启动时间应该在第一次启动活动,然后按照间隔参数重复,是这样吗?有没有办法检查设置了哪些闹钟? - tpow
@cinqoTimo: “看起来启动时间应该在第一次启动活动,然后重复间隔参数,是这样吗?” - 是的,尽管我从未使用AlarmManager来启动活动。 “有没有办法检查设置了哪些闹钟?” - 闹钟被深埋在dumpsys输出中的某个地方。http://developer.android.com/guide/developing/tools/adb.html#shellcommands - CommonsWare

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接