我正在使用闹钟管理器在每天的特定时间运行闹钟。以下是代码
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 00);
calendar.set(Calendar.MINUTE, 00);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, OnAlarmReceive.class);
PendingIntent pendingIntent =PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
24*60*60*1000, pendingIntent);
我每天早上12点都设置闹钟。以下是BroadCastReciever的代码
@Override
public void onReceive(Context context, Intent intent)
{
System.out.println("Time is 12 Am");
Toast.makeText(context, "Alarm Triggered", Toast.LENGTH_LONG).show();
}
此代码中的问题是警报被触发一旦我运行应用程序而不考虑时间。任何帮助将不胜感激。谢谢
答案 0 :(得分:5)
如果您过去设置闹钟,闹钟只会立即触发。
例如。它现在是10:00h,你想每天09:00设置闹钟。为了避免这种情况,您必须查看它现在的时间,如果是这种情况,则将警报移动1天...这允许您使用setRepeating
方法(比{{1}更精确})
这解决了问题:
setInexactRepeating
答案 1 :(得分:4)
我遇到了和你一样的问题,我无法让它发挥作用。此外,我能找到的所有例子也都设定了一个特定的日期,而不仅仅是一个时间。这应该适合你:
Intent myIntent = new Intent(ThisActivity.this , NotifyService.class);
AlarmManager alarmManager = (AlarmManager) Context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(ThisActivity.this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pendingIntent); //Repeat every 24 hours
希望这可以帮助您解决问题!
答案 2 :(得分:2)
尝试使用它:
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,
AlarmManager.INTERVAL_DAY, intent);
答案 3 :(得分:2)
您可以使用以下内容:
Calendar cal = Calendar.getInstance();
if(cal.getTimeInMillis() < System.currentTimeMillis()) {
cal.add(Calendar.DAY_OF_YEAR, 7);
}