Search code examples
androidinsertringtone

Efficient way for adding music to ringtone on Android


I have a problem about adding music (stored in sdcard) to ringtone of Android. I have the code here to insert it :

ContentValues values = new ContentValues();
    values.put(MediaStore.MediaColumns.DATA, filePath);
    values.put(MediaStore.MediaColumns.TITLE, songTitle);
    values.put(MediaStore.MediaColumns.SIZE, file.length());
    values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/" + fileType);
    values.put(MediaStore.Audio.Media.ARTIST, singerName);
    values.put(MediaStore.Audio.Media.DURATION, duration);
    values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
    values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
    values.put(MediaStore.Audio.Media.IS_ALARM, true);
    values.put(MediaStore.Audio.Media.IS_MUSIC, true);

    /* delete bug here */
    Uri uri = MediaStore.Audio.Media.getContentUriForPath(filePath);
    Uri newUri = context.getContentResolver().insert(uri, values);

    if (isRingtone)
        RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
    if (isSMS)
        RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, newUri);

After I have added the ringtone1 to Android setting, I add the ringtone to the setting again and then I have 2 ringtone1 in the ringtone list.

The weird thing is when I am inserting the ringtone to notification, it will be displayed in notification list only. But if I delete the ringtone, it will be deleted on both the phone ringtone list and notification ringtone list. The list which I did not set the ringtone after the deletion will be come to "unknown ringtone".

So I want to find a way to check if the ringtone already exists in the setting. Secondly, I want to find a way to get the uri of the ringtone which was added to the setting.

If you don't get the question, please send me a comment here. Sorry for my bad English. Thank you very much.


Solution

  • Do something like this to find if you have already added the URI that RingtoneManager use

    String[] columns = {
            MediaStore.MediaColumns.TITLE,
            MediaStore.MediaColumns._ID
    };
    
    String selection = MediaStore.Audio.Media.DATA + "=?";
    String selectionArgs[] = { k.getAbsolutePath() };
    
    Cursor cursor = context.getContentResolver().query(uri, columns, selection, selectionArgs, null);
    

    This will bring for you if you have already added it and to get the URI to use in setActualDefaultRingtoneUri()

    It s parse (uri+"/"+cursor.getString(1)); hope it helps