我知道这个问题被问了十亿次,我确实尝试过使用答案,但这似乎无法像我期望的那样工作。我在通过 AlarmManager 设置警报时遇到问题 - 一切似乎都可以在 UTC(或 GMT - 无论你喜欢什么)下正常工作,但当涉及到其他时区时,警报不会在正确的时间触发。 如果我在 12:00 设置闹钟,如果我的时区是 (+2),它会在 14:00 触发,晚 2 小时。
这是一个 fragment :
//todays date in seconds
long current = (System.currentTimeMillis()/86400000)*86400;
long time =current + 43200;
alarmManager.set(AlarmManager.RTC_WAKEUP, time*1000,
operationBroadcast);
设备上的时间是早上 6:42 这是我在 alarmmanagers“转储”文件中找到的内容
RTC_WAKEUP #10: Alarm{420f49b8 type 0 com.pocketenergy.androidbeta}
type=0 when=+7h17m37s418ms repeatInterval=0 count=0
operation=PendingIntent{420f3b20: PendingIntentRecord{420f4808 com.pocketenergy.androidbeta broadcastIntent}}
据我在几个地方读到的,无论在实际设备上选择什么时区,时间都应该设置为 UTC,但我已经尝试了很多不同的日历,例如:
//todays date in seconds
long current = (System.currentTimeMillis()/86400000)*86400;
long time =current + 43200;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time*1000);
TimeZone timeZone= TimeZone.getTimeZone("UTC"); //also tried TimeZone.getDefault();
calendar.setTimeZone(timeZone);
time = cal.getTimeInMillis();
alarmManager.set(AlarmManager.RTC_WAKEUP, time,
operationBroadcast);
同样的结果。 想法,任何人? :)
最佳答案
所以,我终于让它工作了。这是代码:)
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, time, operationBroadcast);
关于java - 如果时区与 GMT(UTC) 不同,AlarmManager 会在错误的时间发出警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27013679/