I'm quite new to Android development and I've decided to create a repeating alarm app where you'd choose when the cycle ends, like after 5 alarm bursts. I have set the alarm and all that, I have a button to cancel the alarm but I can't limit it so it stops automatically after that said amount of alarm bursts. Is there a way to do it? I want to be able to write how many bursts I want in the EditText
window, write the delay between the alarms and then press the button to set it.
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
private Double delay;
private int howManyTimes;
private EditText remaining;
private EditText iterator;
I want to store the amount of bursts in howManyTimes
.
My OnClickListener
looks like this (iterator is an EditText
where I write the number of bursts and remaining is an EditText
where I write the delay between the bursts):
public void onClick(View v) {
if (remaining.getText().toString().equals("") || remaining.getText().toString().equals(".")) {
delay = 0.0;
} else {
delay = (60 * 60 * 1000) * Double.parseDouble(remaining.getText().toString());
}
if (iterator.getText().toString().equals("") || iterator.getText().toString().equals(".")) {
howManyTimes = 0;
} else {
howManyTimes = Integer.parseInt(iterator.getText().toString());
}
if (howManyTimes > 0) {
double tmpDelay = delay;
int tmpIterator = howManyTimes;
updateTimeText(tmpIterator, tmpDelay);
startAlarm();
}
}
startAlarm()
looks like this:
private void startAlarm() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + delay.longValue(),
delay.longValue(), pendingIntent);
}
this is my broadcast receiver:
public class AlertReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder nb = notificationHelper.getChannelNotification();
notificationHelper.getManager().notify(1, nb.build());
}
}