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

问题描述 投票:0回答:1

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

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);
}

alarm reset food added.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,因为它是在ExactRepeating中,但是首选项文件中的关键foodAdded保持不变,即使我重新打开应用程序也是如此。

我很确定警报已经启动,因为当我调试alarmUp时,第一次该值为false,然后当我重新打开它时,这是真的。

java android sharedpreferences alarmmanager repeatingalarm
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.