У меня есть сомнения по поводу того, как остановить AlarmManager.Я хотел бы начать с «х» часов и остановиться на «у» часов, установленных пользователем.Я знаю существование функции ".cancel", но я не знаю, как установить время остановки в часах "y".
onCreate
final EditText chooseTime = findViewById(R.id.etChooseTime);
chooseTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TimePickerDialog timePickerDialog = new TimePickerDialog(AlarmeAguaActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, final int hourOfDay, final int minutes) {
chooseTime.setText(hourOfDay + ":" + minutes);
Button btnIniciarNotificacao = findViewById(R.id.btnIniciarNotificacao);
btnIniciarNotificacao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
configuraAlarme(hourOfDay, minutes);
Toast.makeText(AlarmeAguaActivity.this, "Notificação ativa!", Toast.LENGTH_SHORT).show();
}
});
}
}, 0, 0, false);
timePickerDialog.show();
}
});
Button btnPararTimer = findViewById(R.id.btnPararTimer);
btnPararTimer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pararAlarme();
}
});
Стоп и пауза
private void configuraAlarme(int hora, int minuto) {
try {
alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmNotificationReceiver.class);
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
/* Aqui é aonde setamos o horário de início das notificações*/
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hora);
calendar.set(Calendar.MINUTE, minuto);
/*
* Nosso alarme vai funcionar de uma em uma hora de acordo c/ o
* horário pré definido pelo o usuário
* EXEMPLO = 1000 * 60 * 1 = notificação a cada 1 min.
* */
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60, alarmIntent);
} catch (Exception ex) {
Log.d(TAG, "configuraAlarme: ");
}
}
private void pararAlarme() {
Intent intent = new Intent(this, AlarmNotificationReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Toast.makeText(this, "Suas notificações foram canceladas!", Toast.LENGTH_SHORT).show();
alarmManager.cancel(sender);
}