如何为特定的日期,小时,分钟和秒设置AlarmManager

时间:2018-06-29 09:13:12

标签: java android datetime time java-time

警报在指定时间不起作用 (2018年12月20日,12:10:02)

此代码有什么问题?

Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH,12);
c.set(Calendar.YEAR,2018);
c.set(Calendar.DAY_OF_MONTH,20);
c.set(Calendar.HOUR_OF_DAY,12);
c.set(Calendar.MINUTE,10);
c.set(Calendar.SECOND,2);

Intent intent = new Intent(ProfileList.this, IntentBroadcastedReceiver.class);
PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 30*1000, pintent);

3 个答案:

答案 0 :(得分:4)

改为使用java.time API:

  

LocalDateTime用于表示日期和时间的组合。

import java.time;

LocalDateTime ldt = LocalDateTime.of(2018, Month.DECEMBER, 20, 12, 10);
// or just parse it from string:
LocalDateTime ldt2 = LocalDateTime.parse("2018-12-20T12:10:00");

// after that, you can get millis for your zone this way:
ZonedDateTime zdt = ldt.atZone(ZoneId.of("America/Los_Angeles"));
long currentTimeMillis = zdt.toInstant().toEpochMilli();

//... your code
alarm.setRepeating(AlarmManager.RTC_WAKEUP, currentTimeMillis, 30*1000, pintent);

有关数据的信息,请参阅此指南: http://www.baeldung.com/java-8-date-time-intro

对于26之前的Android,请使用 ThreeTenABP 项目,该项目改编了 ThreeTen-Backport 项目,该项目将许多 java.time Java 6和7的功能。

答案 1 :(得分:1)

我知道了,月份从0开始。应该是:

c.set(Calendar.MONTH,11); //December

答案 2 :(得分:0)

以下代码对我有用:

 // for Alarm 15/09/2018 at 12.00   
 Calendar myAlarmDate = Calendar.getInstance();
 myAlarmDate.setTimeInMillis(System.currentTimeMillis());
 myAlarmDate.set(2012, 09, 15, 12, 00, 0);
 AlarmManager alarmManager = (AlarmManager)

 context.getSystemService(Context.ALARM_SERVICE);

 Intent _myIntent = new Intent(context,AlarmReceiverNotificationForEveryMonth.class);
 _myIntent.putExtra("MyMessage","HERE I AM PASSING THEPERTICULAR MESSAGE WHICH SHOULD BE SHOW ON RECEIVER OF ALARM");
 PendingIntent _myPendingIntent = PendingIntent.getBroadcast(context, 123, _myIntent,PendingIntent.FLAG_UPDATE_CURRENT);
 alarmManager.set(AlarmManager.RTC_WAKEUP, myAlarmDate.getTimeInMillis(),_myPendingIntent);

希望它能对您有所帮助。