0

我有两个使用共享首选项存储的计数器,我需要每天午夜将它们重置为零,我知道我必须使用警报管理器,但我真的不知道该怎么做,我查看了 SO 示例和谷歌文档但找不到办法。

我拥有的两个计数器是这样存储的:

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

我怎样才能在午夜重置它们?

4

1 回答 1

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

添加YourBroadcastReceiver为类并在 AndroidManifest 中。在YourBroadcastReceiver

public void onReceive (Context context, Intent intent) {
    PreferenceManager.getDefaultSharedPreferences(context)
        .edit().remove("wcounter").commit();
}
于 2013-09-07T09:32:22.120 回答