I am trying to change one key of the shared preferences file at the end of the day. So here is what I managed to find on the internet:
boolean alarmUp = (PendingIntent.getBroadcast(this, 0,
new Intent(this, AlarmResetFoodAdded.class),
PendingIntent.FLAG_NO_CREATE) != null);
if (!alarmUp) {
setAlarm();
}
Function 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();
}
I am testing this using the device simulator with API 28. I tried to set the time to about 13:59. Then I'd wait until about 14:01 because it is inExactRepeating, but the key foodAdded in the preferences file stay the same, even when I reopen the app.
I'm pretty sure the alarm is up because when I debug alarmUp, the value is false the first time, then when I reopen it, it is true.
I think you should use prefEditor.apply();
instead of prefEditor.commit();
in your onReceive method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.