androidswitch-statementalarmmanagerandroid-calendartimepickerdialog

How can I turn off my alarm with a switch


i have a switch which triggers a TimePickerDialog to set an alarm. I want now that the alarm turns off when it is switched off. Also i want to set the alarm again when I switch it to on.

public class MainAddMedActivity extends AppCompatActivity {

    private TextView txtAlarmPrompt;
    private TimePickerDialog timePickerDialog;
    private Switch switchReminder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_add_med);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        this.txtAlarmPrompt = (TextView) findViewById(R.id.txtAlarmPrompt);
        this.switchReminder = (Switch) findViewById(R.id.switchReminder);

        switchReminder.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    openTimerPickerDialog(true);
                    timePickerDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            switchReminder.setChecked(false);
                        }
                    });
                }
            }
        });
    }

    private void openTimerPickerDialog(boolean is24HourView) {
        Calendar cal = Calendar.getInstance();

        timePickerDialog = new TimePickerDialog(
                MainAddMedActivity.this,
                onTimeSetListener,
                cal.get(Calendar.HOUR_OF_DAY),
                cal.get(Calendar.MINUTE),
                is24HourView);
        timePickerDialog.show();
    }

    TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            Calendar calNow = Calendar.getInstance();
            Calendar calSet = (Calendar) calNow.clone();

            calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
            calSet.set(Calendar.MINUTE, minute);
            calSet.set(Calendar.SECOND, 0);
            calSet.set(Calendar.MILLISECOND, 0);

            if (calSet.compareTo(calNow) <= 0) {
                calSet.add(Calendar.DATE, 1);
            }
            setAlarm(calSet);
        }
    };

    private void setAlarm(Calendar targetCal) {
        txtAlarmPrompt.setText(getString(R.string.txtPromptAlarm) + " " + targetCal.getTime());
        Intent intent = new Intent(getApplicationContext(), AlarmNotificationReceiver.class);
        final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, AlarmNotificationReceiver.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);

        ***switchReminder.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked = false) {
                    alarmManager.cancel(pendingIntent);
                }
            }
        });*** //This Part is wrong does not work
    }

Solution

  • Your OnCheckedChangeListener is not working, because of your if-statement.

    if (isChecked = false) will assign false to the variable isChecked before the if-statement is being run and so the body of your if-statement will be never be run, because isChecked will never be true.

    Using = will assign the right-hand-side as the new value of the left-hand-side, while == will evaluate 2 values against each other.

    Change your if-statement to:

    if (!isChecked) {
        alarmManager.cancel(pendingIntent);
    }
    

    You could also do:

    if (isChecked == false) {
        alarmManager.cancel(pendingIntent);
    }
    

    but it's considered bad practice to check if a boolean is either true or false by using if (myBoolean == true) or if (myBoolean == false) as an if evaluates booleans directly.

    To set the alarm again, you need an else on your if-statement where you can call alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);

    So the if-else would be something like this:

    if (!isChecked) {
        alarmManager.cancel(pendingIntent);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent); // Remember to change the time to a new time in millis.
    }