使用重复警报编辑共享首选项

时间:2019-03-10 00:41:39

标签: java android sharedpreferences alarmmanager repeatingalarm

我想在一天结束时更改共享首选项文件的一个键。所以这是我在网上找到的东西:

boolean alarmUp = (PendingIntent.getBroadcast(this, 0,
                    new Intent(this, AlarmResetFoodAdded.class),
                    PendingIntent.FLAG_NO_CREATE) != null);
if (!alarmUp) {
    setAlarm();
}

函数setAlarm():

private void setAlarm() {
    alarmMgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, AlarmResetFoodAdded.class);
    alarmIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 14);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
         AlarmManager.INTERVAL_DAY, alarmIntent);
}

AlarmResetFoodAdded.java:

@Override
public void onReceive(Context context, Intent intent)
{
    pref = context.getSharedPreferences(AppControl.PREF, Activity.MODE_PRIVATE);
    prefEditor = pref.edit();

    prefEditor.putInt("foodAdded", 0);
    prefEditor.commit();
}

我正在使用具有API 28的设备模拟器对其进行测试。我试图将时间设置为大约13:59。然后我要等到14:01左右,因为它是inExactRepeating,但是即使重新打开应用程序,首选项文件中的关键foodAdded也保持不变。

我非常确定警报已启动,因为当我调试alarmUp时,该值第一次为false,然后当我重新打开它时,它为true。

1 个答案:

答案 0 :(得分:0)

我认为您应该在onReceive方法中使用prefEditor.apply();而不是prefEditor.commit();