Yunus Haznedar Yunus Haznedar - 18 days ago 5
Android Question

How to set duration for a ringtone?

I want to set duration of ringtones. For example I want to stop it when it's played for 30 seconds. Do you have any idea how to do that? Because ringtones have no

setDuration
method or something like that.

Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();

Answer

Use a countDownTimer as:

new CountDownTimer(long millisInFuture, long countDownInterval) {

     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
}.start();

You can use onTick and onFinish, so cancel the ringtone when timer finishes.

Hope this helps!