我正在使用警报管理器来显示来自应用程序的通知。我也在使用时间选择器设置特定时间。一切正常,但这只是第一次。例如,如果我将星期一设置为晚上8.30,则通知将仅在这一天显示。我想每天显示此通知。 下面是我的通知类。
public class Notifications extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
private TextView mTextView;
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notifications);
mTextView = findViewById(R.id.textView);
sharedPreferences=getSharedPreferences("notificat",Context.MODE_PRIVATE);
String time= sharedPreferences.getString("time","");
mTextView.setText(time);
ButtonsLogic();
}
public void ButtonsLogic(){
Button buttonTimePicker = findViewById(R.id.button_timepicker);
buttonTimePicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getSupportFragmentManager(), "time picker");
}
});
Button buttonCancelAlarm = findViewById(R.id.button_cancel);
buttonCancelAlarm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancelAlarm();
}
});
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
updateTimeText(c);
startAlarm(c);
}
private void updateTimeText(Calendar c) {
String timeText = "Przypomnienie ustawione na godzinę: ";
timeText += DateFormat.getTimeInstance(DateFormat.SHORT).format(c.getTime());
mTextView.setText(timeText);
sharedPreferences= getSharedPreferences("notificat",Context.MODE_PRIVATE);
SharedPreferences.Editor editor= sharedPreferences.edit();
editor.putString("time",mTextView.getText().toString());
editor.apply();
}
private void startAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
}
private void cancelAlarm() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
alarmManager.cancel(pendingIntent);
mTextView.setText("Usunięto przypomnienie");
}
这是解决方案
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);