Home » Android » How to loop / repeat the current ringtone in Android from an application?

How to loop / repeat the current ringtone in Android from an application?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am writing an application on android 4.0 which will play the current ringtone when I press a button.

But in the ringtone is played only one time. I need it to repeat for a few times.

My current code:

Uri notifi = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
final Ringtone r = RingtoneManager.getRingtone(c, notifi);
r.play();
How to&Answers:

Try this code I have used this before and able to play Ringtone continuously until you stop

try {
   Uri alert =  RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
  mMediaPlayer = new MediaPlayer();
  mMediaPlayer.setDataSource(this, alert);
  final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
 if (audioManager.getStreamVolume(AudioManager.STREAM_RING) != 0) {
 mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
 mMediaPlayer.setLooping(true);
 mMediaPlayer.prepare();
 mMediaPlayer.start();
}
} catch(Exception e) {
}   

Answer:

Tried the above codes on lollipop and only this worked for me

  //activating looping ringtone sound
    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
    player = MediaPlayer.create(this, notification);
    player.setLooping(true);
    player.start();

Answer:

You can have a timer regularly check if the ringtone is still playing. For example, every second:

mRingtone.play();
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimerTask() {
    public void run() {
        if (!mRingtone.isPlaying()) {
            mRingtone.play();
        }
    }
}, 1000*1, 1000*1);

Answer:

I have read that ringtone has to have ANDROID_LOOP tag. Ref: http://xanderx.com/2010/08/25/making-ringtones-loop-on-android/

You can also try to play this file using AudioManager and set it looping. Ref: http://developer.android.com/reference/android/media/MediaPlayer.html#setLooping(boolean)