How can I change the ringtone in android programmatically?
Asked Answered
F

1

21

I'm trying to write an app that (among other things) will change the user's ringtone based on their location.

However, I'm having difficulty setting the ringtone of my phone from within my app. I've been able to display a list of the phone's ringtones, and have been using the following code to try and set the ringtone:

RingtoneManager.setActualDefaultRingtoneUri(applicationContext, 
      RingtoneManager.TYPE_RINGTONE,
      MediaStore.Audio.Media.getContentUriForPath(settings.getRingtoneURI()));

Settings.System.putString(c.getContentResolver(), Settings.System.RINGTONE, 
      settings.getRingtoneURI());

where settings.getRingtoneURI() returns a string with the URI of the desired ringtone.

When I run this, I receive no errors but the ringtone does not change.

Any advice?

Ferrochromium answered 31/5, 2011 at 4:2 Comment(4)
Duplicate of #1272277Jewelfish
I actually saw that question prior to posting my own. However, I'm not trying to apply a ringtone by creating a URI from an audio source. I want to use one of the phone's preexisting ringtones. I'm able to display a dialog which lists the available ringtones, but for some reason the above code does not set the default ringtone to the user's selection.Ferrochromium
please refer the following question #1272277Lamellirostral
@dhams: That's the same question that John pointed out.Ferrochromium
I
2

The below code choose any random tone from the mobile for Incoming call.

            RingtoneManager rm = new RingtoneManager(context);
    Random random = new Random();

    int i = rm.getRingtonePosition(RingtoneManager
            .getActualDefaultRingtoneUri(context,
                    RingtoneManager.TYPE_RINGTONE));
    MyApplication.APPLICATION_SHARED_PREFERENCE.edit()
            .putInt(MyConstants.PHONE_RINGTONE_NUMBER, i).commit();
    int chanegToneNumber;
    Cursor cursor = rm.getCursor();

    while (true) {
        chanegToneNumber = random.nextInt(cursor.getCount());
        if (chanegToneNumber != i)
            break;
    }

    Log.d(TAG, "Tone: " + i);

    Log.d(TAG, "Tone total: " + cursor.getCount());

    while (cursor.moveToNext()) {

        if (i == cursor.getInt(cursor
                .getColumnIndex(MediaStore.MediaColumns._ID))) {
            RingtoneManager.setActualDefaultRingtoneUri(context,
                    RingtoneManager.TYPE_RINGTONE,
                    rm.getRingtoneUri(chanegToneNumber));
            break;
        }
    }
Instantaneous answered 19/9, 2012 at 1:21 Comment(2)
MyApplication.APPLICATION_SHARED_PREFERENCE.edit() .putInt(MyConstants.PHONE_RINGTONE_NUMBER, i).commit(); Please tell me the importance of this line ?Jennefer
Sritam Jagadev. Basically I am using this tone number in one more place. That's why I am saving in file. But here for you that may be a redundant. Thanks for a good question.Instantaneous

© 2022 - 2024 — McMap. All rights reserved.