Reset a sharedpreference at a specified time with alarmmanager

半腔热情 提交于 2019-12-23 04:29:11

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/18671714/reset-a-sharedpreference-at-a-specified-time-with-alarmmanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!