在特定时间设置闹钟

4

我正在尝试在一天中的特定时间设置闹钟,例如:20:15。以下是我正在使用的代码,但它不会在20:15响起。

        Intent intent = new Intent(AlarmActivity.this, MyBroadcastReceiver.class);
        intent.putExtra("Hekma", "One better than none");
        PendingIntent pintent = PendingIntent.getService(AlarmActivity.this, 0,intent, 0);
        AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
        Calendar cal = Calendar.getInstance();



        cal.set(Calendar.HOUR_OF_DAY, 20);
        cal.set(Calendar.MINUTE, 15);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pintent);
2个回答

6

我在我的项目中使用了AlarmManager,它运行得非常完美。你可以尝试使用这个方法,也许会对你有所帮助:

Intent myIntent =  new Intent(MainActivity.this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager =  (AlarmManager) getSystemService(ALARM_SERVICE);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

这是静态的,日期选择器上的时间到了就会触发警报。 - Vijay Kahar

0

尝试

alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() - System.currentTimeMillis(), pintent);

这应该得到两个时间之间的差异,因此知道还有多长时间才能到达你想要它响起的时间。因此,它应该在你想要它响起的时间响起。


好的,我再次将其与我的闹钟代码进行比较。我唯一看到的另一个区别是你使用了"PendingIntent.getService(....;",而我使用的是"PendingIntent.getBroadcast(...."。请将alarm.set的参数设置回你之前的值,然后告诉我它是否有效。 - Richard Lewin
现在,无论我将时间设置为多少,更改为 PendingIntent.getBroadcast(...) 后它都会立即执行。 - Qassem AlBahdour
现在它可以工作了,我移除了(- System.currentTimeMillis()),非常感谢。 - Qassem AlBahdour

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接