I am writing code for setting custom ringtone in android. Took help from other answers in stackoverflow. Here is the code.
private void setContactRingtone(String number) {
final Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// The columns used for `Contacts.getLookupUri`
final String[] projection = new String[]{
ContactsContract.Contacts._ID, ContactsContract.Contacts.LOOKUP_KEY
};
// Build your Cursor
final Cursor data = getContentResolver().query(lookupUri, projection, null, null, null);
data.moveToFirst();
try {
// Get the contact lookup Uri
final long contactId = data.getLong(0);
final String lookupKey = data.getString(1);
final Uri contactUri = ContactsContract.Contacts.getLookupUri(contactId, lookupKey);
if (contactUri == null) {
// Invalid arguments
return;
}
File file = new File(this.getFilesDir() + File.separator + "ringtone.mp3");
final String value = Uri.fromFile(file).toString();
final ContentValues values = new ContentValues(1);
values.put(ContactsContract.Contacts.CUSTOM_RINGTONE, value);
getContentResolver().update(contactUri, values, null, null);
Toast.makeText(getApplicationContext(), "Done!!!!!!!!!!!", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
// Don't forget to close your Cursor
data.close();
}
}
The code is not assigning the user defined ringtone to the contact. There are no exceptions generated.