我需要每天早上5点运行我的更新服务,以便在用户拿起手机时刷新数据。我到目前为止的代码是 -
Log.d(TAG, "setAutoRun");
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, RefreshIntentService.class);
PendingIntent pendingI = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, 60); // this was just to test out the alarm service
alarmMgr.set(AlarmManager.RTC, time.getTimeInMillis(), pendingI);
如何修改它,每天早上凌晨5点运行? 我知道我可以设置一个间隔,以便它在X分钟内再次运行,但是如果用户不打开它,我怎么能在凌晨5点开始它。
谢谢
答案 0 :(得分:4)
我认为像这样编辑Calendar params
应该有效,并改为setRepeating()
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 5);
alarmMgr.setRepeating(AlarmManager.RTC, time.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingI);
答案 1 :(得分:0)
你可以使用setRepeating方法,在其中你可以传递特定的时间。看这个例子:
private void scheduleAlarms() {
Intent intent = new Intent(mContext, AlarmActivity.class);
mPendMorInt = PendingIntent.getActivity(
mContext, Constants.ALARM_MORNING_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT);
mPendAftInt = PendingIntent.getActivity(
mContext, Constants.ALARM_AFTERNOON_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT);
List<Long> alarms = SelectorAlarm.timeAlarms(mContext);
if (alarms.size() >= 1) {
mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, getRightTimeAlarm(alarms.get(Constants.MORNING)),
AlarmManager.INTERVAL_DAY, mPendMorInt);
mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, getRightTimeAlarm(alarms.get(Constants.AFTERNOON)),
AlarmManager.INTERVAL_DAY, mPendAftInt);
}
}