使用alarmmanager在指定时间重置共享首选项

时间:2013-09-07 09:07:10

标签: android alarmmanager counter reset

我有两个计数器存储共享偏好,我需要每天午夜将它们重置为零,我知道我必须使用alarmmanager,但我不知道我该怎么做,我看了SO例子和谷歌文档但无法找到方法。

我拥有的两个计数器存储如下:

SharedPreferences.Editor editor = counters.edit(); editor.putInt("wcounter", wcounter); editor.commit();

如何在午夜重置它们?

1 个答案:

答案 0 :(得分:1)

在代码中的适当位置设置闹钟:

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

在课程和AndroidManifest中添加YourBroadcastReceiver。 在YourBroadcastReceiver

public void onReceive (Context context, Intent intent) {
    PreferenceManager.getDefaultSharedPreferences(context)
        .edit().remove("wcounter").commit();
}