3

I have a mp3 file "a.mp3" on my sdcard. I want to set this as my phone ringtone..... Below is the code I found from different answers but when I run the code, the ringtone in changed to None, not a.mp3. Please help me. I am a beginner. Thanks in advance.

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/a.mp3";
    File k = new File(path, "a.mp3");

    ContentValues values = new ContentValues();
    values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
    values.put(MediaStore.MediaColumns.TITLE, "A");
    values.put(MediaStore.MediaColumns.SIZE, 210341);
    values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
    values.put(MediaStore.Audio.Media.ARTIST, "");
    values.put(MediaStore.Audio.Media.DURATION, 230);
    values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
    values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
    values.put(MediaStore.Audio.Media.IS_ALARM, false);
    values.put(MediaStore.Audio.Media.IS_MUSIC, false);

    // Insert it into the database
    Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
    Uri newUri = this.getContentResolver().insert(uri, values);

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

Also if I want the user to choose another ringtone, what should I do? I want to start an Intent (which will open File Explorer) and then I will get the path of that sound file. which I will save in the path String and will continue the same code. Please guide me how to start that intent too.

2 Answers2

0

For launching File Explorer and let user choose file you can use below Intent-

      Intent intent = new Intent();
      intent.setAction(Intent.ACTION_GET_CONTENT);
      intent.setType("file/*");
      startActivity(intent);

Check out this regarding your ringtone issue.

Community
  • 1
  • 1
Android Developer
  • 9,157
  • 18
  • 82
  • 139
0

this code works for me.

Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
                    getContentResolver().delete(uri, MediaStore.MediaColumns.DATA
                            + "=\"" + file.getAbsolutePath() + "\"", null);
Uri newUri = getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(FileActivity.this,
                            RingtoneManager.TYPE_RINGTONE, newUri);

It is likely that ringtone manager inserts uri to a database, and if that database already has the uri, then it will return null. All you need to do is delete the uri first, then insert it again.

cmnewfan
  • 129
  • 1
  • 9