我正在使用闹钟管理器在每天的特定时间运行闹钟。下面是代码
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点设置闹钟。下面是广播接收器的代码
@Override
public void onReceive(Context context, Intent intent)
{
System.out.println("Time is 12 Am");
Toast.makeText(context, "Alarm Triggered", Toast.LENGTH_LONG).show();
}
此代码中的问题是,无论时间如何,只要我运行应用程序,就会触发警报。任何帮助将不胜感激。谢谢
仅当您过去设置过闹钟时,闹钟才会立即触发。
例如。现在是 10:00,您想将闹钟设置为每天 09:00。为了避免这种情况,您必须查看现在是什么时间,如果是这种情况,请将闹钟移 1 天...这允许您使用setRepeating
方法(比setInexactRepeating
)
这解决了这个问题:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 00);
calendar.set(Calendar.MINUTE, 00);
if(Calendar.getInstance().after(calendar)){
// Move to tomorrow
calendar.add(Calendar.DATE, 1);
}
//... continue like before by setting the alarm
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)