在特定时间每天重置整数

时间:2016-10-09 13:05:52

标签: java android android-studio-2.0

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

接收者:

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

主要活动中的共享偏好设置:

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

1 个答案:

答案 0 :(得分: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);

广播接收器应与上述相同。 而且不要忘记将接收器添加到清单中:

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