setting audio file as Ringtone

Solution 1:

Audio is set as ringtone only once, but solution to this problem is - If you are trying to run the same code again, you'll be inserting a duplicate entry into MediaStore's table, but the SQLite database won't allow you. You have to either rename your file and add another instance of it, or go in, remove the entry, and then try again. So I removed that entry every time and then insert it again.

Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + k.getAbsolutePath() + "\"", null);
Uri newUri = getContentResolver().insert(uri, values);

RingtoneManager.setActualDefaultRingtoneUri(activity.this,
        RingtoneManager.TYPE_RINGTONE, newUri);

Solution 2:

Instead of deleting the previously inserted uri, you can reuse it:

    // check if file already exists in MediaStore
    String[] projection = {MediaStore.Audio.Media._ID};
    String selectionClause = MediaStore.Audio.Media.DATA + " = ? ";
    String[] selectionArgs = {ringtoneFile.getAbsolutePath()};
    Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, selectionClause, selectionArgs, null);
    Uri insertedUri;
    if (cursor == null || cursor.getCount() < 1) {
        // not exist, insert into MediaStore
        ContentValues cv = new ContentValues();
        cv.put(MediaStore.Audio.Media.DATA, ringtoneFile.getAbsolutePath());
        cv.put(MediaStore.MediaColumns.TITLE, ringtoneFile.getName());
        insertedUri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, cv);
    } else {
        // already exist
        cursor.moveToNext();
        long id = cursor.getLong(0);
        insertedUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
    }
    RingtoneManager.setActualDefaultRingtoneUri(context, type, insertedUri);

Solution 3:

RingtoneManager.setActualDefaultRingtoneUri(
Context,
RingtoneManager.TYPE_RINGTONE,
Uri
.parse("Media file uri"));

I think this will solve ur problem.