AlarmManager在同一天设置的时间过后触发警报setRepeating [英] AlarmManager firing alarm past the time it was set on the same day, setRepeating

查看:154
本文介绍了AlarmManager在同一天设置的时间过后触发警报setRepeating的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上我有这段代码,时间返回24小时时间,每天重复一次闹钟。

So basically I have this code, time returns 24hour time and repeats the alarm daily.

public setAlarm(String time, Context context){
    String[] strTime;

    strTime = time.split(":");

    int hour, min, sec;
    //set when to alarm
    hour = Integer.valueOf(strTime[0]);
    min = Integer.valueOf(strTime[1]);
    sec = 0;

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, hour);
    cal.set(Calendar.MINUTE, min);
    cal.set(Calendar.SECOND, sec);
    //Create a new PendingIntent and add it to the AlarmManager
    Intent intent = new Intent(context, AlarmReceiverActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 19248, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);
    am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}

无论如何,问题是我将闹钟设置为上午9点而时间是9点:10am,警报响起。为什么?我希望它不会在系统时间过后发出警报。例如将闹钟设置为上午9点,而系统时间是上午9:10。

Anyways, the problem is when I set the alarm 9am while the time is 9:10am, the alarm will go off. Why? I want it not to alarm if it is set past the system time. Ex. set the alarm at 9am while the system time is 9:10am

推荐答案

我现在开始工作了。我添加了警报时间和当前时间的检查器。

I got it working now. I added a checker of the alarm time and current time.

public setAlarm(String time, Context context){
        String[] strTime;

        strTime = time.split(":");

        int hour, min, sec;
        //set when to alarm
        hour = Integer.valueOf(strTime[0]);
        min = Integer.valueOf(strTime[1]);
        sec = 0;

        long _alarm = 0;
        Calendar now = Calendar.getInstance();
        Calendar alarm = Calendar.getInstance();
        alarm.set(Calendar.HOUR_OF_DAY, hour);
        alarm.set(Calendar.MINUTE, min);
        alarm.set(Calendar.SECOND, sec);

        if(alarm.getTimeInMillis() <= now.getTimeInMillis())
            _alarm = alarm.getTimeInMillis() + (AlarmManager.INTERVAL_DAY+1);
        else
            _alarm = alarm.getTimeInMillis();               

        //Create a new PendingIntent and add it to the AlarmManager
        Intent intent = new Intent(context, AlarmReceiverActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 19248, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager am = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP, _alarm, AlarmManager.INTERVAL_DAY, pendingIntent);
    }

这篇关于AlarmManager在同一天设置的时间过后触发警报setRepeating的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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