本文介绍了在指定的时间与alarmmanager重置共享preference的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有存储共享preferences两个柜台,我需要在午夜其重置为零每天,我知道我必须使用alarmmanager,但我真的不知道我是如何做到这一点,我看着SO exemples并在谷歌文档,但无法找到一个方法来做到这一点。

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:

共享preferences.Editor编辑= counters.edit();
 editor.putInt(wcounter,wcounter);
 editor.commit();

我怎么能在午夜进行重置?

how can I reset them at midnight?

推荐答案

设置适当的地方报警在code:

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

添加 YourBroadcastReceiver 作为类和AndroidManifest。
YourBroadcastReceiver

Add YourBroadcastReceiver as class and in AndroidManifest.In YourBroadcastReceiver:

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

这篇关于在指定的时间与alarmmanager重置共享preference的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 21:07