我的服务立即在我的闹钟管理器中启动

时间:2016-10-27 08:41:02

标签: java android alarmmanager

此方法位于扩展Service

的MyClass.java中
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    settPeriodicService = this;
    HOUR = 0;
    MINUTE = 0;
    message="Happy birthday!";
    if(running) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,HOUR);
        calendar.set(Calendar.MINUTE,MINUTE);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.DAY_OF_YEAR,1);
        Intent i = new Intent(this, MyService.class);
        PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
        AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
        running = true;
    }
    return super.onStartCommand(intent, flags, startId);
}

为什么MyService会立即启动?

1 个答案:

答案 0 :(得分:1)

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,HOUR);
calendar.set(Calendar.MINUTE,MINUTE);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.DAY_OF_YEAR,1);

以上日历表示过去的时间,因为您使用calendar.set(Calendar.DAY_OF_YEAR,1);将日期设置为1月1日。设置过去的时间将立即触发警报。

你可能想这样做:

calendar.add(Calendar.DAY_OF_YEAR,1);

将日历设置为明天。