2



AlarmManager()用来触发通知。我将它设置为在上午 10:30 开火,并每 24 小时重复一次。

我的代码如下。我昨天测试过,问题是它在接下来的 2 小时内重复了大约 4-5 次。我不明白这是什么问题。我只想在上午 10:30 开火,然后在 24 小时内重复。

请帮我解决问题。我在我的应用程序的初始屏幕上调用此代码我的onCreate()

代码:

Intent myIntent = new Intent(Splash.this, AlarmReceiver.class);

PendingIntent pendingIntent = PendingIntent.getBroadcast(Splash.this,
        0, myIntent, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

Calendar firingCal = Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();

firingCal.set(Calendar.HOUR_OF_DAY, 10);
firingCal.set(Calendar.MINUTE, 30);
firingCal.set(Calendar.SECOND, 0);

long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();

if (intendedTime >= currentTime) {
    alarmManager.setRepeating(AlarmManager.RTC, intendedTime,
            AlarmManager.INTERVAL_DAY, pendingIntent);

} else {
    firingCal.add(Calendar.DAY_OF_MONTH, 1);
    intendedTime = firingCal.getTimeInMillis();

    alarmManager.setRepeating(AlarmManager.RTC, intendedTime,
            AlarmManager.INTERVAL_DAY, pendingIntent);
}
4

2 回答 2

3

您可以使用 CommonsWare cwac-wakeful库。它具有设置警报的内置支持。

于 2013-06-10T05:42:13.720 回答
0
// Retrieve a PendingIntent that will perform a broadcast
            Intent alarmIntent = new Intent(HomeContactActivity.this,
                    AlarmReceiver.class);
            pendingIntent = PendingIntent.getBroadcast(
                    HomeContactActivity.this, 0, alarmIntent, 0);

            AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

            // Set the alarm to start at 10:00 AM
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.set(Calendar.HOUR_OF_DAY, 10);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);



            manager.setRepeating(AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(), 86400000, 
                    pendingIntent);  // for repeating in every 24 hours
于 2016-01-28T05:56:20.417 回答