I want to change ringtone of given phone number programmatically. I have facing below mention issues.
1. Ringtone is not change on some Nougat device (LG k10, Samsung).
2. It is working fine below the Nougat device.
I am using below mention code to change the ringtone of phone number.
private fun funChangeRingtone(number: String) {
try {
// The Uri used to look up a contact by phone number
val lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, number)
// The columns used for `Contacts.getLookupUri`
val projection = arrayOf<String>(Contacts._ID, Contacts.LOOKUP_KEY)
// Build your Cursor
val data = contentResolver.query(lookupUri, projection, null, null, null)
data!!.moveToFirst()
try {
// Get the contact lookup Uri
val contactId = data.getLong(0)
val lookupKey = data.getString(1)
val contactUri = Contacts.getLookupUri(contactId, lookupKey) ?: // Invalid arguments
return
val file = File(/*storage + "/AudioRecorder",*/ audio /*+ ".mp3"*/)
file.setReadable(true, false);
var value: Uri
/* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
value = FileProvider.getUriForFile(this, null, file);
grantUriPermission("com.example", value, Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {*/
value = Uri.fromFile(file)/*.toString()*/
// }
// Apply the custom ringtone
val values = ContentValues()
values.put(Contacts.CUSTOM_RINGTONE, value.toString())
var permission = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
permission = Settings.System.canWrite(this)
} else {
permission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED
}
if (permission) {
val update = contentResolver.update(contactUri, values, null, null)
Log.d("update", update.toString())
}
} finally {
// Don't forget to close your Cursor
data.close()
}
} catch (e: Exception) {
e.printStackTrace()
}
}