我对如何停止AlarmManager有疑问。我想在“ x”小时开始,在“ y”小时停止,由用户设置。我知道“ .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);
}
答案 0 :(得分:0)
例如,当您创建警报管理器意图时,您可以在结束时间处传递一个额外的参数
alarmIntent.putExtra("end", System.currentTimeMillis() + 60*60*1000); //1 hour from current time
当然,您可以将结束时间替换为用户选择的时间,但必须以毫秒为单位