简体   繁体   English

AlarmManager立即触发警报(不应触发)

[英]AlarmManager fires alarm immediately (while it shouldn't)

I have a scheduleAlarm class which is supposed to set the alarm in a specific time, however the alarm is being fired immediately after the method is called. 我有一个scheduleAlarm类,应该在特定时间设置警报,但是在调用该方法后立即触发警报。 I've checked that provided time in milliseconds is fine, so I've no idea what's going on. 我检查了以毫秒为单位的时间是否合适,所以我不知道发生了什么。

private void scheduleAlarm(int day, int startHour, int startMinute, String info) {

    AlarmManager mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    Calendar c = Calendar.getInstance();

    c.set(Calendar.DAY_OF_WEEK, day);
    c.set(Calendar.HOUR, startHour);
    c.set(Calendar.MINUTE, startMinute);

    Intent startIntent = new Intent(this, Recorder.class);
    startIntent.putExtra("info", "someinfo");

    Log.v("millis", String.valueOf(c.getTimeInMillis())); // time is okay
    Random mRandom = new Random();
    int randomInt = mRandom.nextInt();

    PendingIntent pendingIntent = PendingIntent.getService(this, randomInt, startIntent,PendingIntent.FLAG_UPDATE_CURRENT);
    mAlarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
}

Just make sure that the time set for the alarm is after current time. 只要确保为闹钟设置的时间在当前时间之后即可。

There is an easy way to check that. 有一个简单的方法来检查。

just do 做就是了

Calendar.getInstance().getTimeInMilis() - c.getTimeInMillis()

Log this result, and you can see if the second is before the first. 记录此结果,您可以查看第二个结果是否在第一个之前。 Lets say now is 4 o'clock, and you set the same day and 3 o'clock. 可以说现在是凌晨4点,而您将当天设为凌晨3点。 it will get activated instantly. 它会立即被激活。

Other than that i see no reason why it should fail. 除此之外,我没有理由认为它应该失败。

Another way to test would be to use currentTime and add lets say 10k miliseconds and see if it activates in 10 seconds after you test it. 测试的另一种方法是使用currentTime并添加10k毫秒,然后在测试后10秒内查看它是否激活。 Then you are sure that the time set is wrong in your case. 然后,您可以确定时间设置对您而言是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM