以下是代码:
//From on create of normal activty
intent = new Intent(context, UpdateScoresService.class);
recurringDownloadDaily = PendingIntent.getService(context,0,intent, 0);
recurringDownloadWeekly = PendingIntent.getService(context, 1, intent, 0);
public static class MyPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(final Bundle savedInstanceState){
final ListPreference background_refresh = (ListPreference) findPreference("background_refresh");
Preference.OnPreferenceChangeListener refreshListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(newValue.toString().equals("1")){ /* daily */
background_refresh.setSummary("Scores will be refreshed daily");
AlarmManager manager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
manager.cancel(recurringDownloadDaily);
Log.e("DAILY REFRESH", " ");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,10);
calendar.set(Calendar.MINUTE,00);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, recurringDownloadDaily);
}else if(newValue.toString().equals("2")){ /* weekly */
Log.e("WEEKLY REFRESH", " ");
background_refresh.setSummary("Scores will be refreshed weekly");
AlarmManager manager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
manager.cancel(recurringDownloadDaily);
manager.cancel(recurringDownloadWeekly);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,10);
calendar.set(Calendar.MINUTE,00);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY * 7, recurringDownloadWeekly);
}else{ /* manually */
background_refresh.setSummary("Scores will be refreshed manually");
Log.e("MANUAL REFRESH", " ");
AlarmManager manager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
manager.cancel(recurringDownloadDaily);
manager.cancel(recurringDownloadWeekly);
}
return true;
}
};
background_refresh.setOnPreferenceChangeListener(refreshListener);
似乎正在发生的事情是当我选择前两个选项中的任何一个时,它会立即触发。我不确定为什么会发生这种情况,我在网上看了一些例子,它似乎与我写的相符。我试图安排每天上午10点刷新,或者在上午10点每7天刷新一次。