在Android中设置每天特定时间的重复警报 [英] Set Repeating Alarm Every Day at Specific time In Android
问题描述
我每天使用警报管理器在特定时间运行警报。下面是代码
I am using Alarm manager to run alarm at specific time every day. Below is the code
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的代码
I am Setting alarm at 12AM every day. And Below is the code for 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();
}
此代码中的问题是在我运行应用程序后立即触发警报时间。任何帮助将不胜感激。谢谢
Problem in this code is Alarm is Triggered As soon as i Run the Application Irrespective of time. Any help will be Appreciated. Thank You
推荐答案
仅当您将警报设置为过去时,警报才会立即触发。
例如现在是10:00h,您想每天在09:00设置闹铃。为避免这种情况,您必须查看现在的时间,如果是这种情况,则将警报更改为1天。这允许您使用 setRepeating
方法(
The alarm will only fire immediately if you set the alarm in the past.
E.g. it is now 10:00h and you want to set an alarm every day at 09:00. To avoid this, you have to look what time it is now, and shift the alarm 1 day if that is the case... This allows you to use the setRepeating
method (which is more precise than setInexactRepeating
)
这比 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
这篇关于在Android中设置每天特定时间的重复警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!