5

In my android application, I am trying to play the current default ringtone onCreate of my activity. But the ringtone wouldn't just play completely and stop at arbitrary length each time.

Code is as simple as it could be, any help would be appreciated.

Uri currentUri = RingtoneManager.getActualDefaultRingtoneUri(this.context, 
    RingtoneManager.TYPE_RINGTONE);
Ringtone ringtone = RingtoneManager.getRingtone(this.context,currentUri);
if (ringtone != null){
    ringtone.play();
}
skbohra
  • 51
  • 4

2 Answers2

0

I am using TYPE_NOTIFICATION but appart from that my code was more or less exactly the same.

I found that playing the sound inside a new Handler helped in my case:

        Uri currentUri = RingtoneManager.getActualDefaultRingtoneUri(
                this.context, RingtoneManager.TYPE_RINGTONE);
        final Ringtone ringtone = RingtoneManager.getRingtone(this.context,
                currentUri);
        if (ringtone != null) {
            new Handler().post(new Runnable() {

                @Override
                public void run() {
                    ringtone.play();
                }
            });
        }

Why did this resolve the issue?

I believe that the RingtoneManager might use the UI thread to play the sound, so if the UI thread gets used to create/draw views or do calculations at the same time as the sound is played, it risks getting interrupted.

When using a new handler, the playback is queued until after the other operations, leaving the sound uninterrupted.

At least that is my perception: What exactly does the post method do?

Community
  • 1
  • 1
cYrixmorten
  • 7,110
  • 3
  • 25
  • 33
0

I had the same problem and above answer did not worked in my case.

But the ringtone worked normally in notification so I made a notification (with no content)

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationCompat.Builder mBuilder;
        mBuilder =
                new NotificationCompat.Builder(this)
                .setSound(alarmSound)
                .setVibrate(new long[]{1000,1000});

        mNotificationManager.notify(ANY_INT_WILL_DO_HERE, mBuilder.build());

It worked in my case. I hope this works for you as well.

But I'm not sure if it does any harm if I make this false notification just for playing ringtone

kwmaeng
  • 631
  • 2
  • 5
  • 20