在Android中每天在特定时间设置重复警报 [英] Set Repeating Alarm Every Day at Specific time In Android

查看:38
本文介绍了在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:00,您想在每天 09:00 设置闹钟.为避免这种情况,您必须查看现在是什么时间,如果是这种情况,则将闹钟移动 1 天...这允许您使用 setRepeating 方法(比 setRepeating 方法更精确代码>setInexactRepeating)

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)

这解决了问题:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