Different sound each time when receive call [duplicate] - android

This question already has an answer here:
How can I change the ringtone in android programmatically?
(1 answer)
Closed 9 years ago.
I am wondering if it's possible to write an application that would randomly pick audio files (ringtones) from a predefined/configurable list and play it when I receive a call. So my ringtone would change even when I am called by the same person consecutively.
Is this possible and if so how complicated would it be? Would you need to take dependency on provider or OS into account?.

use "Rings Extended" http://www.androidapps.com/t/rings-extended
The solution is to get the resource file asset and write it to the sdcard 1st, before you give it to the content resolver for insertion.
File newSoundFile = new File("/sdcard/media/ringtone", "myringtone.oog");
Uri mUri = Uri.parse("android.resource://com.your.package/R.raw.your_resource_id");
ContentResolver mCr = app.getContentResolver();
AssetFileDescriptor soundFile;
try {
soundFile= mCr.openAssetFileDescriptor(mUri, "r");
} catch (FileNotFoundException e) {
soundFile=null;
}
try {
byte[] readData = new byte[1024];
FileInputStream fis = soundFile.createInputStream();
FileOutputStream fos = new FileOutputStream(newSoundFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
Then you can use the previously posted solution
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, newSoundFile.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "my ringtone");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/oog");
values.put(MediaStore.MediaColumns.SIZE, newSoundFile.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(newSoundFile.getAbsolutePath());
Uri newUri = mCr.insert(uri, values);
try {
RingtoneManager.setActualDefaultRingtoneUri(getContext(), RingtoneManager.TYPE_RINGTONE, newUri);
} catch (Throwable t) {
Log.d(TAG, "catch exception");
}
hope this helps

Related

Unable to set Ringtone/Notification Tone Programmatically in Android-11

I already know this question has been asked many times and answered, But this is something different. I am trying to set a Tone in android-11 and tried all the possible solutions over the internet and SO.
The most helpful question and answer which I found is How to set a file as a ringtone for Android 10? but still, I couldn't make it happen.
The thing is I am able to save my raw folder.mp3 file to local storage in my phone but when I try to set this as a tone I am getting exceptions and I am unable to set it. I have tried putting log and all only this below 2 lines not getting executed. If anyone can help that would be much appreciated. Thank you.
getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + k.getAbsolutePath() + "\"", null);
Uri newUri = getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(MainActivity.this, RingtoneManager.TYPE_RINGTONE, newUri);
I have already given storage permission and also runtime checked about all the permission. Also i have set android:requestLegacyExternalStorage="true"
my whole code
InputStream fIn = getBaseContext().getResources().openRawResource(R.raw.ring);
try {
byte[] buffer = new byte[fIn.available()];
fIn.read(buffer);
fIn.close();
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES) + "/Tone/";
String filename = "Ring.mp3";
if (!new File(path).exists()) {
new File(path).mkdirs();
}
try {
FileOutputStream save = new FileOutputStream(path + filename);
save.write(buffer);
save.flush();
save.close();
sendBroadcast(new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE", Uri.parse("file://" + path + filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "RingTone");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.MediaColumns.ARTIST, R.string.app_name);
values.put(MediaStore.Audio.Media.IS_RINGTONE, Boolean.valueOf(true));
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, Boolean.valueOf(false));
values.put(MediaStore.Audio.Media.IS_ALARM, Boolean.valueOf(false));
values.put(MediaStore.Audio.Media.IS_MUSIC, Boolean.valueOf(false));
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(MainActivity.this, RingtoneManager.TYPE_RINGTONE, newUri);
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e2) {
e2.printStackTrace();
return false;
}
} catch (IOException e3) {
e3.printStackTrace();
return false;
}
Also i have tried with another method but getting same result like unable to set as ringtone
Uri newUri = getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
try (OutputStream os = getContentResolver().openOutputStream(newUri)) {
//copy your file from asset into os here
int size = (int) f.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(f));
buf.read(bytes, 0, bytes.length);
buf.close();
os.write(bytes);
os.close();
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception ignored) {
ignored.printStackTrace();
}
}

Created file for ringtone doesn't have any sound

