Reason why stopPreviousRingtone() is not stopping the ringtone
I found that it is only possible to stop a ringtone using RingtoneManager.stopPreviousRingtone() only if the Ringtone was created by the same RingtoneManager instance. An easy way to confirm this is to create an activity with a RingtoneManager and three buttons:
- Clicking the first button will use the
RingtoneManager to start a ringtone.
- Clicking the second button will call
stopPreviousRingtone() on the RingtoneManager.
- Clicking the third button will call
stopPreviousRingtone() on the completely different RingtoneManager instance.
After doing this, you should find that the ringtone will only stop if you click the second button.
Stopping a Ringtone if you have access to the original Ringtone instance
If you have access to the original Ringtone instance, you can just call the stop() method:
Ringtone ringtone = RingtoneManager.getRingtone(getActivity());
ringtone.play();
...
ringtone.stop();
Stopping Ringtones when keeping a reference to the original Ringtone is not possible
What you could try is to create a service which will load and play the ringtone when it was started and will stop the ringtone when it was destroyed. Here is an example:
public class RingtonePlayingService extends Service
{
private Ringtone ringtone;
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Uri ringtoneUri = Uri.parse(intent.getExtras().getString("ringtone-uri"));
this.ringtone = RingtoneManager.getRingtone(this, ringtoneUri);
ringtone.play();
return START_NOT_STICKY;
}
@Override
public void onDestroy()
{
ringtone.stop();
}
}
Then, you can start the ringtone in the background just by starting the service:
Intent startIntent = new Intent(context, RingtonePlayingService.class);
startIntent.putExtra("ringtone-uri", ringtoneUri);
context.startService(startIntent);
And, to stop the ringtone, just stop the service:
Intent stopIntent = new Intent(context, RingtonePlayingService.class);
context.stopService(stopIntent);