Android studio Timer end Alarm sound playing problem with stop

502 views Asked by At

I create a timer app and that code was play the alarm sound but how can I stop it? xD I use that code for playing:

Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtone ringtoneSound = RingtoneManager.getRingtone(getApplicationContext(), ringtoneUri)

if (ringtoneSound != null) {
    ringtoneSound.play();
}

So I want to click the reset button and its stop, its how possible? Many thanks, Dominik.

2

There are 2 answers

2
The_Martian On BEST ANSWER

You can check first if the ringtone is playing, only then you stop it.

if(ringtoneSound.isPlaying()){
        ringtoneSound.stop();
    }
0
Chuanhang.gu On

After simple search, I thought Ringtone is register to Android OS. Only left a handle for you to do sth about operation.If you lose that handle, only way to stop is kill app. So I suggest you make ringtone single instance mode.Sth like below.

public class RingUtil {
private static RingUtil mInstance = null;
private Ringtone mRingtone;
private RingUtil(Context context) {
    Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    mRingtone = RingtoneManager.getRingtone(context.getApplicationContext(), ringtoneUri);
}
public static RingUtil getInstance(Context context) {
    if (null == mInstance) {
        mInstance = new RingUtil(context);
    }
    return mInstance;
}
public void play() {
    if (mRingtone.isPlaying()) {
        mRingtone.stop();
    }
    mRingtone.play();
}
public void stop() {
    if (mRingtone.isPlaying()) {
        mRingtone.stop();
    }
}

}