Reputation: 41
I am attempting to make an Android program set the phone's ringtone. When I run the below code once, the ringtone is set correctly and works just fine. However, if I run the code more than once, the ringtone becomes silent. Any help in figuring this out would be extremely appreciated.
void setRingtone() {
//File path = Environment.getExternalStorageDirectory();
//File file = new File(path, "ringtone.mp3");
File file = new File("/sdcard/", "ringtone.mp3");
Uri mUri = Uri.parse("android.resource://com.*****.*****/" + R.raw.*****);
ContentResolver mCr = getContentResolver();
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "my ringtone");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/oog");
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
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, false);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
Uri newUri = mCr.insert(uri, values);
try {
RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE, newUri);
} catch (Throwable t) {}
}
Upvotes: 1
Views: 672
Reputation: 41
The problem was that RingtoneManager.setActualDefaultRingtoneUri adds the file path to a database with the identification as a ringtone. Since the file path was already in the database, there is some error and the value becomes null (if i understand correctly). That is why it only works the first time after setting. To fix this you need to delete the reference first. Here is the code to do so.
getContentResolver().delete(uri, MediaStore.MediaColumns.DATA
+ "=\"" + file.getAbsolutePath() + "\"", null);
Upvotes: 3