每天在特定时间重置整数

Reset integer daily, in specific time

我需要在一天中特定的时间重置一个整数 "daily"。在我的 activity 中,我将 daily 的值写入共享首选项,然后使用警报管理器和广播接收器尝试将其设置为零。一切正常,除了共享偏好之外,价值仍然保持原样。我认为我需要为共享首选项导入不同的上下文。欢迎任何帮助。

接收者:

 public void onReceive(Context context, Intent intent) {

    final SharedPreferences shared =  context.getSharedPreferences("Mydata", MODE_PRIVATE);
    final SharedPreferences.Editor editor = shared.edit();
    int sum = shared.getInt("data1", 0);
    Calendar c = Calendar.getInstance();
    String date = String.valueOf(c.get(Calendar.DATE));

    mainData.insert_data(date, sum);
    int zero = 0;
    editor.putInt("data1", zero);
    editor.apply();

}

报警管理员:

Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 22);
        calendar.set(Calendar.MINUTE, 45);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        final Context context = this.getContext();
        PendingIntent pi = PendingIntent.getService(context, 0,
                new Intent(context, MyAppReciever.class),PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, pi);

主要Activity中的共享首选项:

final SharedPreferences shared = this.getContext().getSharedPreferences("Mydata", MODE_PRIVATE);
        final SharedPreferences.Editor editor = shared.edit();
        editor.putInt("data1", 0);
        editor.putInt("month", 0);
        final int today212 = shared.getInt("data1", 0);
        final int mesec212 = shared.getInt("month", 0);
        final int limit212 = shared.getInt("budget", 0);

所以我对代码做了一些修改,添加了一个PendingIntent requestCode。 代码看起来像这样

设置闹钟的地方:

public void scheduleTestAlarmReceiver(Context context) {
    Intent receiverIntent = new Intent(context, MyAppReciever.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, 123456789, receiverIntent, 0);
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 58);

    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, sender);
}

以及您安排它的位置(比如 onClick):

Context cn= this.getContext();
        scheduleTestAlarmReceiver(cn);

Broadcast receiver应该和上面一样。 并且不要忘记将接收器添加到清单中:

<receiver android:name=".MyAppReciever"></receiver>