I made my app to get file from Raw folder and set that file as Ringtone.
But there is a problem, the file is created and set as ringtone: http://prntscr.com/2so80e
But file does not have any sound, and idk why I am guessing by default my device is playing another ringtone.
Here is my code:
case 64:
String path = "android.resource://" + getPackageName() + "/"+R.raw.fusrodah;
File k= new File(path);
Log.i("OUTPUT", path);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k .getPath());
values.put(MediaStore.MediaColumns.TITLE, "Fusrodah File");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "Testing");
values.put(MediaStore.MediaColumns.SIZE, 215454);
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);
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(Context.this,
RingtoneManager.TYPE_RINGTONE, newUri);
break;
What Am I doing wrong?
Is there something that I am missing?
I have all permissions, file is created but doesn't have any sound.
It looks like you should copy your file to SD-card firstly, then use this copy as ringtone. Here full code sample (I have file "kalimba.mp3" in my assets):
private int size;
private static final int BUFFER_LEN = 1024;
private void copyFile(AssetManager assetManager, String fileName, File out) throws FileNotFoundException, IOException {
size = 0;
FileOutputStream fos = new FileOutputStream(out);
InputStream is = assetManager.open(fileName);
int read = 0;
byte[] buffer = new byte[BUFFER_LEN];
while ((read = is.read(buffer, 0, BUFFER_LEN)) >= 0) {
fos.write(buffer, 0, read);
size += read;
}
fos.flush();
fos.close();
is.close();
}
#Override
public void onClick(View arg0) {
AssetManager assetManager = getAssets();
File file = new File(Environment.getExternalStorageDirectory(),
"/myRingtonFolder/Audio/");
if (!file.exists()) {
file.mkdirs();
}
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/myRingtonFolder/Audio/";
File out = new File(path + "/", "kalimba.mp3");
if(!out.exists()){
try {
copyFile(assetManager, "kalimba.mp3", out);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, out.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "name");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.MediaColumns.SIZE, out.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, true);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(out.getAbsolutePath());
ContentResolver mCr = getContentResolver();
Uri newUri = mCr.insert(uri, values);
try {
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, newUri);
Settings.System.putString(mCr, Settings.System.RINGTONE,
newUri.toString());
}
catch (Throwable t)
{
//TODO Handle exception
}
}

Android: Getting cannot be resiolved to a typr when trying to use RingtunesstarwarsActivity class

