创建应用程序时设置重复警报 - 为什么会立即触发

时间:2013-06-27 16:08:47

标签: android android-alarms

我在清单中声明了一个应用程序对象,此代码在应用程序运行时运行。我想要完成的是设置一个警报:

@Override
public void onCreate() {

    super.onCreate();
    singleton = this;
    persister = new Persister();
    am = (AlarmManager) getSystemService(ALARM_SERVICE);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPref.registerOnSharedPreferenceChangeListener(this);
    registerAlarms();
}

public void registerAlarms() {

    String sleepString = sharedPref.getString("time_sleepLog", "08:00");
    String[] pieces = sleepString.split(":");
    int sleepHour = Integer.parseInt(pieces[0]);
    int sleepMinute = Integer.parseInt(pieces[1]);

    String eveningString = sharedPref.getString("time_eveningLog", "20:00");
    pieces = null;
    pieces = eveningString.split(":");
    int eveningHour = Integer.parseInt(pieces[0]);
    Log.v(TAG, "eveningHour in registerAlarms: " + eveningHour);
    int eveningMinute = Integer.parseInt(pieces[1]);
    // create calendar objects pointing to the next time this clock will
    // occur
    Calendar sleepCal = Calendar.getInstance();
    sleepCal.set(Calendar.HOUR_OF_DAY, sleepHour);
    sleepCal.set(Calendar.MINUTE, sleepMinute);
    sleepCal.set(Calendar.SECOND, 0);

    Calendar eveningCal = Calendar.getInstance();
    eveningCal.set(Calendar.HOUR_OF_DAY, eveningHour);
    eveningCal.set(Calendar.MINUTE, eveningMinute);
    sleepCal.set(Calendar.SECOND, 0);
    Intent syncIntent = new Intent(this, SleepNotificationReceiver.class);
    syncIntent.putExtra("MoodSleepLogAlarm", 0);
    PendingIntent sleepPending = PendingIntent.getBroadcast(this, 0,
            syncIntent, 0);
    // then set the alarms
    am.setRepeating(AlarmManager.RTC_WAKEUP, sleepCal.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, sleepPending);
    Log.v(TAG, "Alarm for sleep registered at " + sleepCal.getTime());
    }

我登录broadcastreceiver以检查它是否以:

运行
Log.v(TAG, "Context: " + context.getClass().getName())

我可以在启动应用程序后4秒内在logcat中看到这个0

6-27 17:59:29.492: V/SleepNotificationReceiver(2609): Context: android.app.ReceiverRestrictedContext

当我通过按钮调用registerAlarms()时,它不会发生。所以只有在调用onCreate时才会这样。

为什么它会在4秒后运行广播接收器?(它还会在我的设置屏幕中以给定时间给出相同的上下文运行广播接收器 - 但我需要它在不运行时运行我设定了它。)

1 个答案:

答案 0 :(得分:3)

当您设置警报重复时,第二个参数指示警报何时必须关闭,所以我认为如果您键入sleepCal.getTimeInMillis()并且您处于“未来”与此时相比,警报瞬间消失。

检查第二个参数是否在将来,因为我认为您没有在日历中设置日期或月份。