0

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.

The_Martian
  • 3,684
  • 5
  • 33
  • 61

2 Answers2

0

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

if(ringtoneSound.isPlaying()){
        ringtoneSound.stop();
    }
The_Martian
  • 3,684
  • 5
  • 33
  • 61
  • The problem with this is that the playing call in a public void and the reset in the private void so they are not under one void [link](https://imgur.com/DXABXeK) image of the code. – Dominik Varga May 17 '20 at 01:27
  • Just paste your code here in stead of sharing an image. What is the role of the reset method in context with the ringtone object? Where would you like to call the stop? Just make the ringtone instance a class member variable, then call it anywhere in the class. – The_Martian May 18 '20 at 01:56
0

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();
    }
}

}

Chuanhang.gu
  • 870
  • 9
  • 13