I created a test project with a methed called testringtone(), that sets a ringtones. It ran fine. When I copied this method in another project, I get a error thats says RingtunesstarwarsActivity cannot be resolved to a type, the line is
RingtunesstarwarsActivity.this.getPackageName()+ "/" + "raw/blasters";
Uri mUri = Uri.parse(strUri);.
This works fine in my test project.
complete
method void testringtone()
{
File newSoundFile = new File("/sdcard/", "myringtone.oog");
ERROR HERE ///////////////////////////////////////////////////
String strUri = "android.resource://"+
RingtunesstarwarsActivity.this.getPackageName()+ "/" + "raw/blasters";
Uri mUri = Uri.parse(strUri);
/////////////////////////////
ContentResolver mCr = getContentResolver();
AssetFileDescriptor soundFile;
try {
soundFile= mCr.openAssetFileDescriptor(mUri, "r");
} catch (FileNotFoundException e) {
soundFile=null;
}
try {
byte[] readData = new byte[1024];
FileInputStream fis = soundFile.createInputStream();
FileOutputStream fos = new FileOutputStream(newSoundFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
//////////////////////////////////////////
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, newSoundFile.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "my ringtone");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/oog");
values.put(MediaStore.MediaColumns.SIZE, newSoundFile.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(newSoundFile.getAbsolutePath());
Uri newUri = mCr.insert(uri, values);
try {
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, newUri);
} catch (Throwable t) {
// Log.d(TAG, "catch exception");
}
///////////////////////////////////////
} // end methed
It seems like you forgot to rename your code to reference your new actvity. Sounds like RingtunesstarwarsActivity is part of the old code and you haven't done the refactoring needed to bring everything up to date.
Either way, I don't even think you need the ClassName.this prefacing getPackageName() unless testringtone() is inside an inner class of some sort, such as an onClickListener.

Android/MonoDroid custom Ringtones question

I am trying to figure out how to take an audio file from the Assets folder (included as an AndroidAsset) and add it to the list of Ringtones you see when you make this call:
this.StartActivity(new Intent(Android.Media.RingtoneManager.ActionRingtonePicker));
I am adding the ringtone via this call:
InputStream inputstream = Assets.Open("filename.mp3");
Does anyone know how this is accomplished? I have been searching all over and haven’t figured it out. Thank you
Something like this:
private void setAsRingtone(){
try {
//Open the InputStream from the Assets
InputStream fis = Assets.Open("filename.mp3");
if (fis == null)
return;
//Open a File to save the ringtone in the SD (/sdcard/Android/data/com.your.package/)
File path = new
File(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Android/data/com.your.package/");
if(!path.exists())
path.mkdirs();
//Create the proper file
File f = new File(path, "YourTitle" + ".mp3");
//Dump the InputStream in the File
OutputStream fos = new FileOutputStream(f);
byte[] buf =new byte[1024];
int len;
while((len=fis.read(buf))>0){
fos.write(buf,0,len);
}
fos.close();
fis.close();
//Here are the metadata of the ringtone
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, f.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "YourTitle");
values.put(MediaStore.MediaColumns.SIZE, f.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, "YourArtist");
//values.put(MediaStore.Audio.Media.DURATION, ""); This is not needed
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);
//We put in the DDBB of MediaStore
Uri uri =
MediaStore.Audio.Media.getContentUriForPath(f.getAbsolutePath());
Uri newUri = getBaseContext().getContentResolver().insert(uri, values);
//Set as default
RingtoneManager.setActualDefaultRingtoneUri(
getBaseContext(),
RingtoneManager.TYPE_RINGTONE,
newUri);
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}

How to set ringtone in Android from my activity?

I'm trying to find a way to set a new default ringtone by code from my Android activity.
I have already downloaded the ringtone into a bytearray.
Finally, I managed to set the default ringtone to one that i downloaded.
The download code is not included below, only what was needed to set it as default ringtone.
File k = new File(path, "mysong.mp3"); // path is a file to /sdcard/media/ringtone
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "My Song title");
values.put(MediaStore.MediaColumns.SIZE, 215454);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, "Madonna");
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(
myActivity,
RingtoneManager.TYPE_RINGTONE,
newUri
);
Anyway, I do not totally understand what this code is doing.
The Ringtone manager needs a uri to the file that is to be set as new ringtone. But this uri can not be directly to the sdcard like "/sdcard/media/ringtones/mysong.mp3". That does not work!
What you need is the external file uri of the file which could be something like
"/external/audio/media/46"
The 46 is the id of the column in the MediaStore database, so thats why you need to add the sdcard file into the database first.
Anyway, how does mediastore maintain its ids? This number can get really high, as you do this operation many times.
Do i need to delete this row my self? Problem is that some times i dont even controll the deleting of the file since it can be deleted directly from the sdcard with a filebrowser.
Answer By Vidar is too long and it adds duplicate entries every time you want to set a song as ringtone . Instead you should try this
Uri newUri=Uri.parse("content://media/external/audio/media/"+ID);
try {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
}
catch (Throwable t) {
}
public void setRingtone() {
String ringtoneuri = Environment.getExternalStorageDirectory().getAbsolutePath() + "/media/ringtone";
File file1 = new File(ringtoneuri);
file1.mkdirs();
File newSoundFile = new File(ringtoneuri, "myringtone.mp3");
Uri mUri = Uri.parse("android.resource://globalapps.funnyringtones/raw/sound_two.mp3");
ContentResolver mCr = this.getContentResolver();
AssetFileDescriptor soundFile;
try {
soundFile = mCr.openAssetFileDescriptor(mUri, "r");
} catch (FileNotFoundException e) {
soundFile = null;
}
try {
byte[] readData = new byte[1024];
FileInputStream fis = soundFile.createInputStream();
FileOutputStream fos = new FileOutputStream(newSoundFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, newSoundFile.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "my ringtone");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.MediaColumns.SIZE, newSoundFile.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(newSoundFile.getAbsolutePath());
Uri newUri = mCr.insert(uri, values);
try {
Uri rUri = RingtoneManager.getValidRingtoneUri(this);
if (rUri != null)
ringtoneManager.setStopPreviousRingtone(true);
RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE, newUri);
Toast.makeText(this, "New Rigntone set", Toast.LENGTH_SHORT).show();
} catch (Throwable t) {
Log.e("sanjay in catch", "catch exception"+e.getMessage());
}
}
You can use the built-in RingtonePreference class. AndroidGuys has a nice tutorial on this here.
This is the code i used! i hope it helps..
This is also the link.
String exStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();
String path=(exStoragePath +"/media/alarms/");
saveas(RingtoneManager.TYPE_RINGTONE);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+path+filename+".mp3"
+ Environment.getExternalStorageDirectory())));
File k = new File(path, filename);
ContentValues values = new ContentValues(4);
long current = System.currentTimeMillis();
values.put(MediaStore.MediaColumns.DATA, path + filename );
values.put(MediaStore.MediaColumns.TITLE, filename );
values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
//new
values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
// Insert it into the database
this.getContentResolver()
.insert(MediaStore.Audio.Media.getContentUriForPath(k
.getAbsolutePath()), values);
HAPPY CODING!
I cannot comment the solution because I don't have enough reputation on stack overflow ... I want just add a way to add the audio file into media database without accessing directly to the database and hence avoiding to get duplicates.
The solution is based on MediaScannerConnection, this is the code I used:
String[] files = { audioFullPath };
MediaScannerConnection.scanFile(
getApplicationContext(),
files,
null,
new OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Log.v("myapp", "file " + path + " was scanned seccessfully: " + uri);
}
}
);
provide intent for ringtone selection.
final Uri currentTone= RingtoneManager.getActualDefaultRingtoneUri(MainActivity.this, RingtoneManager.TYPE_ALARM);
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_RINGTONE);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Tone");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentTone);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
startActivityForResult(intent, 999);
then catch the result of selection in onActivityResult.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 999 && resultCode == RESULT_OK){
Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
txtView.setText("From :" + uri.getPath());
//Set selected ringtone here.
RingtoneManager.setActualDefaultRingtoneUri(
this,
RingtoneManager.TYPE_RINGTONE,
uri
);
}
}
I have try these code its help
private void setRingtone(Context context, String path) {
if (path == null) {
return;
}
File file = new File(path);
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
String filterName = path.substring(path.lastIndexOf("/") + 1);
contentValues.put(MediaStore.MediaColumns.TITLE, filterName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
contentValues.put(MediaStore.MediaColumns.SIZE, file.length());
contentValues.put(MediaStore.Audio.Media.IS_RINGTONE, true);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(path);
Cursor cursor = context.getContentResolver().query(uri, null, MediaStore.MediaColumns.DATA + "=?", new String[]{path}, null);
if (cursor != null && cursor.moveToFirst() && cursor.getCount() > 0) {
String id = cursor.getString(0);
contentValues.put(MediaStore.Audio.Media.IS_RINGTONE, true);
context.getContentResolver().update(uri, contentValues, MediaStore.MediaColumns.DATA + "=?", new String[]{path});
Uri newuri = ContentUris.withAppendedId(uri, Long.valueOf(id));
try {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newuri);
Toast.makeText(context, "Set as Ringtone Successfully.", Toast.LENGTH_SHORT).show();
} catch (Throwable t) {
t.printStackTrace();
}
cursor.close();
}
}
If the accepted answer is not working then use this:
MediaStore.Audio.Media.INTERNAL_CONTENT_URI
instead of this:
MediaStore.Audio.Media.getContentUriForPath()
while inserting values into the database.
For example :
// Defining ringtone.....
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "Sonify");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
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);
// Setting ringtone....
getContentResolver().delete(MediaStore.Audio.Media.INTERNAL_CONTENT_URI,MediaStore.Audio.Media.TITLE + " = \"Sonify\"",null);
// To avoid duplicate inserts
Uri ringUri = getContentResolver().insert(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, values);
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM, ringUri);
Dont forgot to add
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
Use this function to set Ringtone
private void setAsRingtone(String musicId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.System.canWrite(this)) {
Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Long.parseLong(musicId));
RingtoneManager.setActualDefaultRingtoneUri(
this,
RingtoneManager.TYPE_RINGTONE,
uri
);
Toast.makeText(this, "Ring set successfully", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
Music Id can be obtained from Cursor. Hope you know it, or
Check it here
That works for me even in android S
,hope its help to you in set ringtone in android programmatically
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, uri);
I found this code from the Media application from Android.
Settings.System.putString(resolver,
Settings.System.RINGTONE, ringUri.toString());
this works form my.

Categories

Resources