I have two counters stored with sharedpreferences and I need to reset them to zero everyday at midnight, I know I have to use alarmmanager but I don't really know how I have to do it, I looked at SO exemples and on the google documentation but can't find a way to do it.
the two counters I have are stored like this:
SharedPreferences.Editor editor = counters.edit();
editor.putInt("wcounter", wcounter);
editor.commit();
how can I reset them at midnight?
Set the alarm somewhere appropriate in your code:
private void schedAlarm(Context context) {
Calendar cal = Calendar.getInstace();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.DAY_OF_MONTH, 1);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, new Intent(context, YourBroadcastReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*60*60*24, pi);
}
Add YourBroadcastReceiver
as class and in AndroidManifest.
In YourBroadcastReceiver
:
public void onReceive (Context context, Intent intent) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit().remove("wcounter").commit();
}