【问题标题】:Reset a sharedpreference at a specified time with alarmmanager使用警报管理器在指定时间重置共享首选项
【发布时间】:2013-09-07 09:07:10
【问题描述】:

我有两个使用 sharedpreferences 存储的计数器,我需要在每天午夜将它们重置为零,我知道我必须使用 alarmmanager,但我真的不知道该怎么做,我查看了 SO 示例等谷歌文档,但找不到方法。

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

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

如何在午夜重置它们?

【问题讨论】:

    标签: android alarmmanager counter reset


    【解决方案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();
    }
    

    【讨论】:

    • 我必须把广播放在Manifest中??还是在 .java 中?
    • 两者。您需要添加 Java 类并将其注册到您的 AndroidManifest 中以向系统宣布它。它和 Activity 类似,但目的不同。
    • 我在任何地方都找不到如何将您编写的代码的第二部分放在清单中...:/
    • 不要将java代码放入xml中,需要在AndroidManifest.xml中注册receiver。请在d.android.com 上阅读有关 Android 开发的一些基本文档
    • 所以我将您的代码粘贴到了适当的位置,但仍然出现三个错误:cal.add(Calendar.DAY, 1);在这里我有 DAY 无法解决或者不是一个字段;我不知道如何将其更改为:YourBroadcastReceiver.class;在这个“Context.getSystemService(Context.ALARM_SERVICE)”上我有这个错误:无法从类型 Context 对非静态方法 getSystemService(String) 进行静态引用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    相关资源
    最近更新 更多