How to set ringtone programmatically in android from sd card android example

Please follow and like us:

How to set ringtone programmatically in android from sd card android example

Learn how to set ringtone programmatically in android from SD card with easy and short android example code. Let’s explore it.

Add bellow permissions in AndroidMainifest.xml file

 <uses-permission android:name="android.permission.WRITE_SETTINGS"/>

Logic for set ringtone programmatically in android from SD card song path.

	File ringtoneFile = new File("Song path from sd card"); //sd-card path/songname.mp3

									ContentValues content = new ContentValues();
									content.put(MediaStore.MediaColumns.DATA,ringtoneFile.getAbsolutePath());
									content.put(MediaStore.MediaColumns.TITLE, "Song title");
									content.put(MediaStore.MediaColumns.SIZE, 215454);
									content.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
									//  content.put(MediaStore.Audio.Media.ARTIST, "Madonna");
									content.put(MediaStore.Audio.Media.DURATION, 230);
									content.put(MediaStore.Audio.Media.IS_RINGTONE, true);
									content.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
									content.put(MediaStore.Audio.Media.IS_ALARM, false);
									content.put(MediaStore.Audio.Media.IS_MUSIC, false);

									
									Uri Ringtone1 = Uri.parse("current song file path");
									//Insert it into the database
									Log.i("TAG", "the absolute path of the file is :"+
											ringtoneFile.getAbsolutePath());
									Uri uri = MediaStore.Audio.Media.getContentUriForPath(
											ringtoneFile.getAbsolutePath());




									context.getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + ringtoneFile.getAbsolutePath() + "\"",
											null);
									Uri newUri = context.getContentResolver().insert(uri, content);
									System.out.println("uri=="+uri);
									Log.i("TAG","the ringtone uri is :"+newUri);
									RingtoneManager.setActualDefaultRingtoneUri(
											context.getApplicationContext(), RingtoneManager.TYPE_RINGTONE,
											newUri);

Hope, you like our small and simple solution for set ringtone programmatically in android.

nirav kalola