javaandroidalarmringtone

How to stop ringtone alarm in Android?


I made an alarm play for notifications in Android. But how do you make a Stop Button in Android? Code to start the alarm :

public void playRingtone(View view) {
    try {
        Uri path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.song);
        RingtoneManager.setActualDefaultRingtoneUri(
                getApplicationContext(), RingtoneManager.TYPE_ALARM, path
        );
        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), path);
        r.play();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Solution

  •  RingtoneManager ringtoneManager = new RingtoneManager(getContext());
    
     public void playRingtone(View view) {
        try {
            Uri path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.song);
            ringtoneManager.setActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_ALARM, path);
            Ringtone r = ringtoneManager.getRingtone(getApplicationContext(), path);
            r.play();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void stopRingtone(){
       ringtoneManager.stopPreviousRingtone();
    }