How can I change the ringtone in android programmatically?

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;
        }
    }

Leave a Comment