So I want a variable to reset to 0 at a specific time of day. I got this part working.
But every time the app restarts, the alarm stops working.
I got a “TimePicker” that gets a time from the user and then this method is called.
public void setAlarmResetDose(long timeInMillis) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmResetTaken.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, timeInMillis, AlarmManager.INTERVAL_DAY, pendingIntent);
}
That method above calls the class “AlarmResetTaken” which is a “BroadcastReciver” class that runs the code to reset the variable.
But like I said this only work as long as the app is running. When the app restarts, the alarm only starts working again when the user puts in a new time with the “TimePicker”.
My attempt to solve the problem
I used the code from the TimePicker and saved it in a variable:
timeDoseResetTotal = calendar.getTimeInMillis();
I also used sharedPreferences to save this time.
Then in the MainActivity onCreate i loaded the sharedPreferences value and ran the method “setAlarmResetDose(timeDoseResetTotal);” (with that value).
However this don’t seems to work.
Anyone got any ideas on how I could get this to work? :/
Edit:
I created this method and called it in MainActivity onCreate.
public void startAlarmBroadcastReceiver() {
Calendar calendar = Calendar.getInstance();
calendar.set(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
timeDoseResetHour,
timeDoseResetHour,
0
);
setAlarmResetDose(calendar.getTimeInMillis());
Where "timeDoseResetHour" and "timeDoseResetMin" are loaded with SharedPreferences fromearlier. It now works if the user opens the app before the time, but not after. So i guess if you re-open the app after the specific time it goes of the next day instead. Any ideas? :)
AlarmManager.setExactAndAllowWhileIdle
appears to be the method you need. The tradeoff here is that you will need to reschedule this alarm each time it goes off.