javaandroidbroadcastreceiveralarmringtone

How to stop the ringing of a triggered alarm?


This is MainActivity.java

package com.example.quizalarm;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Calendar;

import static android.app.PendingIntent.getBroadcast;

public class MainActivity extends AppCompatActivity{

    int nHour1, nHour2, nHour3, nHour4, nMinute1, nMinute2, nMinute3, nMinute4;
    Calendar cal;
    AlarmManager alarmMgr;
    PendingIntent alarmIntent;
    Intent intent;
    Button editButton, infoButton, stopButton, editAlarm1, editAlarm2, editAlarm3, editAlarm4;
    Switch alarmSwitch1, alarmSwitch2, alarmSwitch3, alarmSwitch4;
    TextView alarmText1, alarmText2, alarmText3, alarmText4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editButton = findViewById(R.id.editButton);
        infoButton = findViewById(R.id.infoButton);
        stopButton = findViewById(R.id.stopButton);
        alarmSwitch1 = findViewById(R.id.alarmSwitch1);
        alarmSwitch2 = findViewById(R.id.alarmSwitch2);
        alarmSwitch3 = findViewById(R.id.alarmSwitch3);
        alarmSwitch4 = findViewById(R.id.alarmSwitch4);
        alarmText1 = findViewById(R.id.alarmText1);
        alarmText2 = findViewById(R.id.alarmText2);
        alarmText3 = findViewById(R.id.alarmText3);
        alarmText4 = findViewById(R.id.alarmText4);
        editAlarm1 = findViewById(R.id.editAlarm1);
        editAlarm2 = findViewById(R.id.editAlarm2);
        editAlarm3 = findViewById(R.id.editAlarm3);
        editAlarm4 = findViewById(R.id.editAlarm4);


        stopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopRinging(1);
            }
        });
        editButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editAlarm1.getVisibility() == View.VISIBLE) {
                    editAlarm1.setVisibility(View.INVISIBLE);
                    editAlarm2.setVisibility(View.INVISIBLE);
                    editAlarm3.setVisibility(View.INVISIBLE);
                    editAlarm4.setVisibility(View.INVISIBLE);
                    editButton.setText("EDIT");
                } else {
                    editAlarm1.setVisibility(View.VISIBLE);
                    editAlarm2.setVisibility(View.VISIBLE);
                    editAlarm3.setVisibility(View.VISIBLE);
                    editAlarm4.setVisibility(View.VISIBLE);
                    editButton.setText("DONE");
                }
            }
        });

        infoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openDialog();
            }
        });


        alarmSwitch1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alarmSwitch1.isChecked()) {
                    Toast.makeText(MainActivity.this, "Alarm 1 Activated", Toast.LENGTH_SHORT).show();
                    startAlarm(1, nHour1, nMinute1);
                    editAlarm1.setClickable(false);
                } else {
                    Toast.makeText(MainActivity.this, "Alarm 1 Deactivated", Toast.LENGTH_SHORT).show();
                    cancelAlarm(1);
                    editAlarm1.setClickable(true);
                }
            }
        });

        alarmSwitch2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alarmSwitch2.isChecked()) {
                    Toast.makeText(MainActivity.this, "Alarm 2 Activated", Toast.LENGTH_SHORT).show();
                    startAlarm(2, nHour2, nMinute2);
                    editAlarm2.setClickable(false);
                } else {
                    Toast.makeText(MainActivity.this, "Alarm 2 Deactivated", Toast.LENGTH_SHORT).show();
                    cancelAlarm(2);
                    editAlarm2.setClickable(true);
                }
            }
        });

        alarmSwitch3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alarmSwitch3.isChecked()) {
                    Toast.makeText(MainActivity.this, "Alarm 3 Activated", Toast.LENGTH_SHORT).show();
                    startAlarm(3, nHour3, nMinute3);
                    editAlarm3.setClickable(false);
                } else {
                    Toast.makeText(MainActivity.this, "Alarm 3 Deactivated", Toast.LENGTH_SHORT).show();
                    cancelAlarm(3);
                    editAlarm3.setClickable(true);
                }
            }
        });

        alarmSwitch4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alarmSwitch4.isChecked()) {
                    Toast.makeText(MainActivity.this, "Alarm 4 Activated", Toast.LENGTH_SHORT).show();
                    startAlarm(4, nHour4, nMinute4);
                    editAlarm4.setClickable(false);
                } else {
                    Toast.makeText(MainActivity.this, "Alarm 4 Deactivated", Toast.LENGTH_SHORT).show();
                    cancelAlarm(4);
                    editAlarm4.setClickable(true);
                }
            }
        });
    }

    public void setTime1(View v) {
        cal = Calendar.getInstance();
        TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                nHour1 = hourOfDay;
                nMinute1 = minute;
                updateAlarmText(nHour1, nMinute1, alarmText1);
            }
        }, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), DateFormat.is24HourFormat(getApplication()));
        timePickerDialog.show();
    }

    public void setTime2(View v) {
        cal = Calendar.getInstance();
        TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                nHour2 = hourOfDay;
                nMinute2 = minute;
                updateAlarmText(nHour2, nMinute2, alarmText2);
            }
        }, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), DateFormat.is24HourFormat(getApplication()));
        timePickerDialog.show();
    }

    public void setTime3(View v) {
        cal = Calendar.getInstance();
        TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                nHour3 = hourOfDay;
                nMinute3 = minute;
                updateAlarmText(nHour3, nMinute3, alarmText3);
            }
        }, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), DateFormat.is24HourFormat(getApplication()));
        timePickerDialog.show();
    }

    public void setTime4(View v) {
        cal = Calendar.getInstance();
        TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                nHour4 = hourOfDay;
                nMinute4 = minute;
                updateAlarmText(nHour4, nMinute4, alarmText4);
            }
        }, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), DateFormat.is24HourFormat(getApplication()));
        timePickerDialog.show();

    }

    public void startAlarm(int requestCode, int nHour, int nMinute) {
        intent = new Intent(this, AlarmReceiver.class);
        alarmIntent = getBroadcast(this.getApplicationContext(), requestCode, intent, 0);
        alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
        cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, nHour);
        cal.set(Calendar.MINUTE, nMinute);
        cal.set(Calendar.SECOND, 0);

        if (cal.before(Calendar.getInstance())){
            cal.add(Calendar.DATE, 1);
        }

        assert alarmMgr != null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            alarmMgr.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), alarmIntent);
        } else {
            alarmMgr.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), alarmIntent);
        }
    }

    public void cancelAlarm(int requestCode) {
        intent = new Intent(this, AlarmReceiver.class);
        alarmIntent = PendingIntent.getBroadcast(this.getApplicationContext(), requestCode, intent, 0);
        alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);

        assert alarmMgr != null;
        alarmMgr.cancel(alarmIntent);
    }
    public void stopRinging(int requestCode){
        intent = new Intent(this, AlarmReceiver.class);
        alarmIntent = PendingIntent.getBroadcast(this.getApplicationContext(), requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    public void openDialog(){
        Dialog dialog = new Dialog();
        dialog.show(getSupportFragmentManager(), "dialog");
    }

    public void updateAlarmText (int nHour, int nMinute, TextView alarmText) {
        String timeTextHour = "";
        String timeTextMinute = "";
        if (nHour == 0){
            timeTextHour = "12";
        }
        if (nHour <= 12 && nHour != 0) {
            timeTextHour = String.valueOf(nHour);
        }
        if (nHour > 12) {
            timeTextHour = String.valueOf(nHour - 12);
        }
        if (nMinute < 10) {
            timeTextMinute += "0" + nMinute;
        } else {
            timeTextMinute = String.valueOf(nMinute);
        }
        if (nHour < 12){
            alarmText.setText(timeTextHour + ":" + timeTextMinute + " AM");
        } else {
            alarmText.setText(timeTextHour + ":" + timeTextMinute + " PM");
        }
    }
}

This is AlarmReceiver.java

package com.example.quizalarm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        Ringtone r = RingtoneManager.getRingtone(context, alarmUri);
        if (r.isPlaying()) {
            r.stop();
        } else {
            r.play();
        }
    }
}

This is AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.quizalarm">

    <application
        android:fullBackupContent="@xml/backup_descriptor"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">
        <activity android:name=".QuizActivity"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".AlarmReceiver" />
    </application>

</manifest>

My problem is in the stopRinging() method. I don't know how to stop the ringing of the triggered alarm. I tried recalling the AlarmReceiver in the stopRinging() method so that it will do r.stop() but it doesn't work, it's still ringing. What is the right way to stop the ringing?


Solution

  • Okay, I've found the solution to trigger the already ringing alarm to stop. Here's the link : https://github.com/JoshSibayan/AlarmClock.

    Basically, use a BroadcastReceiver(AlarmReceiver) and a Service(RingtonePlayingService). use putExtras to start or stop the ringing of the alarm in the Service through the BroadcastReceiver.

    Who ever is this github's creator, probably Josh Sibayan. I am greatly GREATLY Thankful to you for I have finished the application that I needed for our research project. Don't worry, I'm not thinking of publishing or distributing this, I've only done this for the sake of finishing my course.