gpt4 book ai didi

java - AlarmManager:设置停止通知的时间

转载 作者:行者123 更新时间:2023-12-02 05:51:42 32 4
gpt4 key购买 nike

我对如何停止 AlarmManager 有疑问。我想在“x”小时开始并在“y”小时停止,由用户设置。我知道“.cancel”功能的存在,但不知道如何设置“y”小时内的停止时间。

创建时

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

最佳答案

例如,当您创建警报管理器 Intent 时,您可以传递带有结束时间的额外参数

alarmIntent.putExtra("end", System.currentTimeMillis() + 60*60*1000); //1 hour from current time

当然,你可以将结束时间替换为用户选择的时间,但必须以毫秒为单位

关于java - AlarmManager:设置停止通知的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56043065/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com